I am working on a bash script to retrieve uptime of a list of servers. It just reads from a file and executes a remote command on the server. Some servers may have been up for a long time while some may have just been rebooted. I was using something very simple:
uptime | awk '{print \$2,\$3,\$4}'
This works if the server has been up for at least a day, but if it's been up only for a few hours the output from uptime doesn't include the work days, and just uses an hour:minute format.
I found something that I quite like, but can't seem to escape it properly in the ssh command, let alone trying to pass it in the bash script:
uptime | awk -F'( |,|:)+' '{d=h=m=0; if ($7=="min") m=$6; else {if ($7~/^day/) {d=$6;h=$8;m=$9} else {h=$6;m=$7}}} {print d+0,"days,",h+0,"hours,",m+0,"minutes."}'
I have tried several things, but this to me should work and can't seem to figure out what I am missing:
ssh user@IP "uptime | awk -F'( |,|:)+' '{d=h=m=0; if (\$7==\"min\") m=\$6; else {if (\$7\~\/^day\/) {d=\$6;h=\$8;m=\$9} else {h=\$6;m=\$7}}} {print d+0,\"days,\",h+0,\"hours,\",m+0,\"minutes.\"}'"
The output I get is:
awk: {d=h=m=0; if ($7=="min") m=$6; else {if ($7\~\/^day\/) {d=$6;h=$8;m=$9} else {h=$6;m=$7}}} {print d+0,"days,",h+0,"hours,",m+0,"minutes."}
awk: ^ backslash not last character on line
In the end I am trying to put this in a bash script that is something like this:
while IFS= read -r server; do
ssh -tt user@$server "uptime command" < /dev/null >> /home/user/uptime
done < "$file"