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:               #把 try提到for循環下。
 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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM