python监控nginx端口和进程状态
本文实例为大家分享了python监控nginx端口和进程状态的具体代码,供大家参考,具体内容如下
#!/usr/local/bin/python #coding:utf-8 importpsutil importsys importos #获取主机名称 defhostname(): sys=os.name ifsys=='nt': hostname=os.getenv('computername') returnhostname elifsys=='posix': host=os.popen('echo$HOSTNAME') try: hostname=host.read() returnhostname finally: host.close() else: return'Unkwonhostname' #获取进程状态 defprocessStatus(processName): pids=psutil.pids()#获取主机所有的PID a=1 forpidinpids:#对所有PID进行循环 p=psutil.Process(pid)#实例化进程对象 ifp.name()==processName:#判断实例进程名与输入的进程名是否一致(判断进程是否存活) print(a)#返回1,进程存活 a+=1 ifa==1: print(0)#返回0,进程逝去 #获取进程PID defprocessPID(processName): pids=psutil.pids() forpidinpids: p=psutil.Process(pid) ifp.name()==processName: returnpid returnTrue#如果找到该进程则打印它的PID,返回true else: print('找不到进程'+processName) returnFalse#没有找到该进程,返回false #获取进程的端口号 defprocessPort(pid): p=psutil.Process(pid) data=p.connections() data_listen=[xforxindataif'LISTEN'inx] #pid_port=[] #forportindata_listen: #pid_port.append((port.laddr.port)) #returnlist(set(pid_port)) returnlist(data_listen[0][3])[1] hostname=hostname().strip() PID=processPID('nginx') port=processPort(PID) json_data=[ {"name":hostname+'-nginx',"port":port,"host_ip":LOCAL_IP,"PID":PID} ] AutoDiscoveryJson(json_data,object_id='HOST')
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。