shell script to ssh remote machines and print the output of the top command shell script to ssh remote machines and print the output of the top command unix unix

shell script to ssh remote machines and print the output of the top command


When you do

ssh host$i "top -n1 -b | head -n 15>> ~/mysh/top_out"

you’re writing the output to ~/mysh/top_out on the remote host, not the local machine. The remote host might not be using the same physical home directory as your local machine. If you have NFS or something sharing your home directory on some machines but not all, then you’d see the symptoms you described.

Try doing

ssh host$i "top -n1 -b | head -n 15" >> ~/mysh/top_out

instead, or to make things slightly cleaner, maybe even

#!/bin/bashfor i in $(seq 1 8); do    (echo "host$i"     ssh host$i "top -n1 -b | head -n 15") >> ~/mysh/top_out    echo "done host$i"done


you can try an expect script to save the output of each hosts after it connects to it, you can also add more commands to it, p.s. : this assumes you have the same username and password for all hosts :

#/usr/bin/expect -f#write your hosts on a new line inside a file and save it in your workging directory as:#host 1#host 2#host 3#user '' for password if it contains special chars#pass arguments to the script as ./script $username '$password' $hosttxtset user [lindex $argv 0]set pass [lindex $argv 1]#pass path to txt file with line separated hostsset fhost [lindex $argv 2]#set this to the  path where you need to save the output e.g /home/user/output.txtset wd "/home/$user/log.txt"#open hosts file for parsingset fhosts [open $fhost r]exec clear#set loguser 1proc get_top {filename line user pass} {     spawn ssh -l $user $line      expect {          "$ " {}      "(yes/no)? " {            send "yes\r"            expect -re "assword:|assword: "            send "$pass\r"      }     -re "assword:|assword: " {            send "$pass\r"      }     default {        send_user "Login failed\n"     exit 1    }  }  expect "$ " {}  send "top -n1 -b | head -n 15\r"  expect -re "\r\n(.*)\r(.*)(\\\$ |# )"  {       set outcome "$expect_out(1,string)\r"       send "\r"  }  puts $filename "$outcome\n\n-------\n"} while {[gets $fhosts line] !=-1} {       set filename [open $wd "a+"]       get_top $filename $line $user $pass       close $filename }


Check if the hosts for which you are not getting the output is showing following error:

TERM environment variable not set.

If you are getting this error for some of the hosts you can try following command:

ssh user@host "screen -r; top" >> file_where_you_want_to_save_output