码迷,mamicode.com
首页 > 编程语言 > 详细

python日常运维

时间:2019-09-15 18:30:39      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:efi   charts   sage   type   app   ddr   dump   strftime   网卡   

import psutil
import time
from time import sleep
import datetime
import os
import sys
import json
import requests
class MessyServerHardware():
def __int__(self):
self.time_now = time.strftime("%Y-%m-%d %H:%M:%s",time.localtime(time.time()))
self.__serverStartTime = datetime.datetime.fromisoformat(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
def cpu(self):
count = psutil.cpu_count(logical=False) # 查看cpu物理个数
self._cpu = str(psutil.cpu_percent(interval=2, percpu=False)) + ‘%‘# CPU的使用率 interval是获取2s内的cpu使用率波动
return ‘CPU的使用率‘+self._cpu

def memory(self):
self.total = str(round(psutil.virtual_memory().total/(1024.0 * 1024.0 *1024.0 ),2)) # 查看内存大小
self.free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 *1024.0 ),2)) #剩余内存
self._memory = int(psutil.virtual_memory().total - psutil.virtual_memory().free) / float(psutil.virtual_memory().total) # 物理内存使用率(DDR)
self.me = str(int(self._memory * 100)) + ‘%‘
return ‘total‘+self.total,‘free‘+self.free,‘物理内存使用率‘+self.me

def user(self):
self.users_count = len(psutil.users()) # 当前登录用户名
self._users_list = ",".join([u.name for u in psutil.users()]) # 用户个数
return ‘用户个数‘+str(self.users_count),‘当前登录用户名‘+str(self._users_list)


def bytes2symbols(self,bytes_value):
‘‘‘单位符号‘‘‘
symbols = (‘K‘, ‘M‘, ‘G‘, ‘T‘, ‘P‘, ‘E‘, ‘Z‘, ‘Y‘)
# 每个单位对应的bytes数的字典,先定义为空
prefix = {}
for i,s in enumerate(prefix):
# ‘‘‘enumerate()为列举函数‘‘‘
# ‘‘‘i:代表下标‘‘‘
# ‘‘‘s:代表改下标对应的值‘‘‘
# ‘‘‘取到符号元组的值,作为prfix字典的key,根据key给value进行赋值‘‘‘
prefix[s] = 1024 ** (i + 1)
# ‘‘‘打印得到的对应字典‘‘‘
# print(prefix)
symbols_value = 0
symbol = ‘‘
# ‘‘‘循环prefix字典,得到转换值‘‘‘
for key, value in prefix.items():
if bytes_value >= value:
symbols_value = bytes_value / value
symbol = key
# 如果不满足最小的KB,则以B显示
elif bytes_value < 1024:
return ‘%0.2fB‘ % bytes_value
# ‘‘‘返回转换值(str)‘‘‘
return ‘%0.2f%sB‘ % (symbols_value, symbol)

def platform_judge(self):
# 将平台信息小写返回
platform = sys.platform.lower()
return platform

def disk_io_message(self):
t1 = psutil.disk_io_counters()
sleep(1)
t2 = psutil.disk_io_counters()
read_bytes = self.bytes2symbols(t2.read_bytes - t1.read_bytes)
write_bytes = self.bytes2symbols(t2.write_bytes - t1.write_bytes)
tps = t2.read_count + t2.write_count - t1.read_count - t1.write_count
‘‘‘判断平台,命令清屏‘‘‘
if self.platform_judge() == ‘linux‘:
os.system(‘clear‘)
else:
os.system(‘cls‘)
return (‘读/s:%10s‘%read_bytes),(‘写/s:%10s‘%write_bytes)+‘\n‘,(‘Tps:%10d‘%tps)

def network(self):
self.net = psutil.net_io_counters()
self._bytes_rcvd = ‘{0:.2f} Mb‘.format(self.net.bytes_sent / 1024 / 1024) # 网卡接收流量
self._bytes_sent = ‘{0:.2f} Mb‘.format(self.net.bytes_recv / 1024 / 1024) # 网卡发送流量
return ‘网卡接收流量‘+self._bytes_rcvd,‘网卡发送流量‘+self._bytes_sent


if __name__ == ‘__main__‘:
stra = []
M =MessyServerHardware()
stra.append(time.strftime(‘%Y-%m-%d %H:%M:%S‘))
stra.append(M.cpu())
stra.append(M.memory())
stra.append(M.user())
stra.append(M.disk_io_message())
stra.append(M.network())
url = ‘https://oapi.dingtalk.com/robot/send?access_token=91a38bc1a6afc21b23bf450a058baa9baa6d3beb7fcad1b431db18c97c258ce4‘
headers = {"Content-Type": "application/json", "Chartset": "utf-8"}
data = {"msgtype": "text", "text": {"content": "%s " % (stra)},"at": {"atMobiles": [], "isAtAll": False}}
data1 = json.dumps(data)
requests.post(url=url, headers=headers, data=data1)

python日常运维

标签:efi   charts   sage   type   app   ddr   dump   strftime   网卡   

原文地址:https://www.cnblogs.com/ZZYMiss/p/11523573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!