1. #!/usr/bin/env python3
  2. #-*- coding:utf-8 -*-
  3. #create at 2018-12-07
  4. 'this is a system monitor scripts'
  5. __author__="yjt"
  6.  
  7. import os
  8. import time
  9. import sys
  10. import datetime
  11. import socket
  12. import psutil
  13. import re
  14. import json
  15.  
  16. #以下是变量值,自己定义
  17. CPUT = 2 #计算CPU利用率的时间间隔
  18. NETT = 2 #计算网卡流量的时间间隔"""
  19. #LOOPT = 2 """#脚本循环时间间隔"""
  20.  
  21. #获取系统基本信息"""
  22. def baseinfo():
  23. hostname = socket.gethostname()
  24. user_conn = len(psutil.users())
  25. start_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
  26. now_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
  27. # sys_runtime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time() - psutil.boot_time()))
  28. sys_runtime = os.popen('w').readline().split('users')[0].split('up')[1].strip()[:-1].strip()[:-1]
  29. process = os.popen('ps -ef |wc -l').read().split()[0]
  30. value = {"hostname":hostname,"user_conn":user_conn,"sys_start_time":start_time,"now_time":now_time,"sys_runtime":sys_runtime,"process":process}
  31. value_json = json.dumps(value)
  32. return value_json
  33. print('')
  34. print(baseinfo())
  35. #获取CPU信息
  36. def cpuinfo():
  37. ave_load = os.popen('uptime').readline().split(":")[-1].split()
  38. ave_load = ' '.join(ave_load) #CPU平均负载
  39. #以下四项值都是获取的瞬时值
  40. user_time = psutil.cpu_times().user #用户态使用CPU时间
  41. sys_time = psutil.cpu_times().system #系统态使用CPU时间
  42. idle_time = psutil.cpu_times().idle #CPU空闲时间
  43. iowait_time = psutil.cpu_times().iowait #IO等待时间
  44. total_cpu = 0
  45. for i in range(len(psutil.cpu_times())):
  46. total_cpu += psutil.cpu_times()[i]
  47. user_use = str(round(user_time / total_cpu * 100,2)) + '%'
  48. sys_use = str(round(sys_time / total_cpu * 100,2)) + '%'
  49. idle = str(round(idle_time / total_cpu * 100,2)) + '%'
  50. iowait = str(round(iowait_time / total_cpu * 100,2)) + '%'
  51. cpu_pre = str(psutil.cpu_percent(CPUT)) + "%"
  52. logical_cpu = psutil.cpu_count()
  53. pyhsical_cpu = psutil.cpu_count(logical=False)
  54. #获取CPU使用最高的前十行
  55. #top10 = len(os.popen('ps aux|grep -v PID|sort -rn -k +3|head -10').readlines())
  56. # dic1 = {"ave_load":ave_load,"user_use":user_use,"sys_use":sys_use,"idle":idle,"iowait":iowait,"cpu_pre":cpu_pre,"logical_cpu":logical_cpu,"pyhsical_cpu":pyhsical_cpu}
  57. l1,l2,l3,l4,l5,l6 = [],[],[],[],[],[]
  58. i = 0
  59. while i < 10:
  60. #user = os.popen('ps aux|grep -v PID|sort -rn -k +4|head').readlines().[info].split()[0]
  61. #pid = int(os.popen('ps aux|grep -v PID|sort -rn -k +3|head -10').readlines()[i].split()[1])
  62. #a = os.popen('ps aux |sort -k3 -nr').readlines()[i].split()
  63. try:
  64. info = ''
  65. info = psutil.Process(int(os.popen("ps aux|grep -v PID|sort -rn -k +3").readlines()[i].split()[1]))
  66. #if bool(info):
  67. #pid = psutil.Process(int(os.popen('ps aux|grep -v PID|sort -rn -k +3').readlines()[i].split()[1])).pid
  68. pid = info.pid
  69. user = info.username()
  70. process_name = info.name()
  71. cpu_use = str(info.cpu_percent()) + '%'
  72. status = info.status()
  73. l1.append(user)
  74. l2.append(pid)
  75. l3.append(cpu_use)
  76. l4.append(process_name)
  77. l5.append(status)
  78. i += 1
  79. except:
  80. pass
  81. continue
  82. c0 = []
  83. l = ["user","pid","cpu_use","process_name","status"]
  84. cpu_value = list(zip(l1,l2,l3,l4,l5))
  85. cpu_len = len(cpu_value)
  86. for i in range(cpu_len):
  87. c0.append(dict(zip(l,cpu_value[i])))
  88. #def cpu():
  89. #以下获取的是逻辑CPU的瞬时值
  90. with open('/proc/stat','r') as f:
  91. cpu_item = f.readlines()
  92. cpu_number,cpu_use = [],[]
  93. for i in cpu_item:
  94. if re.search("^cpu[0-9]{1,}",i):
  95. cpu_info = i
  96. cpu_info = cpu_info.split(' ')
  97. #cpu_number = cpu_info[0]
  98. cpu_number.append(cpu_info[0])
  99. cpu_total = 0
  100. for num in cpu_info:
  101. if num.isdigit():
  102. cpu_total += float(num)
  103. cpu_free = float(cpu_info[4])
  104. cpu_u = str(round((1 - cpu_free / cpu_total) * 100 ,2)) + '%'
  105. cpu_list = cpu_u.split()
  106. cpu_str = ''.join(cpu_list)
  107. cpu_use.append(cpu_str)
  108. c1 = []
  109. cpu_l = ["cpu_number","cpu_use"]
  110. cpu_v = list(zip(cpu_number,cpu_use))
  111. cpu_len = len(cpu_v)
  112. for i in range(cpu_len):
  113. c1.append(dict(zip(cpu_l,cpu_v[i])))
  114. value = {
  115. "ave_load":ave_load,
  116. "user_use":user_use,
  117. "sys_use":sys_use,
  118. "idle":idle,
  119. "iowait":iowait,
  120. "cpu_pre":cpu_pre,
  121. "logical_cpu":logical_cpu,
  122. "pyhsical_cpu":pyhsical_cpu,
  123. "logical_cpu_use":c1,
  124. "cpu_top10":c0
  125. }
  126. value_json = json.dumps(value)
  127. return value_json
  128. print('')
  129. print(cpuinfo())
  130. #cpuinfo()
  131. #获取内存信息
  132. def meminfo():
  133. total_mem = str(round(psutil.virtual_memory().total / 1024 /1024/1024)) + 'G'
  134. use_mem = str(round(psutil.virtual_memory().used / 1024 /1024/1024)) + 'G'
  135. mem_percent = str(psutil.virtual_memory().percent) + '%'
  136. free_mem = str(round(psutil.virtual_memory().free / 1024 /1024/1024)) + 'G'
  137. swap_mem = str(round(psutil.swap_memory().total / 1024 /1024/1024)) + "G"
  138. swap_use = str(round(psutil.swap_memory().used / 1024 /1024/1024 )) + 'G'
  139. swap_free = str(round(psutil.swap_memory().free / 1024 /1024/1024)) + 'G'
  140. swap_percent = str(psutil.swap_memory().percent) + '%'
  141. #获取memory使用最高的前十行
  142. #top10 = len(os.popen('ps aux|grep -v PID|sort -rn -k +4|head -10').readlines())
  143. # dic1 = {"ave_load":ave_load,"user_use":user_use,"sys_use":sys_use,"idle":idle,"iowait":iowait,"cpu_pre":cpu_pre,"logical_cpu":logical_cpu,"pyhsical_cpu":pyhsical_cpu}
  144. l1,l2,l3,l4,l5,l6 = [],[],[],[],[],[]
  145. i = 0
  146. while i < 10:
  147. #user = os.popen('ps aux|grep -v PID|sort -rn -k +4|head').readlines().[info].split()[0]
  148. #pid = int(os.popen('ps aux|grep -v PID|sort -rn -k +4|head -10').readlines()[i].split()[1])
  149. try:
  150. info = psutil.Process(int(os.popen('ps aux|grep -v PID|sort -rn -k +4').readlines()[i].split()[1]))
  151. pid = info.pid
  152. user = info.username()
  153. process_name = info.name()
  154. mem_use = str(round(info.memory_percent(),2)) + '%'
  155. status = info.status()
  156. l1.append(user)
  157. l2.append(pid)
  158. l3.append(mem_use)
  159. l4.append(process_name)
  160. l5.append(status)
  161. i += 1
  162. except:
  163. pass
  164. continue
  165. m0 = []
  166. l = ["user","pid","mem_use","process_name","status"]
  167. mem_value = list(zip(l1,l2,l3,l4,l5))
  168. mem_len = len(mem_value)
  169. for i in range(mem_len):
  170. m0.append(dict(zip(l,mem_value[i])))
  171.  
  172. value = {
  173. "total_mem":total_mem,
  174. "use_mem":use_mem,
  175. "free_mem":free_mem,
  176. "mem_percent":mem_percent,
  177. "swap_mem":swap_mem,
  178. "swap_use":swap_use,
  179. "swap_free":swap_free,
  180. "swap_percent":swap_percent,
  181. "mem_top10":m0
  182. }
  183. value_json = json.dumps(value)
  184. return value_json
  185. print('')
  186. print(meminfo())
  187. #获取磁盘信息
  188. def diskinfo():
  189. #print("\033[31mdisk_info:\033[0m")
  190. #print("disk%-10s total%-10s free%-10s used%-10s percent%-10s"%('','(G)','(G)','(G)','(%)'))
  191. disk_num = int(''.join(os.popen("ls /dev/sd[a-z]|wc -l").readlines()[0].split()))
  192. d1,d2,d3,d4,d5 = [],[],[],[],[]
  193. disk_total,disk_used,disk_free = 0,0,0
  194. disk_len = len(psutil.disk_partitions())
  195. for info in range(disk_len):
  196. disk = psutil.disk_partitions()[info][1]
  197. if len(disk) < 10:
  198. d1.append(disk)
  199. total = str(round(psutil.disk_usage(disk).total /1024/1024/1024)) + 'G'
  200. total_num = psutil.disk_usage(disk).total
  201. disk_total += total_num
  202. free = str(round(psutil.disk_usage(disk).free /1024/1024/1024)) + 'G'
  203. disk_free += psutil.disk_usage(disk).free
  204. used = str(round(psutil.disk_usage(disk).used /1024/1024/1024)) + 'G'
  205. disk_used += psutil.disk_usage(disk).used
  206. percent = str(psutil.disk_usage(disk).percent) + '%'
  207. d2.append(total)
  208. d3.append(free)
  209. d4.append(used)
  210. d5.append(percent)
  211. disk_used_percent = str(round(disk_used / disk_total * 100,2)) + '%'
  212. disk_free_percent = str(round(disk_free / disk_total * 100,2)) + '%'
  213. disk_total = str(round(disk_total /1024/1024/1024)) + "G"
  214. disk_free = str(round(disk_free /1024/1024/1024)) + "G"
  215. disk_used = str(round(disk_used /1024/1024/1024)) + "G"
  216. d0 = []
  217. d = ["mount","total","free","used","percent"]
  218. disk_value = list(zip(d1,d2,d3,d4,d5))
  219. disk_len = len(disk_value)
  220. for i in range(disk_len):
  221. d0.append(dict(zip(d,disk_value[i])))
  222. value = {
  223. "disk":[
  224. {"disk_num":disk_num},
  225. {"disk_total":disk_total},
  226. {"disk_free":disk_free},
  227. {"disk_used":disk_used},
  228. {"disk_used_percent":disk_used_percent},
  229. {"disk_free_percent":disk_free_percent}
  230. ],
  231. "partitions":d0
  232. }
  233. value_json = json.dumps(value)
  234. return value_json
  235. print('')
  236. print(diskinfo())
  237. #diskinfo()
  238.  
  239. #获取网卡信息
  240. def netinfo():
  241. net_item = list(psutil.net_if_addrs())
  242. n1,n2,n3,n4,n5,n6 = [],[],[],[],[],[]
  243. for net in net_item:
  244. if re.search(r'bond.*|em.*|eno.*|^eth.*',net):
  245. network_card = net
  246. n1.append(network_card)
  247. ip = psutil.net_if_addrs()[net][0].address
  248. ip_len = len(ip.split('.'))
  249. if ip_len == 4:
  250. ip =ip
  251. else:
  252. ip = 'null'
  253. n2.append(ip)
  254. recv_1,recv_2,send_1,send_2=0,0,0,0
  255. with open ('/proc/net/dev','r') as f:
  256. net_info = f.readlines()[2:]
  257. # net_list = str(net_info).lower().split()
  258. net_len = len(net_info)
  259. for i in range(net_len):
  260. net_n_info = net_info[i].split()
  261. net_list = net_info[i].split(':')[0].strip(' ')
  262. #print(net_list)
  263. if net_list == net:
  264. recv_1 = float(net_n_info[1])
  265. # print(recv_1)
  266. send_1 = float(net_n_info[9])
  267. time.sleep(NETT)
  268. with open ('/proc/net/dev','r') as f:
  269. net_info = f.readlines()[2:]
  270. #net_list = str(net_info).lower().split()
  271. net_len = len(net_info)
  272. for i in range(net_len):
  273. net_n_info = net_info[i].split()
  274. net_list = net_info[i].split(':')[0].strip(' ')
  275. if net_list == net:
  276. recv_2 = float(net_n_info[1])
  277. #print(recv_2)
  278. send_2 = float(net_n_info[9])
  279. received = str(round(recv_2/1024 - recv_1/1024,2)) + "kb/s"
  280. transmit = str(round(send_2/1024 - send_1/1024,2)) + "kb/s"
  281. n3.append(transmit)
  282. n4.append(received)
  283. #print(n3,n4)
  284. #网卡带宽
  285. # net_speed = list(os.popen("ethtool %s|grep -i speed"%(network_card)).readlines())[0].split()[1]
  286. # n5.append(net_speed)
  287. #网卡模式
  288. # net_duplex = list(os.popen("ethtool %s|grep -i Duplex"%(network_card)).readlines())[0].split()[1]
  289. # n6.append(net_duplex)
  290. #print (n1,n2,n3,n4)
  291. n0 = []
  292. # n = ["network_card","ip","transmit","received","net_speed","net_duplex"]
  293. n = ["network_card","ip","transmit","received"]
  294. net_value = list(zip(n1,n2,n3,n4))
  295. net_len = len(net_value)
  296. for i in range(net_len):
  297. n0.append(dict(zip(n,net_value[i])))
  298. value = {
  299. "network":n0
  300. }
  301. value_json = json.dumps(value)
  302. return value_json
  303. print('')
  304. print(netinfo())
  305. #netinfo()
  306. #获取TCP连接数
  307. def tcpinfo():
  308. status_list = ["LISTEN","ESTABLISHED","TIME_WAIT","CLOSE_WAIT","LAST_ACK","SYN_SENT"]
  309. status_init = []
  310. net_conn = psutil.net_connections()
  311. n1 = []
  312. for key in net_conn:
  313. status_init.append(key.status)
  314. for value in status_list:
  315. num = status_init.count(value)
  316. n1.append(num)
  317. value = {
  318. "LISTEN":n1[0],
  319. "ESTABLISHED":n1[1],
  320. "TIME_WAIT":n1[2],
  321. "CLOSE_WAIT":n1[3],
  322. "LAST_ACK":n1[4],
  323. "SYN_SENT":n1[5]
  324. }
  325. value_json = json.dumps(value)
  326. return value_json
  327. print('')
  328. print(tcpinfo())

  注:该脚本也适用于python2,当然,需要安装psutil模块,或者已安装anaconda

python3监控系统资源最终版(获取CPU,内存,磁盘,网卡等信息),返回json格式。的更多相关文章

  1. Linux 简单命令查询CPU、内存、网卡等信息

    [转自]Linux查询CPU.内存.网卡等信息 看CPU信息(型号)# cat /proc/cpuinfo | grep name | cut -f2 -d: |uniq -c      1  Int ...

  2. linux系统CPU,内存,磁盘,网络流量监控脚本

    前序 1,#cat /proc/stat/ 信息包含了所有CPU活动的信息,该文件中的所有值都是从系统启动开始累积到当前时刻 2,#vmstat –s 或者#vmstat 虚拟内存统计 3, #cat ...

  3. 一键获取linux内存、cpu、磁盘IO等信息脚本编写,及其原理详解

    更多linux知识,请关注公众号:一口Linux 一.脚本 今天主要分享一个shell脚本,用来获取linux系统CPU.内存.磁盘IO等信息. #!/bin/bash # 获取要监控的本地服务器IP ...

  4. 使用.NET FrameWork获取CPU,内存使用率以及磁盘空间

    在以前,我们想获取CPU,内存等信息就不得不借助win32 API来实现.但现在,.NET FrameWork已经把这些API封装到.NET类库中了,所以我们可以借助.NET类库很轻松的获取这些信息. ...

  5. C# 获取CPU序列号、网卡MAC地址、硬盘序列号封装类,用于软件绑定电脑

    using System.Management; namespace GLaLa { /// <summary> /// hardware_mac 的摘要说明. /// </summ ...

  6. 获取CPU序列号、网卡MAC地址、硬盘序列号

    <pre name="code" class="csharp"> using System; using System.Collections; u ...

  7. AIX/Linux/HP-UX查看CPU/内存/磁盘/存储命令

    1.1    硬件环境验证方式 硬件环境主要包括CPU.内存.磁盘/存储.网络设备(如F5等).系统特有设备(如密押设备等)等,其中网络设备和系统特有设备由网络管理员或项目组提供为准,本节主要关注CP ...

  8. js获取get方式提交的参数返回json格式数据

    /** * 获取GET提交的参数 * @return JSON格式 * @author Terry */ function getArgs(){ var args = {}; var match = ...

  9. linux系统CPU内存磁盘监控发送邮件脚本

    #!/bin/bashexport PATHexport LANG=zh_CN.UTF-8###top之后输入数字1,可以查看每颗CPU的情况.###先配置好mailx邮箱账号密码:#cat>/ ...

随机推荐

  1. FTP搭建注意事项

    正常的FTP搭建步骤很简单,随便网搜一篇文章就出来了 下面提出一个网址可供学习 https://blog.csdn.net/m0_38044299/article/details/81627607 但 ...

  2. .net mvc 迁移到 .netcore

    迁移的时候发现,ef6 不能添加 到  .NET Standard2  的类库,因为不兼容, 6 以上的版本只能用于  .net 4.5 以上 只能用别的

  3. vue+iview 通过a标签实现文件下载

    vue+iview 通过a标签实现文件下载 方法一: 注意: 如果下载的文件放在本地目录下,一定要将模板文件放到 public 目录下,否则由于权限问题找不到文件 路径: 项目更目录-->pub ...

  4. 我们为什么要通过python来入IT这一行

    我们为什么要通过python来入IT这一行 导语 ​ 这个问题,其实大部分在选择转行做IT,或者在行业内处于边缘化的非技术人员都会有这样的疑惑.毕竟,掌握一门技能,是需要花成本的.决策之前,做个前景判 ...

  5. restTemplate源码解析(目录)

    restTemplate是spring实现的,基于restful风格的http请求模板.使用restTemplate可以简化请求操作的复杂性,同时规范了代码风格.本系列文章,将根据以下目录顺序,从源码 ...

  6. VBA While Wend循环

    在While...Wend循环中,如果条件为True,则会执行所有语句,直到遇到Wend关键字. 如果条件为false,则退出循环,然后控件跳转到Wend关键字后面的下一个语句. 语法 以下是VBA中 ...

  7. iOS - Scenekit3D引擎初探之 - 给材质贴图

    今天简单说一下 SceneKit 给材质贴图. 1,最简单的一种方法,直接打开dae 或者 scn 文件直接设置  如上图,这个dae 文件中只有一个几何体,几何体中只有一个材质球,然后设置材质球的d ...

  8. 【转载】使用Response.WriteFile输出文件以及图片

    Response对象是Asp.Net应用程序中非常重要的一个内置对象,其作用为负责将服务器执行好的信息输出给客户端,可以使用Response.WriteFile方法来像客户端输出文件或者图片,输出图片 ...

  9. 张量(tensor)的广播

    在使用numpy 对张量(数组)进行操作时,两个形状相同的张量进行加减等运算很容易理解,那么不同形状的张量之间的运算是通过广播来实现的.广播实际上很简单,但是弄清楚是也花了不小功夫,这里记录一下. 广 ...

  10. 【JUC】2.synchronized

    synchronized关键字的用法也不做太多笔记了,简单回顾一下: synchronized三种使用方式: 修饰实例方法: 线程获取的是当前调用此方法的对象的对象头:即:锁是当前对象: public ...