Python 运维自动化之服务器信息采集

主要是采集服务器的CPU,内存,硬盘,网络等信息。

用到的主要模块psutil还有subprocess,要注意管道问题(subprocess.popen函数的参数注意使用)。

上代码

  1 def test2():
  2     fnull = open(os.devnull, 'w')
  3     return1 = subprocess.call('ping 127.0.0.1 -n 1', shell=True, stdout=fnull, stderr=fnull)
  4     rt = (return1 == 0)
  5     if rt:
  6         print(28)
  7     else:
  8         print(30)
  9     return rt
 10 
 11 def sh(command):           #命令行获取硬盘信息
 12     p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
 13     result = p.stdout.read().decode('gbk')
 14     return result
 15 def sh_receive():
 16     disk_c = ''
 17     usedg_c = 0
 18     hardDisk_c = {}
 19     try:
 20         if os.name == 'nt':
 21             disks = sh("wmic logicaldisk get deviceid").split('\r\r\n')[1:-2]
 22             for disk in disks:
 23                 if disk.strip():
 24                     res = sh('fsutil volume diskfree %s' % disk).split('\r\n')[:-2]
 25                     free = int(res[0].split(':')[1])
 26                     all_bit = int(res[1].split(':')[1])
 27                     total = round(all_bit / 1024 / 1024, 2)  # mb
 28                     totalg = int(total / 1024)  # gb
 29                     used = round((all_bit - free) / 1024 / 1024, 2)  # mb
 30                     usedg = int(used / 1024)  # gb
 31                     Idle = round(free / 1024 / 1024, 2)  # mb
 32                     ram = round(used / total, 2)
 33                     disk_c += "{}GB/{}GB#".format(usedg, totalg)  # 新加的
 34                     usedg_c += Idle
 35                     hardDisk_c[disk.strip()] = {"total": total, "used": used, "Idle": Idle, "ram": ram}
 36         return (disk_c, usedg_c, hardDisk_c)
 37     except Exception as e:
 38         print(e)
 39         return (disk_c, usedg_c, hardDisk_c)
 40 
 41 def netInfo():                          #ip网卡信息
 42     new_ip = {}
 43     new_mac = {}
 44     cache_ip = ""
 45     cache_mac = ""
 46     dic = psutil.net_if_addrs()
 47     for adapter in dic:
 48         snicList = dic[adapter]
 49         mac = False  # '无 mac 地址'
 50         ipv4 = False  # '无 ipv4 地址'
 51         ipv6 = '无 ipv6 地址'
 52         for snic in snicList:
 53             if snic.family.name in {'AF_LINK', 'AF_PACKET'}:
 54                 mac = snic.address
 55             elif snic.family.name == 'AF_INET':
 56                 ipv4 = snic.address
 57         if ipv4 and ipv4 != '127.0.0.1':
 58             new_ip[adapter] = str(ipv4)
 59             cache_ip += '{}#'.format(str(ipv4))
 60         if mac:
 61             if len(mac) == 17:
 62                 new_mac[adapter] = str(mac)
 63                 cache_mac += '{}#'.format(str(mac))
 64     return (new_ip, new_mac, cache_ip, cache_mac)
 65 def netSpeed():
 66     net2 = psutil.net_io_counters()                            #pernic=True 可以查看每一个网卡的传输量
 67     old_bytes_sent = round(net2.bytes_recv / 1024, 2)     #kb
 68     old_bytes_rcvd = round(net2.bytes_sent / 1024, 2)
 69     time.sleep(1)
 70     net3 = psutil.net_io_counters()
 71     bytes_sent = round(net3.bytes_recv / 1024, 2)
 72     bytes_rcvd = round(net3.bytes_sent / 1024, 2)
 73     netSpeedOutgoing = bytes_sent - old_bytes_sent
 74     netSpeedInComing = bytes_rcvd - old_bytes_rcvd
 75     return (netSpeedOutgoing, netSpeedInComing)
 76 
 77 class ServerPicker:
 78     def __init__(self):
 79         # 网络连接
 80         self.onlineStatus = int(test2())
 81         # CPU 占用率
 82         self.cpuUtilization = psutil.cpu_percent(0)
 83         # 总内存,内存使用率,使用内存,剩余内存
 84         mem = psutil.virtual_memory()
 85         # 所有单位均为byte字节,1 KB = 1024 bytes,1 MB = 1024 KB,1 GB = 1024 MB
 86         # total:内存总大小   percent:已用内存百分比(浮点数)     used:已用内存      free:可用内存
 87         self.totalRAM = round(mem.total / 1024 / 1024, 2)  # mb
 88         self.totalRAMg = round(mem.total / 1024 / 1024 / 1024, 2)  # gb
 89         self.ramUtilization = round(mem.percent, 2)
 90         self.usedRAM = round(mem.used / 1024 / 1024, 2)  # mb
 91         self.usedRAMg = round(mem.used / 1024 / 1024 / 1024, 2)  # gb
 92         self.IdleRAM = round(mem.free / 1024 / 1024, 2)  # mb
 93         self.IdleRAMg = round(mem.free / 1024 / 1024 / 1024, 2)  # gb
 94         # 硬盘=个数和每个硬盘的总容量、使用容量、和剩余容量及使用率
 95         self.disk, self.usedg, self.hardDisk = sh_receive()
 96         # 系统开机时间
 97         # powerOnTime=datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
 98         t = int(psutil.boot_time())
 99         self.powerOnTime = str(datetime.datetime.fromtimestamp(t))
100         # 系统开机时长
101         self.powerOnDuration = int(time.time())
102         # # 获取多网卡MAC地址
103         # # 获取ip地址
104         self.ip, self.mac, self.cache_ip, self.cache_mac = netInfo()
105         # 网络收发速率
106         self.netSpeedOutgoing, self.netSpeedInComing = netSpeed()

猜你喜欢

转载自www.cnblogs.com/dashui123/p/10094083.html