Home > Mobile >  SSH into multiple servers and compare timestamps of each server
SSH into multiple servers and compare timestamps of each server

Time:07-28

I need to add the timestamp of all remote servers as part of output and check & comapre whether the timestamp is the same or not,

I am able to print the machine IP and date.

#!/bin/bash

all_ip=(192.168.1.121 192.168.1.122 192.168.1.123)

for ip_addr in "${all_ip[@]}"; do
  aws_ip=$"ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'"
  date=date
  sshpass -p "password" ssh root@$ip_addr "$aws_ip & $date"
  echo "==================================================="
done

Getting Output as :

Wed 27 Jul 2022 05:48:15 AM PDT
192.168.1.121
===================================================
Wed Jul 27 05:48:15 PDT 2022
192.168.1.122
===================================================
Wed Jul 27 05:48:15 PDT 2022
192.168.1.123
===================================================

How to check whether the time ( ignoring seconds ) of all machines is the same or not ,

eg: (Wed 27 Jul 2022 05:48:15 || Wed 27 Jul 2022 05:48:15 || Wed 27 Jul 2022 05:48:15)

Expected Output:

|| Time are in sync on all machines ||

|| Time are not in sync on all machines || # or if not sync

Wed 27 Jul 2022 05:48:15 AM PDT
192.168.1.121
===================================================
Wed Jul 27 05:48:15 PDT 2022
192.168.1.122
===================================================
Wed Jul 27 05:48:15 PDT 2022
192.168.1.123
===================================================

CodePudding user response:

First, you may adjust your "date" command as folow in order to exclude the seconds:

date  %Y-%m-%d_%H:%M  

Then, simply grep your output and validate that all the timestamps are identical. You may dump in a temporary file or any other way. Ex:

grep [aPatternSpecificToTheLinewithTheDate] [yourTemporaryFile] | sort | uniq | wc -l

If the result is 1, it means that all the timestamps are identical. However you will have to deal with the corner case where the minute shift while you are fetching the time form all your servers.

CodePudding user response:

How to check whether the time ( ignoring seconds )

tmpdir=$(mktemp -d)
trap 'rm -r "$tmpdir"' EXIT
for ip in "${allips[@]}"; do
  # Do N connections, in paralllel, each one writes to a separate file.
  sshpass -p "password" ssh root@"$ip" "date  %Y-%m-%d_%H:%M" > "$tmpdir/$ip.txt" &
done
wait

times=$(
  for i in "$tmpdir"/*.txt; do
     # print filename with file contents.
     echo "$i $(<$i)"
  done |
  # Sort them on second column
  sort -k2 | 
  # Uniq on second field
  uniq -f 2
)
echo "$times"
timeslines=$(wc -l <<<"$times")
if ((timeslines == 1)); then
   echo "YAY! minutes on all servers the same"
fi
  • Related