我的第一个Python脚本 - 收集主机信息并存到远程数据库里
开始学习Python已有2周了。 结合工作需要,写出了我的第一个Python脚本(Windows服务)
----------------------------------------------------------------------------
#!/usr/bin/env python
#coding=utf-8
#filename:HostInfo.py
import win32serviceutil , win32service , win32event , win32api
import pymssql
import os , sys , socket , traceback , pythoncom , threading
import wmi , pathutils
import time , decimal
class HostInfo(win32serviceutil.ServiceFramework, threading.Thread):
_svc_name_ = "HostInfo"
_svc_display_name_ = "Host Information"
_svc_description_ = "Collect Information of Host"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
threading.Thread.__init__(self)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
self.updateinfo()
time.sleep(300)
def writeerr(self, errinfo):
''' Write Error Information to log file '''
try:
self.filepath = pathutils.get_main_dir().replace('\\' , '\\\\') + r'\\errors.log'
self.myfile = file(self.filepath , 'w')
self.errlog = '::' + time.strftime('%Y-%m-%d %X') + errinfo
self.myfile.write(self.errlog)
self.myfile.close()
except:
pass
sys.exit()
def updateinfo(self):
# Get FQDN , hostname
try:
self.myfqdn = socket.getfqdn()
self.myhostname = socket.gethostname()
except Exception, e:
estr = traceback.format_exc()
self.writeerr(estr)
# Get members information of Local 'Administrators' user group
try:
pythoncom.CoInitialize()
self.mywmi = wmi.WMI()
self.admgrp = self.mywmi.Win32_Group(Name='Administrators')[0]
self.myadmins = ''
for user in self.admgrp.associators('Win32_GroupUser'):
self.aadmin = ':' + user.Caption.encode('cp936')
self.myadmins += self.aadmin
except Exception, e:
estr = traceback.format_exc()
self.writeerr(estr)
finally:
pythoncom.CoUninitialize()
# Get IP, MAC addresses
try:
self.cmd = "ipconfig /all"
self.r = os.popen(self.cmd).readlines()
except Exception, e:
estr = traceback.format_exc()
self.writeerr(estr)
self.rcount = len(self.r)
for macline in range(self.rcount):
if self.r[macline].find('Physical Address') != -1:
self.mymac = self.r[macline].split(':')[1].replace('\n','')
self.myip = self.r[macline + 2].split(':')[1].replace('\n','')
try:
# Write information to DB
self.conn = pymssql.connect(host='***',user='***',password='***',database='***')
self.cur = self.conn.cursor()
self.myquery = 'exec itisme @fqdn="%s", @hostname="%s", @ipaddr="%s", @macaddr="%s", @admins="%s"' % (self.myfqdn, self.myhostname, self.myip, self.mymac, self.myadmins)
self.cur.execute(self.myquery)
self.conn.commit()
self.conn.close()
except Exception, e:
estr = traceback.format_exc()
self.writeerr(estr)
if __name__=='__main__':
win32serviceutil.HandleCommandLine(HostInfo)