I am very new to shell scripting, and started writing a script today. I am trying to read a server name from a list that stores server name and passing each server name to get the uptime. What i would to achieve is that, i should get a file with server names along with their uptimes on a separate line.
For example:
Server1 Uptime
server2 Uptime
..and so on
My script:
server_list=`/tmp/hosts.list`
for server in $server_list
do
while read line
do
cut -f1 -d" " //hosts.list has other info like IP address
upt=`/usr/local/bin/ssh $server uptime`
printf $server $upt
done<$server
done
when i run the script i get the following error:
/tmp/hosts.list[1] : server1: not found
/tmp/hosts.list[2] : server2: not found
# First column goes in server, all the rest go in OTHERSTUFF
while read SERVER OTHERSTUFF
do
/usr/local/bin/ssh "$SERVER" printf "${SERVER}: " ';' uptime
done < /tmp/hosts.list
This will print the server's name on the server itself, then run uptime, doing everything in one neat operation with no backticks whatsoever. The quotes around the semicolon are mandatory -- without that, uptime will run locally instead of being considered part of the ssh command...
the updates you made to the script displays only one row and i wanted all 50 servers to be displayed.
My changes are not working either:
server_list='/tmp/hosts.list'
for SERVER in $server_list
do
while read line
do
/usr/local/bin/ssh "$SERVER" printf "${server} : " ';' uptime
done < $server_list
done
Errors i am getting:
ssh: /tmp/hosts.list: no address associated with name
ssh: /tmp/hosts.list: no address associated with name
ssh: /tmp/hosts.list: no address associated with name
.....
My suggestion was not a skeleton or pseudocode, I expected it to work as-is and you didn't need to modify it to add extra loops. It already had a loop which read servers from your server file one by one and fed them into ssh individually. Did you try my original, unmodified code?
$server_list is a file, therefore, 'for x in $server_list' makes no sense. You read from files.
server_list='/tmp/hosts.list'
while read SERVER
do
/usr/local/bin/ssh "$SERVER" printf "${SERVER} : " ';' uptime
done < $server_list
Thanks itkamaraj for the help! I made little changes to the script where the contents of the output.txt are being to my email address. So far everything works perfectly.
TODAY=`date "+%Y%m%d"`
export TODAY
SERVERS=$(cat /tmp/hosts.list)
for i in $SERVERS;
do
uptime=$(ssh $i uptime | cut -f1 -d",")
echo "$i $uptime" >> uptimes_${TODAY}.txt
done
cat uptimes_${TODAY}.txt | mailx -s "Uptimes for `date`" myemail@email.com
I am also trying to think of implementing the following.
If i run the script through crontab on Monday morning, i would like the script to print only the servers who have been up for more than one day, this way only the servers that didnt get rebooted will be mailed to my email address. Any thoughts on how i should be handling? Really appreciate all your help so far.
Cheers!