当前位置:   article > 正文

Python 开发简易巡检工具_python windows远程登录巡检

python windows远程登录巡检

利用SSH或者Zabbix监控,配合Django开发框架,改造出属于自己的监控平台,实现包括主机图形,自动发现,计划任务,批量cmd执行,服务监控,日志监控等功能,由于公司机器混乱,基本上市面上的所有设备都能找到,监控这些不同型号不同系统的主机需要分别对待,我们就借助各种开源项目来做一个简单的巡检工具,方便工作需要。

由于公司及其都是老式的性能不高,所以全程我都没敢加多线程,生怕把服务器拒绝服务了。

安装Zabbix客户端

首先客户端还是需要安装zabbix-agent这个监控工具,该工具可以监控所有的平台,windows linux mac unix 等,利用该工具完成一整套自动化平台一点问题都没有,连ansible都不需要了。

  1. [root@localhost ~]# wget http://repo.zabbix.com/zabbix/4.4/rhel/7/x86_64/zabbix-agent-4.4.3-1.el7.x86_64.rpm
  2. [root@localhost ~]# rpm -ivh zabbix-agent-4.2.0-0.1alpha1.el7.x86_64.rpm

该配置文件,并启动服务完事。

  1. [root@localhost ~]# vim /etc/zabbix/zabbix_agentd.conf
  2. PidFile=/var/run/zabbix/zabbix_agentd.pid
  3. LogFile=/var/log/zabbix/zabbix_agentd.log
  4. LogFileSize=0
  5. Server=192.168.1.2
  6. ServerActive=192.168.1.2
  7. Hostname=centos1
  8. Timeout=1
  9. Include=/etc/zabbix/zabbix_agentd.d/*.conf
  10. EnableRemoteCommands=1
  11. [root@localhost ~]# systemctl restart zabbix-agent
  12. [root@localhost ~]# systemctl enable zabbix-agent

服务端下载

Download Zabbix agents

下载好之后将里面的 zabbix-get.exe 拖入项目中,直接调用就好。

基本的数据采集命令:

  1. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.hostname
  2. localhost.localdomain // 此处才是主机名称
  3. zabbix_get.exe -s 192.168.1.20 -p 10050 -k agent.hostname
  4. centos1 // 此处是我们zabbix中自定义的键值对
  5. zabbix_get.exe -s 192.168.1.20 -p 10050 -k agent.ping
  6. 1
  7. zabbix_get.exe -s 192.168.1.20 -p 10050 -k agent.version
  8. 4.4.3 // zabbix 的version
  9. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.boottime
  10. 1578564779 // 系统启动的时间戳
  11. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.cpu.num
  12. 1 // 处理器个数
  13. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.localtime
  14. 1578569019 // 当前系统时间戳
  15. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.sw.arch
  16. x86_64 // 返回系统架构
  17. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.sw.os
  18. Linux version 3.10.0-1062.el7.x86_64 (mockbuild@kbuilder.bsys.centos.org) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) ) #1 SMP Wed Aug 7 18:08:02 UTC 2019 // 返回系统详细架构
  19. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.sw.packages[ssh] // 已安装软件列表
  20. [rpm] libssh2-1.8.0-3.el7.x86_64, openssh-7.4p1-21.el7.x86_64, openssh-clients-7.4p1-21.el7.x86_64, openssh-server-7.4p1-21.el7.x86_64
  21. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.uname
  22. Linux localhost.localdomain 3.10.0-1062.el7.x86_64 #1 SMP Wed Aug 7 18:08:02 UTC 2019 x86_64
  23. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.uptime
  24. 4438 // 系统运行时长(秒)多少秒使用s/uptime来获取
  25. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.users.num
  26. 0 // 登陆用户数
  27. zabbix_get.exe -s 192.168.1.20 -p 10050 -k kernel.maxfiles
  28. 96437 // 系统支持最大的open files整数
  29. zabbix_get.exe -s 192.168.1.20 -p 10050 -k kernel.maxproc
  30. 65536 // 系统支持最大进程数
  31. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.hw.macaddr
  32. [ens32] 00:50:56:22:6f:d3 // mac 地址列表
  33. >zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.sw.os
  34. Linux version 3.10.0-1062.el7.x86_64 (mockbuild@kbuilder.bsys.centos.org) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) ) #1 SMP Wed Aug 7 18:08:02 UTC 2019 // 操作系统信息

允许远程执行命令:

  1. [root@localhost ~]# vim /etc/zabbix/zabbix_agentd.conf
  2. EnableRemoteCommands=1
  3. [root@localhost ~]# systemctl restart zabbix-agent
  4. D:\zabbix> zabbix_get.exe -s 192.168.1.20 -p 10050 -k "system.run[df -h]"
  5. Filesystem Size Used Avail Use% Mounted on
  6. devtmpfs 480M 0 480M 0% /dev
  7. tmpfs 491M 0 491M 0% /dev/shm
  8. tmpfs 491M 7.4M 484M 2% /run
  9. tmpfs 491M 0 491M 0% /sys/fs/cgroup
  10. /dev/mapper/centos-root 27G 1.7G 26G 7% /
  11. /dev/sda1 1014M 136M 879M 14% /boot
  12. tmpfs 99M 0 99M 0% /run/user/0

监控CPU

  1. system.cpu.util[<cpu>,<type>,<mode>]
  2. -CPU: CPU数量(默认是所有CPU)
  3. -Type: 可用值,idle,nice,user,system,iowait,interrupt,sottrq,steal
  4. -Mode 可用值,avg1(一分钟负载),avg5,avg15
  5. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k system.cpu.util[,,avg1]
  6. 0.016692
  7. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.cpu.num
  8. 1 // cpu 个数
  9. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.cpu.util
  10. 0.016461 // cpu 利用率百分比
  11. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.hw.cpu // cpu 详细信息
  12. processor 0: GenuineIntel Intel(R) Celeron(R) CPU E3500 @ 2.70GHz working at 2700MHz

监控内存

  1. proc.mem[<name>,<user>,<mode>,<cmdline>,<memtype>]
  2. -name 进程名(默认所有进程)
  3. -user 用户名(默认所有用户)
  4. -mode 可选值,avg,max,min,sum
  5. -cmdline 命令过滤
  6. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k proc.mem[httpd,,,]
  7. 1376378880
  8. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k proc.mem[]
  9. 6479925248
  10. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.swap.in
  11. 0 // Swap in (f内存到磁盘) .数字
  12. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.swap.out
  13. 0 //Swap out (f内存到磁盘) .数字
  14. zabbix_get.exe -s 192.168.1.20 -p 10050 -k system.swap.size
  15. 2147479552 // 交换分区大小字节或者百分比
  16. mode - total (默认), active, anon, buffers, cached, exec, file, free, inactive, pinned, shared, wired, used, pused, available
  17. zabbix_get.exe -s 192.168.1.20 -p 10050 -k vm.memory.size[free]
  18. 598949888 // 监控内存变化

监控网卡

  1. net.if.in [if,<mode>] #网卡入口流量
  2. net.if.out [if,<mode>] #网卡出口流量
  3. net.if.total [if,<mode>] #网卡进/出流量总和
  4. -if 网卡名称
  5. -mode 可用值(如下)
  6. bytes 字节数
  7. packets 包数量
  8. errors 错误数量
  9. droppend 丢包数量
  10. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k net.if.in[ens32,bytes]
  11. 165983
  12. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k net.if.in[ens32,packets]
  13. 2166
  14. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k net.if.out[ens32,packets]
  15. 2067
  16. [root@localhost ~]# zabbix_get.exe -s 192.168.1.20 -p 10050 -k net.if.discovery
  17. [{"{#IFNAME}":"ens32"},{"{#IFNAME}":"lo"}] // 列出系统网卡信息
  18. zabbix_get.exe -s 192.168.1.20 -p 10050 -k net.if.total[ens32]
  19. 20785083 // 列出网卡总流量
  20. zabbix_get.exe -s 192.168.1.20 -p 10050 -k net.tcp.listen[10050]
  21. 1 // 检测指定端口是否开启
  22. zabbix_get.exe -s 192.168.1.20 -p 10050 -k net.tcp.port[,80]
  23. 0 // 检测本机web服务是否开启
  24. zabbix_get.exe -s 192.168.1.20 -p 10050 -k net.tcp.service[ssh,,22]
  25. 1 // 检测是定服务是否在运行

监控IO/读写

  1. vfs.dev.read [<device>,<type>,<mode>] #磁盘读取
  2. vfs.dev.write [<device>,<type>,<mode>] #磁盘写入
  3. -device 磁盘设备(默认all)
  4. -type sectors,operations,bytes,sps,ops,hps
  5. -mode 默认有(avg1,avg5,avg15)
  6. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k vfs.dev.read[/dev/sda,,avg1]
  7. 0.000000
  8. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k vfs.dev.read[all]
  9. 195.200000
  10. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k vfs.dev.read[all,,avg1]
  11. 195.200000
  12. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k vfs.dev.read[all,,avg5]
  13. 177.758242
  14. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k vfs.dev.write[all,,avg5]
  15. 465.284483
  16. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k vfs.dev.write[all,,avg1]
  17. 877.200000
  18. [root@localhost ~]# zabbix_get -s 192.168.1.25 -k vfs.dev.write[/dev/sda,,]
  19. 374.800000

文件操作:

  1. zabbix_get.exe -s 192.168.1.20 -p 10050 -k vfs.file.exists[/etc/passwd]
  2. 1 // 检测指定文件是否存在
  3. zabbix_get.exe -s 192.168.1.20 -p 10050 -k vfs.file.md5sum[/etc/passwd]
  4. 52f5db4f5688b79b9c07ef5a42ea29af // md5验证
  5. zabbix_get.exe -s 192.168.1.20 -p 10050 -k vfs.file.size[/etc/passwd]
  6. 870 // 文件大小字节数
  7. zabbix_get.exe -s 192.168.1.20 -p 10050 -k vfs.file.time[/etc/passwd]
  8. 1578566854 // 文件日期时间戳
  9. zabbix_get.exe -s 192.168.1.20 -p 10050 -k vfs.fs.discovery // 列出文件系统所有目录结构
  10. [{"{#FSNAME}":"/","{#FSTYPE}":"rootfs"},{"{#FSNAME}":"/sys","{#FSTYPE}":"sysfs"},{"{#FSNAME}":"/proc","{#FSTYPE}":"proc"},{"{#FSNAME}":"/dev","{#FSTYPE}":"devtmpfs"},{"{#FSNAME}":"/sys/kernel/security","{#FSTYPE}":"securityfs"},{"{#FSNAME}":"/dev/shm"}]
  11. mode - total (默认), free, used, pfree (空闲百分比), pused (使用百分比)
  12. zabbix_get.exe -s 192.168.1.20 -p 10050 -k vfs.fs.inode[/dev,free]
  13. 122355 // 检测/dev/空闲空间
  14. zabbix_get.exe -s 192.168.1.20 -p 10050 -k vfs.fs.size[/dev,free]
  15. 502525952 // 磁盘空间,返回本地文件系统的使用量字节

磁盘利用率

  1. 监控磁盘使用情况需要vfs.fs.size[fs,<mode>]键值
  2. fs:文件系统
  3. mode:模式
  4. total默认全部,free空闲,used使用,pfree空闲百分比,pused使用百分比
  5. 名称:c盘总量
  6. 键值:vfs.fs.size[c:,total]
  7. 名称:c盘剩余量 键值vfs.fs.size[c:,free]
  8. 名称:c盘使用量 键值vfs.fs.size[c:,used]
  9. 名称:c盘剩余百分比 键值:vfs.fs.size[c:,pfree]
  10. 名称:c盘使用百分比 键值:vfs.fs.size[c:,pused]

先来完成一个Ping操作

  1. import os,sqlite3,datetime,time,signal,sys
  2. import subprocess
  3. def Ping(address,port,timeout):
  4. command = "get.exe -s {} -p {} -k agent.ping".format(address,port).split(" ")
  5. start = datetime.datetime.now()
  6. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  7. while process.poll() is None:
  8. time.sleep(1)
  9. now = datetime.datetime.now()
  10. if (now - start).seconds > timeout:
  11. return 0
  12. return 1
  13. for i in range(10,22):
  14. a = Ping("192.168.1.{}".format(i),"10050",1)
  15. print(a)

封装connect方法 connect.py

  1. import os,subprocess,sys,math
  2. import time
  3. import datetime
  4. # 检查主机状态
  5. def GetPing(addr,port,timeout):
  6. try:
  7. command = "engine.exe -s {} -p {} -k agent.ping".format(addr, port).split(" ")
  8. start = datetime.datetime.now()
  9. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  10. while process.poll() is None:
  11. time.sleep(1)
  12. now = datetime.datetime.now()
  13. if (now - start).seconds > timeout:
  14. return 0
  15. return 1
  16. except Exception:
  17. return 0
  18. # 获取目标主机名 仅用于Windows
  19. def GetHostName(addr,port,timeout):
  20. try:
  21. Command = "engine.exe -s {} -p {} -k system.hostname".format(addr,port)
  22. start = datetime.datetime.now()
  23. process = subprocess.Popen(Command, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  24. HostName = str(process.stdout.readlines()[0].split()[0],"utf-8")
  25. while process.poll() is None:
  26. time.sleep(1)
  27. now = datetime.datetime.now()
  28. if (now - start).seconds > timeout:
  29. return 0
  30. return HostName
  31. except Exception:
  32. return 0
  33. # 得到系统型号,例如windows linux等
  34. def GetSysUname(addr,port,timeout):
  35. try:
  36. Command = "engine.exe -s {} -p {} -k system.uname".format(addr,port)
  37. start = datetime.datetime.now()
  38. process = subprocess.Popen(Command, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  39. Uname = str(process.stdout.readlines()[0].split()[0],"utf-8")
  40. while process.poll() is None:
  41. time.sleep(1)
  42. now = datetime.datetime.now()
  43. if (now - start).seconds > timeout:
  44. return 0
  45. return Uname
  46. except Exception:
  47. return 0
  48. # 列出系统平台 x86 or x64
  49. def GetSysArch(addr,port,timeout):
  50. try:
  51. command = "engine.exe -s {} -p {} -k system.sw.arch".format(addr, port).split(" ")
  52. start = datetime.datetime.now()
  53. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  54. while process.poll() is None:
  55. time.sleep(1)
  56. now = datetime.datetime.now()
  57. if (now - start).seconds > timeout:
  58. return 0
  59. arch = process.stdout.readlines()[0].split()[0]
  60. return str(arch,"utf-8")
  61. except Exception:
  62. return 0
  63. # 获取CPU核心数
  64. def GetCPUCoreNumber(addr,port,timeout):
  65. try:
  66. Command = "engine.exe -s {} -p {} -k system.cpu.num[online]".format(addr,port)
  67. start = datetime.datetime.now()
  68. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  69. CpuCoreNum = process.stdout.readlines()[0].split()[0]
  70. #print()
  71. return str(CpuCoreNum,"utf-8")
  72. except Exception:
  73. return 0
  74. # 获取CPU的利用率 10%
  75. def GetCPUCoreInfo(addr,port,timeout):
  76. try:
  77. Command = "engine.exe -s {} -p {} -k system.cpu.util".format(addr, port)
  78. start = datetime.datetime.now()
  79. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  80. CPU = math.ceil(float(process.stdout.readlines()[0].split()[0]))
  81. while process.poll() is None:
  82. time.sleep(1)
  83. now = datetime.datetime.now()
  84. if (now - start).seconds > timeout:
  85. return 0
  86. return CPU
  87. except Exception:
  88. return 0
  89. # 获取CPU 的负载值 avg1 avg5 avg15
  90. def GetCPULoadAvg(addr,port,avg,timeout):
  91. try:
  92. Command = "engine.exe -s {} -p {} -k system.cpu.load[,{}]".format(addr, port,avg)
  93. start = datetime.datetime.now()
  94. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  95. CPU = float(process.stdout.readlines()[0].split()[0])
  96. while process.poll() is None:
  97. time.sleep(1)
  98. now = datetime.datetime.now()
  99. if (now - start).seconds > timeout:
  100. return 0
  101. return CPU
  102. except Exception:
  103. return 0
  104. # 获取内存数据 返回总内存/剩余内存
  105. def GetMemInfo(addr,port,timeout):
  106. try:
  107. Total = subprocess.Popen("engine.exe -s {} -p {} -k vm.memory.size[total]".format(addr, port)
  108. , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  109. Free = subprocess.Popen("engine.exe -s {} -p {} -k vm.memory.size[free]".format(addr, port)
  110. , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  111. Total = math.ceil(int(Total.stdout.readlines()[0].split()[0])/1024/1024)
  112. Free = math.ceil(int(Free.stdout.readlines()[0].split()[0])/1024/1024)
  113. return Total,Free
  114. except Exception:
  115. return 0
  116. # 获取全部磁盘容量
  117. def GetDiskInfo(self):
  118. try:
  119. Free = subprocess.Popen("engine.exe -s {} -p {} -k vfs.fs.size[/,pfree]".format(self.addr, self.port)
  120. , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  121. Free = float(Free.stdout.readlines()[0].split()[0])
  122. return Free
  123. except Exception:
  124. return 0
  125. # 获取特定进程是否运行
  126. def GetProcessStatus(addr,port,procname):
  127. command = "engine.exe -s {} -p {} -k proc.num[\"{}\"]".format(addr,port,procname)
  128. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  129. ref = process.stdout.readlines()[0]
  130. if ref == b"1\r\n":
  131. return 1
  132. return 0
  133. # 获取端口开放状态
  134. def GetNetworkPort(addr,port,check_port):
  135. command = "engine.exe -s {} -p {} -k net.tcp.listen[{}]".format(addr,port,check_port)
  136. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  137. ref = process.stdout.readlines()[0]
  138. if ref == b"1\r\n":
  139. return 1
  140. return 0

调用命令,获取系统基本信息。

  1. import connect
  2. def SysInfo():
  3. lis = [["127.0.0.1","MCP服务器"],["192.168.1.1","CTI"]]
  4. print("IP地址 \t\t 主机作用 \t\t 主机类型 \t\t 主机架构 \t\t 核心数 \t\t CPU利用率 \t\t CPU Avg1 \t Avg5 \t Avg15 \t 内存利用率 \t Ping")
  5. host_addr = lis[0][0]
  6. host_type = lis[0][1]
  7. host_address = host_addr
  8. host_user_type = host_type
  9. host_ping = connect.GetPing(host_address,"10050",2)
  10. host_type = connect.GetSysUname(host_address,"10050",2)
  11. host_arch = connect.GetSysArch(host_address,"10050",2)
  12. host_cpu_number = connect.GetCPUCoreNumber(host_address,"10050",2)
  13. host_cpu_core = connect.GetCPUCoreInfo(host_address,"10050",2)
  14. host_cpu_load1 = connect.GetCPULoadAvg(host_address,"10050","avg1",2)
  15. host_cpu_load5 = connect.GetCPULoadAvg(host_address,"10050","avg5",2)
  16. host_cpu_load15 = connect.GetCPULoadAvg(host_address,"10050","avg15",2)
  17. host_memory = connect.GetMemInfo(host_address,"10050",2)
  18. print("{} \t {} \t\t {} \t\t {} \t\t\t {} \t\t\t {}% \t\t {} \t\t {} \t {} \t {} \t {}".
  19. format(host_address,host_user_type,host_type,host_arch,host_cpu_number,
  20. host_cpu_core,host_cpu_load1,host_cpu_load5,host_cpu_load15,host_memory,host_ping))
  21. if __name__ == '__main__':
  22. SysInfo()

批量ping检测

  1. import subprocess, datetime, time
  2. import threading,os,sys
  3. lock = threading.RLock()
  4. def GetPing(command, timeout):
  5. cmd = command.split(" ")
  6. start = datetime.datetime.now()
  7. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  8. while process.poll() is None:
  9. time.sleep(0.2)
  10. now = datetime.datetime.now()
  11. if (now - start).seconds> timeout:
  12. return "异常"
  13. try:
  14. ref = process.stdout.readlines()[0]
  15. if ref == b"1\r\n":
  16. return "正常"
  17. else:
  18. return "异常"
  19. except Exception:
  20. return "异常"
  21. def MyThread(ptr):
  22. each = eval(ptr)
  23. command = "engine.exe -s {} -p 10050 -k agent.ping".format(each[0])
  24. ref = GetPing(command,1)
  25. lock.acquire()
  26. if(ref == "异常"):
  27. print("{0:15}\t\t {1:15}\t {2:10}\t\t {3:10}\t {4:4} <--".format(each[0], each[1], each[2], each[3], ref))
  28. else:
  29. print("{0:15}\t\t {1:15}\t {2:10}\t\t {3:10}\t {4:4}".format(each[0], each[1], each[2], each[3], ref))
  30. lock.release()
  31. if __name__ == "__main__":
  32. # Base.db 内容: ["127.0.0.1","ANA2048567","1M-2F","MCP服务器"]
  33. fp = open("base.db","r",encoding="utf-8")
  34. count=len(open("base.db","r",encoding="utf-8").readlines())
  35. print("-" * 100)
  36. print("{0:13}\t\t {1:15}\t {2:10}\t\t {3:8}\t {4:4}".format("IP地址","SN号码","机房位置","作用","Ping"))
  37. print("-" * 100)
  38. for i in range(count):
  39. ptr = fp.readline()
  40. thread = threading.Thread(target=MyThread, args=(ptr,))
  41. thread.start()

批量进程检测

  1. import subprocess, datetime, time
  2. import threading,os,sys
  3. # 获取特定进程是否运行
  4. def GetProcessStatus(addr,port,timeout,procname):
  5. command = "engine.exe -s {} -p {} -k proc.num[\"{}\"]".format(addr,port,procname)
  6. start = datetime.datetime.now()
  7. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  8. while process.poll() is None:
  9. time.sleep(0.2)
  10. now = datetime.datetime.now()
  11. if (now - start).seconds> timeout:
  12. return 0
  13. try:
  14. ref = process.stdout.readlines()[0]
  15. if ref != b"0\r\n":
  16. return int(ref)
  17. else:
  18. return 0
  19. except Exception:
  20. return 0
  21. if __name__ == "__main__":
  22. process_cache = []
  23. proc_fp = open("process.db","r",encoding="utf-8")
  24. count = len(open("process.db","r",encoding="utf-8").readlines())
  25. for each in range(1,count+1):
  26. proc = eval(proc_fp.readline())
  27. proc_len = len(proc)
  28. print("-" * 70)
  29. print("---> 巡检地址: {}".format(proc[0]))
  30. print("-" * 70)
  31. for process in range(1,proc_len):
  32. ref = GetProcessStatus(proc[0],10050,3,proc[process])
  33. if(ref != 0):
  34. print("进程: {0:18} \t 进程数: {1:5} \t 状态: {2}".format(proc[process],ref,"√"))
  35. else:
  36. print("进程: {0:18} \t 进程数: {1:5} \t 状态: {2}".format(proc[process],ref,"×"))
  37. print()

批量CPU负载检测等

  1. import subprocess, datetime, time,math
  2. import threading,os,sys
  3. lock = threading.RLock()
  4. # 获取CPU的利用率 %
  5. def GetCPUCoreInfo(addr,port,timeout):
  6. try:
  7. Command = "engine.exe -s {} -p {} -k system.cpu.util".format(addr, port)
  8. start = datetime.datetime.now()
  9. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  10. CPU = math.ceil(float(process.stdout.readlines()[0].split()[0]))
  11. while process.poll() is None:
  12. time.sleep(0.3)
  13. now = datetime.datetime.now()
  14. if (now - start).seconds > timeout:
  15. return str("0%")
  16. return str(CPU) + "%"
  17. except Exception:
  18. return str("0%")
  19. # 获取CPU 的负载值 avg1 avg5 avg15
  20. def GetCPULoadAvg(addr,port,avg,timeout):
  21. try:
  22. Command = "engine.exe -s {} -p {} -k system.cpu.load[,{}]".format(addr, port,avg)
  23. start = datetime.datetime.now()
  24. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  25. CPU = float(process.stdout.readlines()[0].split()[0])
  26. while process.poll() is None:
  27. time.sleep(0.3)
  28. now = datetime.datetime.now()
  29. if (now - start).seconds > timeout:
  30. return 0
  31. return CPU
  32. except Exception:
  33. return 0
  34. # 获取内存数据 返回 %
  35. def GetMemInfo(addr,port,timeout):
  36. try:
  37. Total = subprocess.Popen("engine.exe -s {} -p {} -k vm.memory.size[total]".format(addr, port)
  38. , shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  39. start = datetime.datetime.now()
  40. while Total.poll() is None:
  41. time.sleep(0.3)
  42. now = datetime.datetime.now()
  43. if (now - start).seconds > timeout:
  44. return 0
  45. Free = subprocess.Popen("engine.exe -s {} -p {} -k vm.memory.size[free]".format(addr, port)
  46. , shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  47. start = datetime.datetime.now()
  48. while Free.poll() is None:
  49. time.sleep(0.3)
  50. now = datetime.datetime.now()
  51. if (now - start).seconds > timeout:
  52. return str(0)+"%"
  53. Total = math.ceil(int(Total.stdout.readlines()[0].split()[0])/1024/1024)
  54. Free = math.ceil(int(Free.stdout.readlines()[0].split()[0])/1024/1024)
  55. percentage = 100 - int(Free/int(Total/100))
  56. return str(percentage)+"%"
  57. except Exception:
  58. return str(0)+"%"
  59. def MyThread(ptr):
  60. address = eval(ptr)
  61. cpu_info = GetCPUCoreInfo(address[0], 10050, 1)
  62. mem_info = GetMemInfo(address[0], 10050, 1)
  63. cpu_load1 = GetCPULoadAvg(address[0], 10050, "avg1", 1)
  64. cpu_load5 = GetCPULoadAvg(address[0], 10050, "avg5", 1)
  65. cpu_load15 = GetCPULoadAvg(address[0], 10050, "avg15", 1)
  66. lock.acquire()
  67. print("{0:10} \t {1:10} \t {2:10} \t {3:10} \t {4:10} \t {5:10} \t".
  68. format(address[0], cpu_info, mem_info,cpu_load1, cpu_load5,cpu_load15))
  69. lock.release()
  70. if __name__ == "__main__":
  71. fp = open("base.db","r",encoding="utf-8")
  72. count = len(open("base.db","r",encoding="utf-8").readlines())
  73. print("-" * 100)
  74. print("IP地址 \t\t CPU利用率 \t 内存利用率 \t 1分钟负载 \t 5分钟负载 \t 15分钟负载 \t")
  75. print("-" * 100)
  76. for i in range(count):
  77. ptr = fp.readline()
  78. thread = threading.Thread(target=MyThread, args=(ptr,))
  79. thread.start()

封装一个Zabbix调用类

  1. import subprocess,datetime,time,math
  2. class Engine():
  3. def __init__(self,address,port):
  4. self.address = address
  5. self.port = port
  6. def GetValue(self,key):
  7. try:
  8. command = "get.exe -s {0} -p {1} -k {2}".format(self.address,self.port,key).split(" ")
  9. start = datetime.datetime.now()
  10. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  11. while process.poll() is None:
  12. time.sleep(1)
  13. now = datetime.datetime.now()
  14. if (now - start).seconds > 2:
  15. return 0
  16. return str(process.stdout.readlines()[0].split()[0],"utf-8")
  17. except Exception:
  18. return 0
  19. # 获取主机组基本信息
  20. def GetSystem(self):
  21. ref_dict = { "Address" : 0 ,"HostName" : 0,"Uname":0, "Ping":0 }
  22. ref_dict["Address"] = self.address
  23. ref_dict["HostName"] = self.GetValue("system.hostname")
  24. ref_dict["Uname"] = self.GetValue("system.uname")
  25. ref_dict["Ping"] = self.GetValue("agent.ping")
  26. return ref_dict
  27. # 获取CPU利用率
  28. def GetCPU(self):
  29. ref_dict = { "Address": 0 ,"Core": 0,"Active":0 , "Avg1": 0 ,"Avg5":0 , "Avg15":0 }
  30. ref_dict["Address"] = self.address
  31. ref_dict["Core"] = self.GetValue("system.cpu.num")
  32. ref_dict["Active"] = math.ceil(float(self.GetValue("system.cpu.util")))
  33. ref_dict["Avg1"] = self.GetValue("system.cpu.load[,avg1]")
  34. ref_dict["Avg5"] = self.GetValue("system.cpu.load[,avg5]")
  35. ref_dict["Avg15"] = self.GetValue("system.cpu.load[,avg15]")
  36. return ref_dict
  37. # 获取内存利用率
  38. def GetMemory(self):
  39. ref_dict = { "Address":0,"Total":0,"Free":0,"Percentage":0 }
  40. ref_dict["Address"] = self.address
  41. ref_dict["Total"] = self.GetValue("vm.memory.size[total]")
  42. ref_dict["Free"] = self.GetValue("vm.memory.size[free]")
  43. # 计算百分比: percentage = 100 - int(Free/int(Total/100))
  44. ref_dict["Percentage"] = str( 100 - int( int(ref_dict.get("Free")) / (int(ref_dict.get("Total"))/100)) ) + "%"
  45. return ref_dict
  46. # 获取磁盘数据
  47. def GetDisk(self):
  48. ref_list = []
  49. disk_ = eval( self.GetValue("vfs.fs.discovery") )
  50. for x in range(len(disk_)):
  51. dict_ = { "Address":0, "Name":0,"Type":0,"Free":0}
  52. dict_["Address"] = self.address
  53. dict_["Name"] = disk_[x].get("{#FSNAME}")
  54. dict_["Type"] = disk_[x].get("{#FSTYPE}")
  55. if dict_["Type"] != "UNKNOWN":
  56. pfree = self.GetValue("vfs.fs.size[\"{0}\",pfree]".format(dict_["Name"]))
  57. dict_["Free"] = str(math.ceil(float(pfree)))
  58. else:
  59. dict_["Free"] = 0
  60. ref_list.append(dict_)
  61. return ref_list
  62. if __name__ == "__main__":
  63. ptr_windows = Engine("132.35.93.2","10050")
  64. ret = ptr_windows.GetDisk()
  65. print(ret)

简单的监控脚本编写 (无脑写法)

首先是连接脚本 win32_connect.py

  1. import subprocess, datetime, time
  2. import threading, os, sys,math
  3. # 获取Ping返回状态
  4. def GetPing(command, timeout):
  5. cmd = command.split(" ")
  6. start = datetime.datetime.now()
  7. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  8. while process.poll() is None:
  9. time.sleep(0.2)
  10. now = datetime.datetime.now()
  11. if (now - start).seconds > timeout:
  12. return "异常"
  13. try:
  14. ref = process.stdout.readlines()[0]
  15. if ref == b"1\r\n":
  16. return "正常"
  17. else:
  18. return "异常"
  19. except Exception:
  20. return "异常"
  21. # 获取特定进程是否运行
  22. def GetProcessStatus(addr,port,timeout,procname):
  23. command = "engine.exe -s {} -p {} -k proc.num[\"{}\"]".format(addr,port,procname)
  24. start = datetime.datetime.now()
  25. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  26. while process.poll() is None:
  27. time.sleep(0.2)
  28. now = datetime.datetime.now()
  29. if (now - start).seconds> timeout:
  30. return 0
  31. try:
  32. ref = process.stdout.readlines()[0]
  33. if ref != b"0\r\n":
  34. return int(ref)
  35. else:
  36. return 0
  37. except Exception:
  38. return 0
  39. # 获取CPU的利用率 %
  40. def GetCPUCoreInfo(addr,port,timeout):
  41. try:
  42. Command = "engine.exe -s {} -p {} -k system.cpu.util".format(addr, port)
  43. start = datetime.datetime.now()
  44. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  45. CPU = math.ceil(float(process.stdout.readlines()[0].split()[0]))
  46. while process.poll() is None:
  47. time.sleep(0.3)
  48. now = datetime.datetime.now()
  49. if (now - start).seconds > timeout:
  50. return str("0%")
  51. return str(CPU) + "%"
  52. except Exception:
  53. return str("0%")
  54. # 获取CPU 的负载值 avg1 avg5 avg15
  55. def GetCPULoadAvg(addr,port,avg,timeout):
  56. try:
  57. Command = "engine.exe -s {} -p {} -k system.cpu.load[,{}]".format(addr, port,avg)
  58. start = datetime.datetime.now()
  59. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  60. CPU = float(process.stdout.readlines()[0].split()[0])
  61. while process.poll() is None:
  62. time.sleep(0.3)
  63. now = datetime.datetime.now()
  64. if (now - start).seconds > timeout:
  65. return 0
  66. return CPU
  67. except Exception:
  68. return 0
  69. # 获取内存数据 返回 %
  70. def GetMemInfo(addr,port,timeout):
  71. try:
  72. Total = subprocess.Popen("engine.exe -s {} -p {} -k vm.memory.size[total]".format(addr, port)
  73. , shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  74. start = datetime.datetime.now()
  75. while Total.poll() is None:
  76. time.sleep(0.3)
  77. now = datetime.datetime.now()
  78. if (now - start).seconds > timeout:
  79. return 0
  80. Free = subprocess.Popen("engine.exe -s {} -p {} -k vm.memory.size[free]".format(addr, port)
  81. , shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  82. start = datetime.datetime.now()
  83. while Free.poll() is None:
  84. time.sleep(0.3)
  85. now = datetime.datetime.now()
  86. if (now - start).seconds > timeout:
  87. return str(0)+"%"
  88. Total = math.ceil(int(Total.stdout.readlines()[0].split()[0])/1024/1024)
  89. Free = math.ceil(int(Free.stdout.readlines()[0].split()[0])/1024/1024)
  90. percentage = 100 - int(Free/int(Total/100))
  91. return str(percentage)+"%"
  92. except Exception:
  93. return str(0)+"%"
  94. # 获取磁盘容量、pfree_disk 已用 、 ptotal_disk 可用
  95. def GetDisk(addr,port,timeout,diskname):
  96. command = "engine.exe -s {} -p {} -k vfs.fs.size[\"{}\",pfree]".format(addr,port,diskname)
  97. start = datetime.datetime.now()
  98. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  99. try:
  100. while process.poll() is None:
  101. time.sleep(0.2)
  102. now = datetime.datetime.now()
  103. if (now - start).seconds> timeout:
  104. return 0
  105. try:
  106. pfree_disk = math.ceil(float(process.stdout.readlines()[0]))
  107. ptotal_disk = math.ceil(100 - pfree_disk)
  108. return pfree_disk,ptotal_disk
  109. except Exception:
  110. return 0,0
  111. except Exception:
  112. return 0,0
  113. # 检测端口开启状态
  114. def GetListenPort(addr,port,timeout,check_port):
  115. Command = "engine.exe -s {} -p {} -k net.tcp.listen[{}]".format(addr, port,check_port)
  116. start = datetime.datetime.now()
  117. try:
  118. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  119. while process.poll() is None:
  120. time.sleep(0.2)
  121. now = datetime.datetime.now()
  122. if (now - start).seconds> timeout:
  123. return 0
  124. status = int(process.stdout.readlines()[0])
  125. return status
  126. except Exception:
  127. return 0
  128. return 0
  129. # 检测Web服务器状态 使用LocalAddr的地址对check_addr的check_port端口进行检测
  130. def CheckWebServerStatus(Local_Addr,port,timeout,check_addr,check_port):
  131. test_ping = "engine.exe -s {} -p 10050 -k agent.ping".format(Local_Addr)
  132. ref = GetPing(test_ping, 1)
  133. if ref != "异常":
  134. Command = "engine.exe -s {} -p {} -k net.tcp.port[\"{}\",{}]".format(Local_Addr, port,check_addr,check_port)
  135. start = datetime.datetime.now()
  136. try:
  137. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  138. while process.poll() is None:
  139. time.sleep(0.2)
  140. now = datetime.datetime.now()
  141. if (now - start).seconds> timeout:
  142. return 0
  143. status = int(process.stdout.readlines()[0])
  144. return status
  145. except Exception:
  146. return 0
  147. return 0
  148. return 0

接着是win32_core.py

  1. import win32_connect
  2. def MyPing():
  3. fp = open("win32_base.db", "r", encoding="utf-8")
  4. count = len(open("win32_base.db", "r", encoding="utf-8").readlines())
  5. print("-" * 100)
  6. print("{0:20} \t {1:10} \t {2:13} \t {3:5} \t {4:9} \t {5:40}".format("IP地址","机器系统","设备SN","机房位置","存活状态","主机作用"))
  7. print("-" * 100)
  8. for each in range(count):
  9. item = fp.readline().replace("\n","")
  10. eval_list = eval(item)
  11. command = "engine.exe -s {} -p 10050 -k agent.ping".format(eval_list[0])
  12. ref = win32_connect.GetPing(command, 1)
  13. print("{0:20} \t {1:15} \t {2:13} \t {3:10} \t {4:5} \t {5:40}".
  14. format(eval_list[0],eval_list[1],eval_list[2],eval_list[3],ref,eval_list[4]))
  15. fp.close()
  16. # 统计系统启动进程
  17. def MyProcessCheck():
  18. process_cache = []
  19. proc_fp = open("win32_process.db", "r", encoding="utf-8")
  20. count = len(open("win32_process.db", "r", encoding="utf-8").readlines())
  21. for each in range(1, count + 1):
  22. proc = eval(proc_fp.readline())
  23. proc_len = len(proc)
  24. print("-" * 70)
  25. print("---> 巡检地址: {}".format(proc[0]))
  26. print("-" * 70)
  27. for process in range(1, proc_len):
  28. ref = win32_connect.GetProcessStatus(proc[0], 10050, 3, proc[process])
  29. if (ref != 0):
  30. print("进程: {0:18} \t 进程数: {1:5} \t 状态: {2}".format(proc[process], ref, "√"))
  31. else:
  32. print("进程: {0:18} \t 进程数: {1:5} \t 状态: {2}".format(proc[process], ref, "×"))
  33. print()
  34. proc_fp.close()
  35. # 统计系统负载情况
  36. def GetLoadAvg():
  37. fp = open("win32_base.db", "r", encoding="utf-8")
  38. count = len(open("win32_base.db", "r", encoding="utf-8").readlines())
  39. print("-" * 120)
  40. print("IP地址 \t\t\t 系统类型 \t\t CPU利用率 \t 内存利用率 \t 1分钟负载 \t 5分钟负载 \t 15分钟负载 \t 主机位置 \t\t 主机作用")
  41. print("-" * 120)
  42. for item in range(count):
  43. ptr = eval(fp.readline())
  44. command = "engine.exe -s {} -p 10050 -k agent.ping".format(ptr[0])
  45. flag = win32_connect.GetPing(command, 1)
  46. if flag == "正常":
  47. cpu_info = win32_connect.GetCPUCoreInfo(ptr[0], 10050, 1)
  48. mem_info = win32_connect.GetMemInfo(ptr[0], 10050, 1)
  49. cpu_load1 = win32_connect.GetCPULoadAvg(ptr[0], 10050, "avg1", 1)
  50. cpu_load5 = win32_connect.GetCPULoadAvg(ptr[0], 10050, "avg5", 1)
  51. cpu_load15 = win32_connect.GetCPULoadAvg(ptr[0], 10050, "avg15", 1)
  52. print("{0:10} \t {1:15} \t {2:4} \t {3:4} \t {4:7} \t {5:7} \t {6:7} \t\t {7:10} \t {8:30}".
  53. format(ptr[0],ptr[1],cpu_info,mem_info,cpu_load1,cpu_load5,cpu_load15,ptr[3],ptr[4]))
  54. else:
  55. print("{0:10} \t {1:15} \t {2:4} \t {3:4} \t {4:7} \t {5:7} \t {6:7} \t\t {7:10} \t {7:30}".
  56. format(ptr[0],ptr[1],"-1","-1","-1","-1","-1",ptr[3],ptr[4]))
  57. fp.close()
  58. # 统计磁盘
  59. def GetFDisk():
  60. fp = open("win32_disk.db", "r", encoding="utf-8")
  61. count = len(open("win32_disk.db", "r", encoding="utf-8").readlines())
  62. for each in range(1,count+1):
  63. item = fp.readline().replace("\n", "")
  64. eval_list = eval(item)
  65. print()
  66. print("-" * 80)
  67. print("检测主机: {}".format(eval_list[0]))
  68. print("-" * 80)
  69. for x in range(1,(len(eval_list)-1)+1):
  70. command = "engine.exe -s {} -p 10050 -k agent.ping".format(eval_list[0])
  71. ref = win32_connect.GetPing(command, 1)
  72. if ref == "正常":
  73. pfree,ptotal = win32_connect.GetDisk(eval_list[0], 10050, 1, eval_list[x])
  74. print("---> 磁盘分区: {0:10} \t 剩余空间: {1:5} \t 已用空间: {2:5}".format(eval_list[x],str(pfree)+"%",str(ptotal)+"%"))
  75. fp.close()
  76. # 统计Web服务器是否运行中
  77. def CheckWebServer():
  78. fp = open("WebServer.db", "r", encoding="utf-8")
  79. count = len(open("WebServer.db", "r", encoding="utf-8").readlines())
  80. for each in range(count):
  81. fp_list = eval(fp.readline().replace("\n",""))
  82. ref = win32_connect.CheckWebServerStatus("132.35.93.2", 10050, 1, fp_list[0], fp_list[1])
  83. if ref == 1:
  84. print("[成功] -> Web主机: {0:20} \t 检测端口: {1:5} \t 业务名称: {2:20}".format(fp_list[0],fp_list[1],fp_list[2]))
  85. else:
  86. print("*失败* -> Web主机: {0:20} \t 检测端口: {1:5} \t 业务名称: {2:20}".format(fp_list[0],fp_list[1],fp_list[2]))
  87. fp.close()

最后的win32_engine.py

  1. import os,subprocess,sys,math
  2. import time
  3. import datetime
  4. # 检查主机状态
  5. def GetPing(addr,port,timeout):
  6. try:
  7. command = "engine.exe -s {} -p {} -k agent.ping".format(addr, port).split(" ")
  8. start = datetime.datetime.now()
  9. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  10. while process.poll() is None:
  11. time.sleep(1)
  12. now = datetime.datetime.now()
  13. if (now - start).seconds > timeout:
  14. return 0
  15. return 1
  16. except Exception:
  17. return 0
  18. # 获取目标主机名 仅用于Windows
  19. def GetHostName(addr,port,timeout):
  20. try:
  21. Command = "engine.exe -s {} -p {} -k system.hostname".format(addr,port)
  22. start = datetime.datetime.now()
  23. process = subprocess.Popen(Command, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  24. HostName = str(process.stdout.readlines()[0].split()[0],"utf-8")
  25. while process.poll() is None:
  26. time.sleep(1)
  27. now = datetime.datetime.now()
  28. if (now - start).seconds > timeout:
  29. return 0
  30. return HostName
  31. except Exception:
  32. return 0
  33. # 得到系统型号,例如windows linux等
  34. def GetSysUname(addr,port,timeout):
  35. try:
  36. Command = "engine.exe -s {} -p {} -k system.uname".format(addr,port)
  37. start = datetime.datetime.now()
  38. process = subprocess.Popen(Command, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  39. Uname = str(process.stdout.readlines()[0].split()[0],"utf-8")
  40. while process.poll() is None:
  41. time.sleep(1)
  42. now = datetime.datetime.now()
  43. if (now - start).seconds > timeout:
  44. return 0
  45. return Uname
  46. except Exception:
  47. return 0
  48. # 列出系统平台 x86 or x64
  49. def GetSysArch(addr,port,timeout):
  50. try:
  51. command = "engine.exe -s {} -p {} -k system.sw.arch".format(addr, port).split(" ")
  52. start = datetime.datetime.now()
  53. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  54. while process.poll() is None:
  55. time.sleep(1)
  56. now = datetime.datetime.now()
  57. if (now - start).seconds > timeout:
  58. return 0
  59. arch = process.stdout.readlines()[0].split()[0]
  60. return str(arch,"utf-8")
  61. except Exception:
  62. return 0
  63. # 获取CPU核心数
  64. def GetCPUCoreNumber(addr,port,timeout):
  65. try:
  66. Command = "engine.exe -s {} -p {} -k system.cpu.num[online]".format(addr,port)
  67. start = datetime.datetime.now()
  68. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  69. CpuCoreNum = process.stdout.readlines()[0].split()[0]
  70. #print()
  71. return str(CpuCoreNum,"utf-8")
  72. except Exception:
  73. return 0
  74. # 获取CPU的利用率 10%
  75. def GetCPUCoreInfo(addr,port,timeout):
  76. try:
  77. Command = "engine.exe -s {} -p {} -k system.cpu.util".format(addr, port)
  78. start = datetime.datetime.now()
  79. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  80. CPU = math.ceil(float(process.stdout.readlines()[0].split()[0]))
  81. while process.poll() is None:
  82. time.sleep(1)
  83. now = datetime.datetime.now()
  84. if (now - start).seconds > timeout:
  85. return 0
  86. return CPU
  87. except Exception:
  88. return 0
  89. # 获取CPU 的负载值 avg1 avg5 avg15
  90. def GetCPULoadAvg(addr,port,avg,timeout):
  91. try:
  92. Command = "engine.exe -s {} -p {} -k system.cpu.load[,{}]".format(addr, port,avg)
  93. start = datetime.datetime.now()
  94. process = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  95. CPU = float(process.stdout.readlines()[0].split()[0])
  96. while process.poll() is None:
  97. time.sleep(1)
  98. now = datetime.datetime.now()
  99. if (now - start).seconds > timeout:
  100. return 0
  101. return CPU
  102. except Exception:
  103. return 0
  104. # 获取内存数据 返回总内存/剩余内存
  105. def GetMemInfo(addr,port,timeout):
  106. try:
  107. Total = subprocess.Popen("engine.exe -s {} -p {} -k vm.memory.size[total]".format(addr, port)
  108. , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  109. Free = subprocess.Popen("engine.exe -s {} -p {} -k vm.memory.size[free]".format(addr, port)
  110. , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  111. Total = math.ceil(int(Total.stdout.readlines()[0].split()[0])/1024/1024)
  112. Free = math.ceil(int(Free.stdout.readlines()[0].split()[0])/1024/1024)
  113. return Total,Free
  114. except Exception:
  115. return 0
  116. # 获取全部磁盘容量
  117. def GetDiskInfo(self):
  118. try:
  119. Free = subprocess.Popen("engine.exe -s {} -p {} -k vfs.fs.size[/,pfree]".format(self.addr, self.port)
  120. , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  121. Free = float(Free.stdout.readlines()[0].split()[0])
  122. return Free
  123. except Exception:
  124. return 0
  125. # 获取特定进程是否运行
  126. def GetProcessStatus(addr,port,procname):
  127. command = "engine.exe -s {} -p {} -k proc.num[\"{}\"]".format(addr,port,procname)
  128. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  129. ref = process.stdout.readlines()[0]
  130. if ref == b"1\r\n":
  131. return 1
  132. return 0
  133. # 获取端口开放状态
  134. def GetNetworkPort(addr,port,check_port):
  135. command = "engine.exe -s {} -p {} -k net.tcp.listen[{}]".format(addr,port,check_port)
  136. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  137. ref = process.stdout.readlines()[0]
  138. if ref == b"1\r\n":
  139. return 1
  140. return 0

监控unix系列,Unix_core.py

  1. import paramiko
  2. ssh = paramiko.SSHClient()
  3. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  4. # 执行命令CMD
  5. def BatchCMD(address,username,password,port,command):
  6. try:
  7. ssh.connect(hostname=address,username=username,password=password,port=port,timeout=2)
  8. stdin , stdout , stderr = ssh.exec_command(command)
  9. result = stdout.read()
  10. if len(result) != 0:
  11. return result
  12. else:
  13. return -1
  14. except Exception:
  15. return -1
  16. # 通过获取主机Ping状态
  17. def GetPing():
  18. fp = open("unix_base.db", "r", encoding="utf-8")
  19. count = len(open("unix_base.db", "r", encoding="utf-8").readlines())
  20. print("-" * 100)
  21. print("{0:20} \t {1:10} \t {2:13} \t {3:5} \t {4:9} \t {5:40}".format("IP地址","机器系统","设备SN","机房位置","存活状态","主机作用"))
  22. print("-" * 100)
  23. for each in range(count):
  24. ref = eval(fp.readline())
  25. ret = BatchCMD(ref[0],ref[5],ref[6],22,"pwd | echo $?")
  26. if(int(ret)==0):
  27. print("{0:20} \t {1:10} \t {2:11} \t {3:5} \t {4:9} \t {5:40}".
  28. format(ref[0],ref[1],ref[2],ref[3],"正常",ref[4]))
  29. else:
  30. print("{0:20} \t {1:10} \t {2:13} \t {3:5} \t {4:9} \t {5:40}".
  31. format(ref[0],ref[1],ref[2],ref[3],"异常",ref[4]))
  32. fp.close()
  33. # ps aux | grep "usbCfgDev" | grep -v "grep" | awk {'print $2'}
  34. def GetProcessStatus():
  35. fp = open("unix_process.db", "r", encoding="utf-8")
  36. count = len(open("unix_process.db", "r", encoding="utf-8").readlines())
  37. for each in range(count):
  38. proc = eval(fp.readline())
  39. proc_len = len(proc)
  40. print("-" * 70)
  41. print("---> 巡检地址: {0:10} \t 登录用户: {1:7} \t 登录密码: {2:10}".format(proc[0],proc[1],proc[2]))
  42. print("-" * 70)
  43. for process in range(3, proc_len):
  44. command = "ps aux | grep \'{}\' | grep -v \'grep\' | awk '{}' | head -1".format(proc[process],"{print $2}")
  45. try:
  46. ref = BatchCMD(proc[0],proc[1],proc[2],22,command)
  47. if(int(ref)!=-1):
  48. print("进程: {0:18} \t PID: {1:10} \t 状态: {2}".format(proc[process], int(ref),"√"))
  49. else:
  50. print("进程: {0:18} \t PID:{1:10} \t 状态: {2}".format(proc[process], 0,"×"))
  51. except Exception:
  52. print("进程: {0:18} \t PID:{1:10} \t 状态: {2}".format(proc[process], 0,"×"))
  53. print()
  54. fp.close()
  55. def GetDiskStatus():
  56. fp = open("unix_disk.db", "r", encoding="utf-8")
  57. count = len(open("unix_disk.db", "r", encoding="utf-8").readlines())
  58. for each in range(count):
  59. proc = eval(fp.readline())
  60. proc_len = len(proc)
  61. print("-" * 100)
  62. print("---> 巡检地址: {0:10} \t 登录系统: {1:7} \t 登录账号: {2:10} 登录密码: {3:10}".
  63. format(proc[0],proc[1],proc[2],proc[3]))
  64. print("-" * 100)
  65. try:
  66. ref = BatchCMD(proc[0], proc[2], proc[3], 22, "df | grep -v 'Filesystem'")
  67. st = str(ref).replace("\\n", "\n")
  68. print(st.replace("b'", "").replace("'", ""))
  69. except Exception:
  70. pass
  71. print()
  72. fp.close()
  73. # 运行命令
  74. def RunCmd(command,system):
  75. fp = open("unix_disk.db", "r", encoding="utf-8")
  76. count = len(open("unix_disk.db", "r", encoding="utf-8").readlines())
  77. for each in range(count):
  78. proc = eval(fp.readline())
  79. proc_len = len(proc)
  80. if proc[1] == system:
  81. print("-" * 100)
  82. print("---> 巡检地址: {0:10} \t 登录系统: {1:7} \t 登录账号: {2:10} 登录密码: {3:10}".
  83. format(proc[0],proc[1],proc[2],proc[3]))
  84. print("-" * 100)
  85. try:
  86. ref = BatchCMD(proc[0], proc[2], proc[3], 22, command)
  87. st = str(ref).replace("\\n", "\n")
  88. print(st.replace("b'", "").replace("'", ""))
  89. except Exception:
  90. pass
  91. fp.close()

配置文件

  1. unix_base.db
  2. ["127.0.0.1","Suse","CN11111","C-F-04","国漫 CTI3.6","root","1111111"]
  3. unix_disk.db
  4. ["127.0.0.1","Suse","root","123123"]
  5. unix_process.db
  6. ["127.0.0.1","root","123123","oracle","mysqld"]
  7. webserver.db
  8. ["127.0.0.1",8005,"跨省投诉-在线客服跨省协办"]
  9. win32_base.db
  10. ["127.0.0.1","Windows XP","0000000","0-0-0","本地跳板机"]
  11. win32_disk.db
  12. ["127.0.0.1","c:","d:"]
  13. win32_port.db
  14. ["127.0.0.1","80","3421","8080"]
  15. win32_process.db
  16. ["127.0.0.1","ilmt_tray.exe","awhost32.exe"]

比较好的改进写法

上方代码中每个表都有一份账号密码,很麻烦,第二次重写我通过一个UUID序号,来定位用户名密码等登录信息,然后在一个配置文件中包含了所有配置项,程序中对不同的项目进行解析,来实现一个配置文件配置所有的配置项,只有基础base结构存储账号密码,每个base结构对应一个UUID号,当添加进程等表时,自动根据UUID号码,来解析账号密码,这样通过序号关联,只需写一份密码即可,通过UUID相关联。

使用Django开发图形化界面

收集目标主机数据的类:

  1. import os,subprocess,sys,math
  2. class GetSysInfo(object):
  3. def __init__(self,addr,port):
  4. self.addr = addr
  5. self.port = port
  6. def GetHostName(self):
  7. try:
  8. Command = "get.exe -s {} -p {} -k system.hostname".format(self.addr,self.port)
  9. proc = subprocess.Popen(Command, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  10. HostName = str(proc.stdout.readlines()[0].split()[0])
  11. return HostName
  12. except Exception:
  13. return 0
  14. def GetCPUInfo(self):
  15. try:
  16. Command = "get.exe -s {} -p {} -k system.cpu.util".format(self.addr, self.port)
  17. proc = subprocess.Popen(Command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  18. CPU = math.ceil(float(proc.stdout.readlines()[0].split()[0]))
  19. return CPU
  20. except Exception:
  21. return 0
  22. def GetMemInfo(self):
  23. try:
  24. Total = subprocess.Popen("get.exe -s {} -p {} -k vm.memory.size[total]".format(self.addr, self.port)
  25. , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  26. Free = subprocess.Popen("get.exe -s {} -p {} -k vm.memory.size[free]".format(self.addr, self.port)
  27. , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  28. Total = math.ceil(int(Total.stdout.readlines()[0].split()[0])/1024/1024)
  29. Free = math.ceil(int(Free.stdout.readlines()[0].split()[0])/1024/1024)
  30. return Total,Free
  31. except Exception:
  32. return 0
  33. def GetDiskInfo(self):
  34. try:
  35. Free = subprocess.Popen("get.exe -s {} -p {} -k vfs.fs.size[/,pfree]".format(self.addr, self.port)
  36. , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  37. Free = float(Free.stdout.readlines()[0].split()[0])
  38. return Free
  39. except Exception:
  40. return 0
  41. def GetNetInfo(self):
  42. try:
  43. InModule = subprocess.Popen("get.exe -s {} -p {} -k net.if.in[ens32,bytes]".format(self.addr, self.port)
  44. , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  45. InModule = int(InModule.stdout.readlines()[0].split()[0])
  46. OutModule = subprocess.Popen("get.exe -s {} -p {} -k net.if.out[ens32,bytes]".format(self.addr, self.port)
  47. , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  48. OutModule = int(OutModule.stdout.readlines()[0].split()[0])
  49. return InModule,OutModule
  50. except Exception:
  51. return 0
  52. a = GetSysInfo("192.168.1.20","10050")
  53. b = a.GetNetInfo()
  54. print(b)

admin.py

Python

models.py

  1. from django.db import models
  2. class HostInfo(models.Model):
  3. id = models.AutoField(primary_key = True)
  4. HostAddr = models.CharField(max_length=64,verbose_name="主机地址")
  5. HostName = models.CharField(max_length=64,verbose_name="主机名称")
  6. HostCPU = models.CharField(max_length=64,verbose_name="CPU利用率")
  7. HostMem = models.CharField(max_length=64,verbose_name="内存数据")
  8. HostDisk = models.CharField(max_length=64,verbose_name="磁盘空闲")
  9. HostNet = models.CharField(max_length=64,verbose_name="网卡流量")

先来判断是否有指定的IP地址,有的话后端直接爬取数据并填充到数据库中,要求是只需要输入IP地址即可取出所有的数据,并自动填充,有几台自动填充几台。

  1. if __name__ == "__main__":
  2. conn = sqlite3.connect("C:/Users/LyShark/PycharmProjects/MyProject/db.sqlite3")
  3. cursor = conn.cursor()
  4. cursor.execute('select * from MyWeb_hostinfo;')
  5. data = cursor.fetchall()
  6. for item in range(0,len(data)):
  7. addr = data[item][1]
  8. info = GetSysInfo(addr,"10050")
  9. print(info.GetNetInfo())

fabric的使用技巧 fabric工具也是自动化运维利器,其默认依赖于paramiko的二次封装.

  1. # 简单实现命令执行
  2. from fabric import Connection
  3. conn = Connection(host="192.168.1.10",user="root",port="22",connect_kwargs={"password":"123"})
  4. try:
  5. with conn.cd("/var/www/html/"):
  6. ret = conn.run("ls -lh",hide=True)
  7. print("主机:" + conn.host + "端口:" + conn.port + "完成")
  8. except Exception:
  9. print("主机:" + conn.host + "端口:" + conn.port + "失败")
  10. # 读取数据到本地
  11. from fabric import Connection
  12. conn = Connection(host="192.168.1.20",user="root",port="22",connect_kwargs={"password":"123"})
  13. uname = conn.run('uname -s', hide=True)
  14. if 'Linux' in uname.stdout:
  15. command = "df -h / | tail -n1 | awk '{print $5}'"
  16. print(conn.run(command,hide=True).stdout.strip())
  17. # 文件上传与下载
  18. from fabric import Connection
  19. conn = Connection(host="192.168.1.20",user="root",port="22",connect_kwargs={"password":"123"})
  20. conn.put("D://zabbix_get.exe","/tmp/zabbix.exe") # 文件上传
  21. conn.get("/tmp/zabbix.exe","./zab.exe") # 下载文件
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/775067
推荐阅读
相关标签
  

闽ICP备14008679号