Although I am not a system administrator, I do have to make sure that the date/time on many different servers is correct. For some reason, the time on these servers keeps getting off by between 15 and 30 minutes. I use to simply write the sudo date -s command to reset the date but I eventually got tired of doing that. Now I use the following bash script:


#!/bin/bash
# If this script wasn't run as SUDO, do it.
if [ "$(id -u)" != "0" ]; then
  MY_PATH="$( cd "$( dirname "$0" )" && pwd )/$(basename $0)"    # Path to this script.
  sudo $MY_PATH;
else
  echo
  echo "+------------------------------+";
  echo "| REMOTE SERVER AUTHENTICATION |";
  echo "+------------------------------+";
  read -p "IP Address:  " IP;
  read -p "Username:  " USERNAME;
  ssh $USERNAME@$IP "echo \\\"\`date\`\\\"" | xargs date -s;
  echo
fi

For all of you real systems administrators, I am sure there are many better solutions as to how to synchronize the dates on servers, but our system administrator is too busy to get the solution working right now. This simple bash script does the following:

  1. Forces the script to run under SUDO privileges.
  2. Prompts the user for the remote IP address.  I always use my Mac as the remote machine.
  3. Prompts the user for the remote username.
  4. Prompts the user for the remote password.
  5. Sets the date using the date of the remote machine.

The script can be run in either of the following ways (assuming that you are in the directory with the file, the file is named sync_time.sh, and the permissions are setup correctly [chmod 777 sync_time.sh]):

  • ./sync_time.sh
  • sudo ./sync_time.sh
Running this script is like doing the following (while making sure that the date is pulled from the remote machine):

sudo date -s "08/07/2012 14:30:00"
Categories: Blog

Leave a Reply

Your email address will not be published. Required fields are marked *