本代码linux、window平台通用。
Python3.6编译的话Windows2008会提示缺少运行库,安装VC2015运行库需要提前安装sp1补丁。可直接用Python2.7编译。
linux平台还可以监控load average,我在这里没写。以前方法比较笨,让shell执行uptime,awk过滤。我想用正则匹配第一个浮点数应该很简单。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#GuoYabin
import os,sys,psutil,time def my_system():
return(sys.platform) def zabbix_bin():
if my_system() == 'win32':
zabbix='C:\\zabbix\\zabbix_sender.exe'
else:
zabbix='/usr/local/zabbix/bin/zabbix_sender'
return(zabbix) def my_ip():
ip_dict=psutil.net_if_addrs().items()
#ip=[]
for key,value in ip_dict:
for i in value:
if '10.1' in i.address:
#ip.append(key,i.address) #返回多IP的字典
return(key,i.address) def my_mem():
my_mem=psutil.virtual_memory()
return (my_mem.percent) def my_cpu():
return (psutil.cpu_percent(interval=0.5)) def my_tcp():
if my_system() == 'win32':
my_tcp=int(os.popen('netstat -n |find /C "ESTAB"').read())
else:
my_tcp=int(os.popen("ss -s |grep -o '[0-9]*[1-9]'|awk 'NR==4'").read())
return(my_tcp) def my_disk():
if my_system() == 'win32':
panfu=psutil.disk_partitions()[1].device #盘符
else:
panfu='/usr/local'
my_disk=psutil.disk_usage(panfu).percent
return(my_disk) def my_network():
old_net_out=psutil.net_io_counters(pernic=True)[my_ip()[0]][0]
old_net_in=psutil.net_io_counters(pernic=True)[my_ip()[0]][1]
time.sleep(1) #这里要浪费1秒了,有更好的办法吗?
new_net_out=psutil.net_io_counters(pernic=True)[my_ip()[0]][0]
new_net_in=psutil.net_io_counters(pernic=True)[my_ip()[0]][1]
net_out=new_net_out - old_net_out
net_in=new_net_in - old_net_in
return(net_out,net_in) if __name__=='__main__':
report_url='10.1.2.61'
zabbix_key=['CPU_usage_rate','Network_In','Network_Out','TCP_Estab','Disk_usage_rate','Memory_usage_rate']
zabbix_value=[my_cpu(),my_network()[1],my_network()[0],my_tcp(),my_disk(),my_mem()]
for i in range(6):
os.system("%s -z %s -s %s -k %s -o %s" %(zabbix_bin(),report_url,my_ip()[1],zabbix_key[i],zabbix_value[i]))
无耻的求一下赞助