#!/usr/bin/env python # -*- coding: UTF-8 -*- from os import popen2 from os.path import getmtime, isfile, expanduser from time import gmtime, strftime, time FREQUENCY = 60 CACHE_FILE = expanduser('~/sandbox/uptime.dat') LOG_FILE = expanduser('~/sandbox/uptime.log') ENABLE_LOG = True def getprocessoutput(e): """ Executes e and returns its output. """ return popen2(e)[1].read().rstrip() # So, um, why do people put everything in a main() function? def main(): now = time() if isfile(CACHE_FILE): fresh = False fh = open(CACHE_FILE, 'r') uptime, servername = [line.rstrip() for line in fh.readlines()] fh.close() if getmtime(CACHE_FILE) <= (now - FREQUENCY): fresh = True uptime = getprocessoutput('/usr/bin/uptime') # I do not know how to only open the file once. :| fh = open(CACHE_FILE, 'w') fh.write(uptime + '\n' + servername) fh.close() else: fresh = True uptime = getprocessoutput('/usr/bin/uptime') hostname = getprocessoutput('/bin/hostname') domainname = getprocessoutput('/bin/dnsdomainname') # Is that even possible? if hostname in ('','localhost'): servername = 'this server' else: if domainname in ('','localdomain'): servername = hostname else: servername = hostname + '.' + domainname # The file could probably be screwed up if the script is accessed twice # at the exact same time... cfh = open(CACHE_FILE, 'w') cfh.write(uptime + '\n' + servername) cfh.close() mtime = getmtime(CACHE_FILE) # That getmtime() is called up in the if and here.. print 'Content-Type: text/plain;charset=us-ascii' print 'Cache-Control: max-age=' + str(FREQUENCY) + ', must-revalidate, private, ' \ 'proxy-revalidate, s-maxage=' + str(FREQUENCY) print 'Expires: ' + strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(now + FREQUENCY)) print 'Last-Modified: ' + strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(mtime)) print print '/usr/bin/uptime output on', servername, 'as of', if fresh: # The bit of code below is simply not being executed. I can make the if # check for a nonexistant variable if I want to, and I won't get an # error. If I put invalid syntax here, I get an error, so Python knows # it exists (how could it not?). The code messing with cfh above works, # but I can put a print or whatever I want in or around it, and it won't # be executed. Is my sleepy brain missing something, or is Python # completely insane? if ENABLE_LOG: lfh = open(LOG_FILE, 'a') lfh.write(strftime('%Y-%m-%d %H:%M:%S: ') + uptime + '\n') lfh.close() print 'right now:\n' else: timediff = int(now - mtime) print timediff, if timediff == 1: print 'second ago:\n' else: print 'seconds ago:\n' print uptime if __name__ == '__main__': main()