Skip to content

Instantly share code, notes, and snippets.

@sdvg
Created February 7, 2012 18:59
Show Gist options
  • Save sdvg/1761248 to your computer and use it in GitHub Desktop.
Save sdvg/1761248 to your computer and use it in GitHub Desktop.
uhuc uptime
#!/usr/bin/env python
# TCP client
"""
This file is part of utime_serve.
utime_serve is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
utime_serve is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with utime_serve. If not, see <http://www.gnu.org/licenses/>.
"""
VERSION="0.0.3-r6"
BUFSIZE = 512
import socket
from time import time
from time import sleep
import sys
import os
import logging
from optparse import OptionParser
from xml.etree import ElementTree as ET
import hashlib
import math
try:
from Foundation import *
except ImportError:
logging.debug("no Foundation..")
class ut_client():
def __init__(s, host, port, config, ipv):
s.__CONFIG = config
s.__HOST = host
s.__PORT = int(port)
s.__sock = None
s.__IPv = int(ipv)
s.__run()
def getResults(s):
try:
data = s.__sock.recv(BUFSIZE)
data = data.strip()
if(len(data) > 4): print data
except socket.error, msg: logging.debug("Socket error: %s"%msg)
except: logging.debug("Error")
def __run(s):
s.conn_create(s.__HOST, s.__PORT)
s.__varis()
if(opts.versio!=0): s.__version()
if(opts.temps!=0): s.__templates()
if(opts.remove!=0): s.__remove()
if(opts.record!=0): s.__record()
s.__uptime()
def __templates(s):
print("user-helfen-usern Uptime\nClient Version %s"%VERSION)
s.__sock.send('TEMPLATES')
s.getResults()
s.__sock.send('BYE')
s.__sock.close()
sys.exit(0)
def __record(s):
proc = os.popen('uname -n')
node = proc.read()
file = open("/proc/uptime", "r")
uptime = file.read()
uptime, load = uptime.split(" ")
s.__sock.send('RECORD,%s,%s'%(node,s.USERNAME))
rec = s.__sock.recv(BUFSIZE)
rec = rec.strip()
print("%s. Aktuell: %s"%(rec,s.str_uptime(uptime)))
s.__sock.send('BYE')
s.__sock.close()
sys.exit(0)
def __version(s):
print("user-helfen-usern Uptime\nClient Version %s"%VERSION)
s.versio()
s.__sock.close()
sys.exit(0)
def __remove(s):
proc = os.popen('uname -n')
node = proc.read()
print("user-helfen-usern Uptime. Remove from UptimeDatabase.")
s.__sock.send('REMOVE,%s,%s,%s'%(node,s.USERNAME,s.PASSHASH))
s.getResults()
s.__sock.send('BYE')
s.__sock.close()
sys.exit(0)
def __uptime(s):
proc = os.popen('uname -n')
node = proc.read()
#LINUX
if s.isOSX() == False:
proc = os.popen('uname -r')
kernel_v = proc.read()
file = open("/proc/uptime", "r")
uptime = file.read()
else: #MAC
macName = os.popen('sw_vers -productName').read()
macVers = os.popen('sw_vers -productVersion').read()
kernel_v = "%s %s"%(macName, macVers)
uptime = math.floor( NSProcessInfo.processInfo().systemUptime() )
uptime = "%s %s"%(uptime, uptime)
sendstring = "%s,%s,%s,%s,%s,%s,%s,%s"%(uptime,VERSION,kernel_v,node,s.USERNAME,s.PASSHASH,s.THEME,s.FONTCOL)
logging.debug("Sending: %s"%sendstring)
s.__sock.send(sendstring)
s.getResults()
s.__sock.send('BYE')
def versio(s):
s.__sock.send('VERSION')
s.getResults()
s.__sock.send('BYE')
def str_uptime(s, utime):
try: contents = utime.split()
except: contents = utime
total_seconds = float(contents[0])
# Helper vars:
MINUTE = 60
HOUR = MINUTE * 60
DAY = HOUR * 24
# Get the days, hours, etc:
days = int( total_seconds / DAY )
hours = int( ( total_seconds % DAY ) / HOUR )
minutes = int( ( total_seconds % HOUR ) / MINUTE )
seconds = int( total_seconds % MINUTE )
# Build up the pretty string (like this: "N days, N hours, N minutes, N seconds")
string = ""
if days> 0:
string += str(days) + "" + (days == 1 and "d" or "d" ) + " "
if len(string)> 0 or hours> 0:
string += str(hours) + "" + (hours == 1 and "h" or "h" ) + " "
if len(string)> 0 or minutes> 0:
string += str(minutes) + "" + (minutes == 1 and "m" or "m" ) + " "
string += str(seconds) + "" + (seconds == 1 and "s" or "s" )
return string
def isOSX(s):
uname = os.popen('uname -s').read().rstrip()
if uname == 'Darwin':
return True
return False
def conn_create(s, HOST, PORT):
s.__sock = None
if (s.__IPv == 0):
try:
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try: s.__sock = socket.socket(af, socktype, proto)
except socket.error, msg:
logging.error("Socket error: %s"%msg[0])
s.__sock = None
continue
try:
s.__sock.settimeout(30)
s.__sock.connect(sa)
logging.debug("Connection established to %s on port %i"%(sa[0],sa[1]))
except socket.error, msg:
logging.debug("Connection error: %s"%msg)
s.__sock.close()
s.__sock = None
continue
break
except:
logging.debug("Connection error")
elif (s.__IPv == 1):
try: s.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
logging.error("Socket error: %s"%msg[0])
s.__sock = None
try:
s.__sock.settimeout(30)
s.__sock.connect((s.__HOST, s.__PORT))
logging.debug("[IPv4] Connection established to %s on port %i"%(s.__HOST,s.__PORT))
except socket.error, msg:
logging.debug("Connection error: %s"%msg)
s.__sock.close()
s.__sock = None
elif (s.__IPv == 2):
try: s.__sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
except socket.error, msg:
logging.error("Socket error: %s"%msg[0])
s.__sock = None
try:
s.__sock.settimeout(30)
s.__sock.connect((s.__HOST, s.__PORT))
logging.debug("[IPv6] Connection established to %s on port %i"%(s.__HOST,s.__PORT))
except socket.error, msg:
logging.debug("Connection error: %s"%msg)
s.__sock.close()
s.__sock = None
if s.__sock is None:
logging.error("Could not bind socket.")
sys.exit(1)
def __varis(s):
config = loadConfig(s.__CONFIG)
pwConf = config.find('pw')
themeConf = config.find('design')
s.THEME = themeConf.attrib['sel']
s.FONTCOL = themeConf.attrib['font_col']
logging.debug("Using style %s with font color %s"%(s.THEME,s.FONTCOL))
aConf = config.find('auth')
s.USERNAME = aConf.attrib['nick'].lower()
passwd = aConf.attrib['pass']
logging.debug("Plain PW: %s"%passwd)
if (pwConf.attrib['hash'] == 'sha1'): s.PASSHASH = hashlib.sha1(passwd).hexdigest()
if (pwConf.attrib['hash'] == 'md5'): s.PASSHASH = hashlib.md5(passwd).hexdigest()
logging.debug("Hashed PW: %s using salt: %s"%(s.PASSHASH,s.USERNAME))
def loadConfig(configFile): return ET.parse(configFile)
if __name__ == '__main__':
__dir__ = os.path.dirname(os.path.abspath(__file__))
filepath = os.path.join(__dir__, 'utime_client.xml')
optp = OptionParser()
optp.add_option('-q','--quiet', help='set logging to ERROR', action='store_const', dest='loglevel', const=logging.ERROR, default=logging.INFO)
optp.add_option('-d','--debug', help='set logging to DEBUG', action='store_const', dest='loglevel', const=logging.DEBUG, default=logging.INFO)
optp.add_option('-v','--version', help='Show version', dest='versio', action='count', default=0)
optp.add_option('--remove', help='Remove your entry in the uptime database', dest='remove', action='count', default=0)
optp.add_option('-t','--templates', help='Show templates', dest='temps', action='count', default=0)
optp.add_option('-c','--config', dest='configfile', default=filepath, help='set config file to use')
optp.add_option('-r','--record', dest='record', action='count', default=0, help='show machine uptime record')
optp.add_option('-4', dest='ipv4', action='count', default=0, help='Force using IPv4')
optp.add_option('-6', dest='ipv6', action='count', default=0, help='Force using IPv6')
opts,args = optp.parse_args()
logging.basicConfig(level=opts.loglevel,format='%(asctime)s %(levelname)-8s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S')
config = loadConfig(opts.configfile)
ipv = 0
if (opts.ipv4 != 0): ipv = 1
if (opts.ipv6 != 0): ipv = 2
if (opts.ipv4 != 0) and (opts.ipv6 != 0): ipv = 0
sConf = config.find('server')
host = sConf.attrib['host']
port = sConf.attrib['port']
ut_client(host, port, opts.configfile, ipv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment