Python 運維自動化之伺服器資訊採集
阿新 • • 發佈:2018-12-09
主要是採集伺服器的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()