参考网站:http://blog.chinaunix.net/uid-7910284-id-5774420.html

参考官方文档:https://docs.microsoft.com/en-us/previous-versions//aa394298(v=vs.85)

获取服务信息

from win32com.client import GetObject
import wmi,sys,argparse,subprocess parser = argparse.ArgumentParser( usage = 'check_win_service.py -t xx -n xxxx -cw xx.xx -cc xx.xx -mw xx.xx -mc xx.xx', description='to check windows iis thrift or process usages' )
parser.add_argument( '-t', dest='type', metavar='string', type=str, required=True, help='resource type:iis|srv|app' )
parser.add_argument( '-n', dest='name', metavar='string', type=str, required=True, help='service or app name' )
parser.add_argument( '-cw', dest='cpuwarn', metavar='float', type=float, nargs='?', const=80.00, help='warning value for cpu,default 80%' )
parser.add_argument( '-cc', dest='cpucrit', metavar='float', type=float, nargs='?', const=90.00, help='critial value for cpu,default 90%' )
parser.add_argument( '-mw', dest='memwarn', metavar='float', type=float, nargs='?', const=15.00, help='warning value for mem,default 15%' )
parser.add_argument( '-mc', dest='memcrit', metavar='float', type=float, nargs='?', const=20.00, help='critial value for mem,default 20%' )
parser.add_argument( '-tw', dest='tcpwarn', metavar='int', type=int, nargs='?', const=800, help='warning value for tcp,default 800' )
parser.add_argument( '-tc', dest='tcpcrit', metavar='int', type=int, nargs='?', const=1000, help='critial value for tcp,default 1000' )
args = parser.parse_args() def iis_usage(iisname):
wmi = GetObject('winmgmts:/root/cimv2')
iisbase = wmi.ExecQuery('select * from Win32_PerfFormattedData_W3SVCW3WPCounterProvider_W3SVCW3WP where Name like "%{}"'.format(iisname)) for item in iisbase:
iispid = item.Name.split('_')[0] iisstatus = [] try:
iisinfo = wmi.ExecQuery('select * from Win32_PerfFormattedData_PerfProc_Process where IDProcess = "{}"'.format(iispid))
except UnboundLocalError as nopid:
print("CRITIAL - {} was down".format(iisname))
sys.exit(2) for item in iisinfo:
iisstatus.append(item.PercentProcessorTime)
iisstatus.append(round(float(item.WorkingSetPrivate)/1024/1024,2))
iiscon = wmi.ExecQuery('select * from Win32_PerfFormattedData_W3SVC_WebService where Name = "{}"'.format(iisname))
for item in iiscon:
iisstatus.append(item.CurrentConnections) return(iisname,iispid,iisstatus) def srv_usage(srvname):
wmi = GetObject('winmgmts:/root/cimv2')
srvbase = wmi.ExecQuery('select * from Win32_Service where Name = "{}"'.format(srvname)) for item in srvbase:
srvpid = item.ProcessId srvstatus = [] try:
srvinfo = wmi.ExecQuery('select * from Win32_PerfFormattedData_PerfProc_Process where IDProcess = "{}"'.format(srvpid))
except UnboundLocalError as nopid:
print("CRITIAL - {} was down".format(srvname))
sys.exit(2) for item in srvinfo:
srvstatus.append(item.PercentProcessorTime)
srvstatus.append(round(float(item.WorkingSetPrivate)/1024/1024,2))
srvstatus.append(subprocess.getstatusoutput('netstat -ano | findstr {} | wc -l'.format(srvpid))[1]) return(srvname,srvpid,srvstatus) def app_usage(appname):
wmi = GetObject('winmgmts:/root/cimv2')
appbase = wmi.ExecQuery('select * from Win32_Process where CommandLine like "%{}%" and Caption != "python.exe"'.format(appname))
for item in appbase:
apppid = item.ProcessId appstatus = [] try:
appinfo = wmi.ExecQuery('select * from Win32_PerfFormattedData_PerfProc_Process where IDProcess = "{}"'.format(apppid))
except UnboundLocalError as nopid:
print("CRITIAL - {} was down".format(appname))
sys.exit(2) for item in appinfo:
appstatus.append(item.PercentProcessorTime)
appstatus.append(round(float(item.WorkingSetPrivate)/1024/1024,2))
appstatus.append(subprocess.getstatusoutput('netstat -ano | findstr {} | wc -l'.format(apppid))[1]) return(appname,apppid,appstatus) def judgement(judgetype,judgename,judgecpuw,judgecpuc,judgememw,judgememc,judgeconw,judgeconc):
wmi = GetObject('winmgmts:/root/cimv2')
totalmem = wmi.ExecQuery('select * from Win32_PhysicalMemory')
memtotal = 0
for item in totalmem:
memtotal += round((float(item.Capacity)/1024)/1024,2) if judgetype == 'iis':
stu = iis_usage(args.name)
elif judgetype == 'srv':
stu = srv_usage(args.name)
elif judgetype == 'app':
stu = app_usage(args.name)
else:
print("there have not this type")
sys.exit(3) statstr = "OK"
status = 0
cp = float(stu[2][0])
mp = round((float(stu[2][1])/memtotal)*100, 2)
tp = int(stu[2][2])
if cp < judgecpuw and mp < judgememw and tp < judgeconw:
pass
elif judgecpuw <= cp < judgecpuc or judgememw <= mp < judgememc or judgeconw <= tp < judgeconc:
status = 1
statstr = "WARNING"
elif judgecpuc <= cp[3][0] or judgememc <= mp or judgeconc <= tp:
status = 2
statstr = "CRITIAL"
else:
status = 3
statstr = "UNKNOWN"
print("{0} - {1} PID:{2}, Cpu Usage:{3}%,Mem Usage:{4}% {5}MB,Tcp Sockes:{6}CON | Cpu={3}%;{7};{8} Mem={4}%;{9};{10} MemUsage={5}MB;; Tcp={6}CON;{11};{12}"
.format(statstr,stu[0],stu[1],cp,mp,stu[2][1],tp,judgecpuw,judgecpuc,judgememw,judgememc,judgeconw,judgeconc))
sys.exit(status) judgement(args.type,args.name,args.cpuwarn,args.cpucrit,args.memwarn,args.memcrit,args.tcpwarn,args.tcpcrit)

  获取资源信息

from win32com.client import GetObject
import wmi,sys,argparse parser = argparse.ArgumentParser( usage = 'check_win_network.py -w xx.xx -c xx.xx', description='to check linuxs mem or net usages' )
parser.add_argument( '-t', dest='type', metavar='string', type=str, required=True, help='resource type:mem|net' )
parser.add_argument( '-d', dest='devs', metavar='string', type=str, nargs='?', const="eth0", help='network card name,do not define it if type is not "net"' )
parser.add_argument( '-w', dest='warn', metavar='float', type=float, nargs='?', const=80.0, help='warning value,default 80' )
parser.add_argument( '-c', dest='crit', metavar='float', type=float, nargs='?', const=90.0, help='critial value,default 90' )
args = parser.parse_args() def net_usage(dev="eth0", warning=80.00, critical=90.00):
wmi = GetObject('winmgmts:/root/cimv2')
networks = wmi.ExecQuery('select * from Win32_PerfFormattedData_Tcpip_NetworkInterface')
netinfo=[]
for item in networks:
if item.Name == dev:
netinfo.append(item.Name)
netinfo.append(round(float(item.BytesReceivedPersec)*8/1024/1024,2))
netinfo.append(round(float(item.BytesSentPersec)*8/1024/1024,2))
netinfo.append(round(float(item.BytesTotalPersec)*8/1024/1024,2))
netinfo.append(round(float(item.CurrentBandwidth)/1000/1000,0))
netinfo.append(item.PacketsReceivedPersec)
netinfo.append(item.PacketsSentPersec)
netinfo.append(item.PacketsPersec) exitflag = 0
status="OK" warning_line = netinfo[4] * (warning/100)
critical_line = netinfo[4] * (critical/100)
usepec = round((netinfo[3] / netinfo[4]) * 100,2)
tp = netinfo[3]
if tp < warning_line:
pass
elif warning_line <= tp < critical_line:
exitflag = 1
status="WARNING"
elif tp >= critical_line:
exitflag = 2
status="CRITICAL"
else:
print("UNKNOW")
sys.exit(3) print("{0} - {1} NetWork Usage: Network wide {2}Mbps, Use_Persent {3}%, Total_RX-TX {4}Mbps, RX {5}Mbps ,RX-package {6}, TX {7}Mbps, TX-package {8} | Use_Persent={3}%;;; Total_RX-TX={4}Mbps;{9};{10}; RX={5}Mbps;;; RX-package={6};;; TX={7}Mbps;;; TX-package={8};;;"
.format(status,netinfo[0],netinfo[4],usepec,netinfo[3],netinfo[1],netinfo[5],netinfo[2],netinfo[6],warning_line,critical_line))
sys.exit(exitflag) def mem_usage(warning=80.00, critical=90.00):
wmi = GetObject('winmgmts:/root/cimv2')
totalmem = wmi.ExecQuery('select * from Win32_PhysicalMemory')
freemem = wmi.ExecQuery('select * from Win32_PerfFormattedData_PerfOS_Memory') memtotal = 0.0
memused = 0.0
memfree = 0.0
memcache = 0.0 for item in totalmem:
memtotal += round((float(item.Capacity)/1024)/1024,2)
for item in freemem:
memfree = float(item.AvailableMBytes)
memcache = round(float(item.CacheBytes)/1024/1024,2)
memused = memtotal - memfree exitflag = 0
status="OK"
warning_mem = round((warning/100) * memtotal,2)
critical_mem = round((critical/100) * memtotal,2) if memused < warning_mem:
pass
elif warning_mem <= memused < critical_mem:
exitflag = 1
status="WARNING"
elif memused >= critical_mem:
exitflag = 2
status="CRITICAL"
else:
print("UNKNOW")
sys.exit(3) print("{0} - Mem Usage: Use_Persent {1}%, total {2}MB, free {3}MB, used {4}MB, cache-buffer {5}MB | Use_Persent={1}%;;; total={2}MB;;; free={3}MB;;; used={4}MB;{6};{7}; cache-buffer={5}MB;;;"
.format(status,round((memused/memtotal)*100,2),memtotal,memfree,memused,memcache,warning_mem,critical_mem))
sys.exit(exitflag) if args.type == "mem":
mem_usage(args.warn, args.crit)
elif args.type == "net":
net_usage(args.devs,args.warn,args.crit)
else:
print(args.type)
print("no this types -h for help")

  

用WMI监控IIS的更多相关文章

  1. 监控IIS的运行状态

    IIS经常出现假死的情况,具体什么时候会出现假死,我就不说了,今天我要写的是如何监控IIS的状态. 程序的功能是:如果IIS是为运行的状态,就重启IIS,如果IIS的连接数达到了设置的连接数,也重启I ...

  2. Zabbix WMI监控

    检查Windows OS是否激活,5表示处于通知模式,1表示已激活 wmi.get[root\cimv2,select LicenseStatus FROM SoftwareLicensingProd ...

  3. python利用WMI监控windows状态如CPU、内存、硬盘

    安装pywin32库 下载地址: https://sourceforge.net/projects/pywin32/files%2Fpywin32/选择对应python版本的文件.下载后在window ...

  4. 使用WMI监控进程启动与结束

    需要添加引用System.Management 代码: static void Main(string[] args) { //创建WQL事件查询,监视进程开启 var qCreate = new W ...

  5. 监控iis计数器

  6. IIS监控应用程序池和站点假死,自动重启IIS小工具

    文章技术适合初学者.高级的C#开发工程师这些估计都熟悉到烂了,望不要喷. 第一.C#代码要操作IIS 就必须先导入 Microsoft.Web.Administration.dll ,方便控制台程序做 ...

  7. 一个只需要点 「下一步」就完成监控 Windows

    Cloud Insight 此前已然支持 Linux 操作系统,支持20多中数据库中间件等组件,多种操作,多种搭配,服务器监控玩的其乐无穷啊!但想想还有许多 Windows 的小伙伴没有体验过,所以在 ...

  8. 老司机实战Windows Server Docker:2 docker化现有iis应用的正确姿势

    前言 上一篇老司机实战Windows Server Docker:1 初体验之各种填坑介绍了安装docker服务过程中的一些小坑.这一篇,我们来填一些稍大一些的坑:如何docker化一个现有的iis应 ...

  9. IIS Enabling HTTP Keep-Alives

    IIS 6.0 from:https://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/ea116535-8e ...

随机推荐

  1. cmd命令对java程序进行编译时出现:编码GBK的不可映射字符

    原因:由于JDK是国际版的,在编译的时候,如果我们没有用-encoding参数指定JAVA源程序的编码格式,则java.exe首先获得我们才做系统默认采用的编码格式,也即在编译JAVA程序时,若我们不 ...

  2. java io系列13之 BufferedOutputStream(缓冲输出流)的认知、源码和示例

    本章内容包括3个部分:BufferedOutputStream介绍,BufferedOutputStream源码,以及BufferedOutputStream使用示例. 转载请注明出处:http:// ...

  3. Windows 运行库

    Microsoft Visual C++ 2005 Redistributable - 8.0.61001http://download.microsoft.com/download/8/B/4/8B ...

  4. C++回顾day02---<对象构造和析构,外加友元函数>

    一:若没有显示写构造函数,默认会有一个默认构造函数(无参),若自己构造后,不会存在这个默认构造函数 二:类成员若是有const修饰,必须在对象初始化的时候,为该类成员赋值(或者一开始就定死,同C中) ...

  5. [JUC-1]并发包实现及线程状态

    一.Java 并发包实现 二.Java 线程状态转换图

  6. 使用 highlight.js 在网页中高亮显示java 代码 【原】

    <html> <head> <meta charset="UTF-8"> <script src="http://apps.bd ...

  7. Part-One

    首先,必须要声明一下,这个目录下的所有东西,是我对一本书复习,只是敲出部分代码让自己不至于眼高手低,其中有很多东西可能都是我的个人理解,如果有兴趣的朋友可以看一下,同时也欢迎大家指正. 1.Hello ...

  8. oracle杀掉连接

    相关sql --查看当前连接 select count(*) from v$process --数据库允许的最大连接数 select value from v$parameter where name ...

  9. docker 系列 - 容器数据持久化和数据共享

    docker 主要有两种数据存储形式, 一种是storage driver(也叫做 Graph driver), 另一种是 volume driver. stroage driver主要是存储那些无状 ...

  10. Image转Base64

    今天和一个朋友联调图片转Base64时发现一个问题 public static string ImageToBase64(Image img) { BinaryFormatter binFormatt ...