Tuesday, February 28, 2012

Setting linux time and date without ntp

I have an unfortunate situation where I have a couple of linux servers that are unable to access any ntp servers because UDP is blocked on the corporate network. I searched for an existing solution but did not find anything except advice on how to set up NTP :).

So, here is a quick python program that will set the time based on the timeserver from the US Naval Observatory. This is nowhere near as accurate as NTP but should stay within a second or so of 'official time'.

Note that on my system I had to create a shell script called update_time.sh to call the python program because I did not want to allow python to be run as root with no password. I added an entry into crontab to call the python program using sudo /update_time.sh. And all was well.

The quick and dirty python code:

import datetime
import httplib2
import re
import os

h = httplib2.Http()
httpstr = 'http://tycho.usno.navy.mil/cgi-bin/timer.pl'
eastre = re.compile('Eastern')
extractre = re.compile('(?P<month>\w+)\.\s(?P<day>\d{2}),\s(?P<time>\d{2}:\d{2}:\d{2})\s(?P<ampm>AM|PM)')

resp, content = h.request( httpstr )
lines = content.split('
')

for line in lines:
res1 = eastre.search(line)
if ( res1 != None ):
res2 = extractre.search(line)
if ( res2 != None ):
    month = res2.group('month')
    day = res2.group('day')
    time = res2.group('time')
    ampm = res2.group('ampm')
    break

if month != None:
os.system( 'sudo date +%%T%%p -s "%s%s"' % (time,ampm) )


And the entry to sudoers:


yourusername  ALL=NOPASSWD: /path/tocode/update_time.sh ""