I am looking to build a script that will log in to multiple servers using a host file and run uptime, hostname -I and hostname

Script so far

echo"" ; 
echo "hostname:" $(ssh $HOST hostname) ;
echo "IP:" $(ssh $HOST hostname -I) ;
echo "uptime" $(ssh $HOST uptime) ;
echo"" ;

What would be the best way to accomplish my goal?

closed as off-topic by Rui F Ribeiro, msp9011, telcoM, Archemar, Jeff Schaller Aug 11 '18 at 13:22

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Requests for learning materials (tutorials, how-tos etc.) are off topic. The only exception is questions about where to find official documentation (e.g. POSIX specifications). See the Help Center and our Community Meta for more information." – Rui F Ribeiro, msp9011, telcoM, Archemar
If this question can be reworded to fit the rules in the help center, please edit the question.

  • It's probably way overkill, but nagios does that as part of its monitoring. – JohnP Aug 10 '18 at 21:06
  • What is your goal? You want all this information spit into the terminal or logged to a file? Sent to an API? Do you have ssh authorized keys setup on each host or will you need to enter a password? – Jesse_b Aug 10 '18 at 21:11
  • This looks like job for Ansible. There is very quick howto which should be sufficient for this task: www.ansible.com/overview/how-ansible-works – Jaroslav Kucera Aug 11 '18 at 7:06
  • I want the information to display on the terminal and I do have SSH keys set up on each host – jabur Aug 13 '18 at 16:34

Assuming you just want all output in the terminal:



while read -r host; do
    hostname=$(ssh "${username}@${host}" hostname)
    ip_addr=$(ssh "${username}@${host}" hostname -I)
    uptime=$(ssh "${username}@${host}" uptime)
        echo "Hostname:?$hostname"
        echo "IP:?$ip_addr"
        echo "uptime:?$uptime"
    } | column -s\? -t
done <"$hosts_file"

This will loop through each line of your hosts_file, assigning the whole line to host. Then it will set the hostname, ip_addr, and uptime to the corresponding results on the remote machine. It will then echo those results in a columnized format.

  • This is exactly what I was looking for, thanks Jesse – jabur Aug 13 '18 at 16:25
  • If I wanted to use ssh keys I could just append -i /path/to/key after ssh correct? – jabur Aug 13 '18 at 16:51

Try (assuming your hosts in hostlist have a correct authentication set up)

while read HOST
  do { read HN; read IP; read UP; printf "hostname: %s\nIP: %s\nuptime: %s\n" "$HN" "$IP" "$UP"; } <<< "$(ssh $HOST  "hostname; hostname -I; uptime")"
  done < hostlist

Not the answer you're looking for? Browse other questions tagged or ask your own question.