python通过ssh-powershell监控windows的方法
本文实例讲述了python通过ssh-powershell监控windows的方法。分享给大家供大家参考。具体分析如下:
对于服务器的监控来说,监控linux不管是自己动手写脚本还是用一些开源的工具比如nagios,zenoss什么的。但毕竟还是有些公司有windows做服务器的,相对linux来说,windows没有方便的shell,cmd下提供的命令对于监控来说远远没有linux方便。但是现在windows上如果安装了powershell(win7,2008自带),就比以前方便多了,linux上的命令基本都能在powershell里执行,比如查看进程还是ps.
自己封装了一个python通过ssh(通过pexpect模块)调用powershell的脚本,里面包快ps,netstat,ping检测,查看硬盘,cpu信息和负载,内存信息。通过创建ssh_win32类对象,然后调用它的方法,返回的都是解析好的python对象。
ssh_powershell.py:
#!/usr/bin/envpython #-*-coding:utf-8-*- importre frompexpectimport* classssh_win32: def__init__(self,user,host,password=None,systemroot='c',papath='',timeout=5,verbose=0): self.user=user#监控机器的username self.host=host#监控机器的ip self.verbose=verbose self.password=password#密码 self.timeout=timeout#执行命令的timeout self.systemroot=systemroot#windows所安装的盘符 ifnotpapath:#powershell.exe的路径 self.powershell_path=self.systemroot+':/WINDOWS/system32/WindowsPowerShell/v1.0/powershell.exe' self.key=[ 'authenticity', 'assword:', '@@@@@@@@@@@@', 'Commandnotfound.', EOF, ] self.f=open('ssh.out','w') defssh(self,command): cmd='ssh-l%s%s%s'%(self.user,self.host,command) print"cmd:",cmd con=spawn(cmd,timeout=self.timeout) seen=con.expect(self.key) ifseen==0: con.sendline('yes') seen=con.expect(self.key) ifseen==1: #ifnotself.password: #self.password=getpass.getpass('Remotepassword:') con.sendline(self.password) try: res=con.read() exceptException,e: res=con.before #print"res:",res returnres defssh_disk(self): cmd=self.powershell_path+"Get-WmiObjectwin32_logicaldisk" res=self.ssh(cmd) disk={} ifres: res=res.split('Nosuchfileordirectory')[-1].replace('\r','').split('\n') res=[cforcinresifc] #print'res:',res predisk='C' fordinres: #printd key,value=d.split(':',1) #printd #print'key:',key,'value:',value key=key.strip() value=value.strip() ifkey=='DeviceID'andvaluenotindisk.keys(): predisk=value disk[predisk]={} disk[predisk][key]=value else: ifkeyin['FreeSpace','Size']: ifvalue: value=int(value)/1024/1024/1024 disk[predisk][key]=value fordindisk.keys(): ifdisk[d]['DriveType']!='3': disk.pop(d) #print'disk:',disk returndisk defssh_cpu(self): cmd=self.powershell_path+'gwmi-computernamelocalhostwin32_Processor' res=self.ssh(cmd) res=res.split('Nosuchfileordirectory')[-1].replace('\r','').split('\n') res=[rforrinresifr] #printres cpu={} foriinres: #print'='*10 #printi i=i.split(':') #printi iflen(i)==2: key,value=i else: continue key=key.strip() value=value.strip() #print'key:',key #print'value:',value cpu[key]=value returncpu defssh_memory(self): totalmem=self.powershell_path+'Get-WmiObjectwin32_OperatingSystemTotalVisibleMemorySize' freemem=self.powershell_path+'Get-WmiObjectwin32_OperatingSystemFreePhysicalMemory' memory={} forcmdin[totalmem,freemem]: res=self.ssh(cmd) if'Win32_OperatingSystem'inres: res=res=res.replace('\r','').split('\n') res=[mforminresifm][-1] print'res:',res key,value=res.split(':') key=key.strip() value=value.strip() memory[key]=value else: print"notreturndata" returnNone returnmemory defssh_ping(self,host): cmd='ping-n1%s'%host patt=r'.+?(\d*)%loss.*' res=self.ssh(cmd).replace('\r','').replace('\n','') printres m=re.match(patt,res) ifm: lost_percent=m.group(1) print'lost_percent:',lost_percent returnint(lost_percent) else: returnNone defssh_ps(self): cmd=self.powershell_path+'ps' res=self.ssh(cmd) ps=[] if'-------------'inres: res=res.replace('\r','').split('-------------')[-1].split('\n') res=[dfordinresifd.strip()] forpinres: process={} row=[paraforparainp.split('')ifpara.strip()] process['handles']=row[0] process['npm']=row[1] process['pm']=row[2] process['ws']=row[3] process['vm']=row[4] process['cpu']=row[5] process['id']=row[6] process['process_name']=row[-1] ps.append(process) #printps returnps else: returnNone defssh_netstat(self): cmd='netstat-ao' res=self.ssh(cmd) netstat=[] if'PID'inres: res=res.replace('\r','').split('PID')[-1].split('\n') res=[dfordinresifd.strip()] forpinres: process={} row=[paraforparainp.split('')ifpara.strip()] process['proto']=row[0] process['local_address']=row[1] process['foreign_address']=row[2] process['state']=row[3] process['pid']=row[-1] netstat.append(process) #printnetstat returnnetstat else: returnNone if__name__=="__main__": cmd="c:/WINDOWS/system32/WindowsPowerShell/v1.0/powershell.exeps" user='admin' host='192.168.123.105' password='123456' ssh=ssh_win32(user,host,password,systemroot='c',timeout=5) #printssh.ssh_cpu() #print"\n\n\n\n" #printssh.ssh_disk() #print"\n\n\n\n" #printssh.ssh_memory() #printssh.ssh_ping(host) #printssh.ssh_ps() #printssh.ssh_netstat()
希望本文所述对大家的Python程序设计有所帮助。