Red Hat System Administration II
Use loops to efficiently print the hostname from multiple servers.
Outcomes
Create a
forloop to iterate through a list of items from the command line and in a shell script.
As the student user on the workstation machine, use the lab command to prepare your system for this exercise.
This command prepares your environment and ensures that all required resources are available.
[student@workstation ~]$ lab start console-commands
Instructions
Use the
sshandhostnamecommands to print the hostname of theserveraandserverbmachines to standard output.[student@workstation ~]$
ssh student@servera hostnameservera.lab.example.com [student@workstation ~]$ssh student@serverb hostnameserverb.lab.example.comCreate a
forloop to execute thehostnamecommand on theserveraandserverbmachines.[student@workstation ~]$
for HOST in servera serverb do ssh student@${HOST} hostname doneservera.lab.example.com serverb.lab.example.comCreate a shell script in the
/home/student/bindirectory to execute the sameforloop. Ensure that the script is included in thePATHenvironment variable.Create the
/home/student/bindirectory to store the shell script, if the directory does not exist.[student@workstation ~]$
mkdir ~/binVerify that the
binsubdirectory of your home directory is in yourPATHenvironment variable.[student@workstation ~]$
echo $PATH/home/student/.local/bin:/home/student/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/student/.venv/labs/binCreate a shell script called
printhostname.shin the/home/student/bindirectory to perform theforloop, and add the following content in the file.[student@workstation ~]$
vim ~/bin/printhostname.sh#!/usr/bin/bash #Execute for loop to print server hostname. for HOST in servera serverb do ssh student@${HOST} hostname done exit 0Give the created script executable permission.
[student@workstation ~]$
chmod +x ~/bin/printhostname.shRun the script from your home directory.
[student@workstation ~]$
printhostname.shservera.lab.example.com serverb.lab.example.comVerify that the exit code of your script is 0.
[student@workstation ~]$
echo $?0