#!/usr/bin/env python3
#create at 2018-12-04
'this is a system monitor scripts'
__author__="yjt" import os
import time
import sys
import datetime
import socket #用于获取主机名
import psutil #用于获取CPU等信息
import re #以下是变量值,自己定义
CPUT = 2 #计算CPU利用率的时间间隔
NETT = 2 #计算网卡流量的时间间隔
LOOPT = 2 #脚本循环时间间隔 #获取系统基本信息
def baseinfo():
hostname = socket.gethostname()
user_conn = len(psutil.users())
start_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
now_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
# sys_runtime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time() - psutil.boot_time()))
sys_runtime = os.popen('w').readline().split('users')[0].split('up')[1].strip()[:-1].strip()[:-1]
process = os.popen('ps -ef |wc -l').read().split()[0]
return {"hostname":hostname,"user_conn":user_conn,"sys_start_time":start_time,"now_time":now_time,"sys_runtime":sys_runtime,"process":process}
print('')
print(baseinfo())
#获取CPU信息
def cpuinfo():
ave_load = os.popen('uptime').readline().split(":")[-1].split()
ave_load = ' '.join(ave_load) #CPU平均负载
#以下四项值都是获取的瞬时值
user_time = psutil.cpu_times().user #用户态使用CPU时间
sys_time = psutil.cpu_times().system #系统态使用CPU时间
idle_time = psutil.cpu_times().idle #CPU空闲时间
iowait_time = psutil.cpu_times().iowait #IO等待时间
total_cpu = 0
for i in range(len(psutil.cpu_times())):
total_cpu += psutil.cpu_times()[i]
user_use = str(round(user_time / total_cpu * 100,2)) + '%'
sys_use = str(round(sys_time / total_cpu * 100,2)) + '%'
idle = str(round(idle_time / total_cpu * 100,2)) + '%'
iowait = str(round(iowait_time / total_cpu * 100,2)) + '%'
cpu_pre = str(psutil.cpu_percent(CPUT)) + "%"
logical_cpu = psutil.cpu_count()
pyhsical_cpu = psutil.cpu_count(logical=False)
#获取CPU使用最高的前十行
top10 = len(os.popen('ps aux|grep -v PID|sort -rn -k +3|head -10').readlines())
# 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}
l1,l2,l3,l4,l5,l6 = [],[],[],[],[],[]
for i in range(10):
#user = os.popen('ps aux|grep -v PID|sort -rn -k +4|head').readlines().[info].split()[0]
pid = int(os.popen('ps aux|grep -v PID|sort -rn -k +3|head -10').readlines()[i].split()[1])
info = psutil.Process(pid)
user = info.username()
process_name = info.exe()
cpu_use = str(info.cpu_percent()) + '%'
status = info.status()
l1.append(user)
l2.append(pid)
l3.append(cpu_use)
l4.append(process_name)
l5.append(status) #def cpu():
#以下获取的是逻辑CPU的瞬时值
with open('/proc/stat','r') as f:
cpu_item = f.readlines()
for i in cpu_item:
if re.search("^cpu[0-9]{1,}",i):
cpu_info = i
cpu_info = cpu_info.split(' ')
cpu_number = cpu_info[0]
cpu_total = 0
for num in cpu_info:
if num.isdigit():
cpu_total += float(num)
cpu_free = float(cpu_info[4])
cpu_use = str(round((1 - cpu_free / cpu_total) * 100 ,2)) + '%'
# print(cpu_number,cpu_use) return {
"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,
"logical_cpu_use":[{"cpu_number":cpu_number},{"cpu_use":cpu_use}],
"cpu_top10":[
({"user":l1[0]},{"pid":l2[0]},{"cpu_use":l3[0]},{"process_name":l4[0]},{"status":l5[0]}),
({"user":l1[1]},{"pid":l2[1]},{"cpu_use":l3[1]},{"process_name":l4[1]},{"status":l5[1]}),
({"user":l1[2]},{"pid":l2[2]},{"cpu_use":l3[2]},{"process_name":l4[2]},{"status":l5[2]}),
({"user":l1[3]},{"pid":l2[3]},{"cpu_use":l3[3]},{"process_name":l4[3]},{"status":l5[3]}),
({"user":l1[4]},{"pid":l2[4]},{"cpu_use":l3[4]},{"process_name":l4[4]},{"status":l5[4]}),
({"user":l1[1]},{"pid":l2[5]},{"cpu_use":l3[5]},{"process_name":l4[5]},{"status":l5[5]}),
({"user":l1[5]},{"pid":l2[6]},{"cpu_use":l3[6]},{"process_name":l4[6]},{"status":l5[6]}),
({"user":l1[7]},{"pid":l2[7]},{"cpu_use":l3[7]},{"process_name":l4[7]},{"status":l5[7]}),
({"user":l1[8]},{"pid":l2[8]},{"cpu_use":l3[8]},{"process_name":l4[8]},{"status":l5[8]}),
({"user":l1[9]},{"pid":l2[9]},{"cpu_use":l3[9]},{"process_name":l4[9]},{"status":l5[9]})
]
}
print('')
print(cpuinfo())
#获取内存信息
def meminfo():
total_mem = str(round(psutil.virtual_memory().total / 1024 /1024/1024)) + 'G'
use_mem = str(round(psutil.virtual_memory().used / 1024 /1024/1024)) + 'G'
mem_percent = str(psutil.virtual_memory().percent) + '%'
free_mem = str(round(psutil.virtual_memory().free / 1024 /1024/1024)) + 'G'
swap_mem = str(round(psutil.swap_memory().total / 1024 /1024/1024)) + "G"
swap_use = str(round(psutil.swap_memory().used / 1024 /1024/1024 )) + 'G'
swap_free = str(round(psutil.swap_memory().free / 1024 /1024/1024)) + 'G'
swap_percent = str(psutil.swap_memory().percent) + '%'
#获取memory使用最高的前十行
top10 = len(os.popen('ps aux|grep -v PID|sort -rn -k +4|head -10').readlines())
# 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}
l1,l2,l3,l4,l5,l6 = [],[],[],[],[],[]
for i in range(10):
#user = os.popen('ps aux|grep -v PID|sort -rn -k +4|head').readlines().[info].split()[0]
pid = int(os.popen('ps aux|grep -v PID|sort -rn -k +4|head -10').readlines()[i].split()[1])
info = psutil.Process(pid)
user = info.username()
process_name = info.exe()
mem_use = str(round(info.memory_percent(),2)) + '%'
status = info.status()
l1.append(user)
l2.append(pid)
l3.append(mem_use)
l4.append(process_name)
l5.append(status)
return {
"total_mem":total_mem,
"use_mem":use_mem,
"free_mem":free_mem,
"mem_percent":mem_percent,
"swap_mem":swap_mem,
"swap_use":swap_use,
"swap_free":swap_free,
"swap_percent":swap_percent,
"mem_top10":[
({"user":l1[0]},{"pid":l2[0]},{"mem_use":l3[0]},{"process_name":l4[0]},{"status":l5[0]}),
({"user":l1[1]},{"pid":l2[1]},{"mem_use":l3[1]},{"process_name":l4[1]},{"status":l5[1]}),
({"user":l1[2]},{"pid":l2[2]},{"mem_use":l3[2]},{"process_name":l4[2]},{"status":l5[2]}),
({"user":l1[3]},{"pid":l2[3]},{"mem_use":l3[3]},{"process_name":l4[3]},{"status":l5[3]}),
({"user":l1[4]},{"pid":l2[4]},{"mem_use":l3[4]},{"process_name":l4[4]},{"status":l5[4]}),
({"user":l1[1]},{"pid":l2[5]},{"mem_use":l3[5]},{"process_name":l4[5]},{"status":l5[5]}),
({"user":l1[5]},{"pid":l2[6]},{"mem_use":l3[6]},{"process_name":l4[6]},{"status":l5[6]}),
({"user":l1[7]},{"pid":l2[7]},{"mem_use":l3[7]},{"process_name":l4[7]},{"status":l5[7]}),
({"user":l1[8]},{"pid":l2[8]},{"mem_use":l3[8]},{"process_name":l4[8]},{"status":l5[8]}),
({"user":l1[9]},{"pid":l2[9]},{"mem_use":l3[9]},{"process_name":l4[9]},{"status":l5[9]})
]
}
print('')
print(meminfo())
#获取磁盘信息
def diskinfo():
#print("\033[31mdisk_info:\033[0m")
#print("disk%-10s total%-10s free%-10s used%-10s percent%-10s"%('','(G)','(G)','(G)','(%)'))
d1,d2,d3,d4,d5 = [],[],[],[],[]
disk_total,disk_used,disk_free = 0,0,0
disk_len = len(psutil.disk_partitions())
for info in range(disk_len):
disk = psutil.disk_partitions()[info][1]
if len(disk) < 10:
d1.append(disk)
total = str(round(psutil.disk_usage(disk).total /1024/1024/1024)) + 'G'
total_num = psutil.disk_usage(disk).total
disk_total += total_num
free = str(round(psutil.disk_usage(disk).free /1024/1024/1024)) + 'G'
disk_free += psutil.disk_usage(disk).free
used = str(round(psutil.disk_usage(disk).used /1024/1024/1024)) + 'G'
disk_used += psutil.disk_usage(disk).used
percent = str(psutil.disk_usage(disk).percent) + '%'
d2.append(total)
d3.append(free)
d4.append(used)
d5.append(percent)
disk_used_percent = str(round(disk_used / disk_total * 100,2)) + '%'
disk_free_percent = str(round(disk_free / disk_total * 100,2)) + '%'
disk_total = str(round(disk_total /1024/1024/1024)) + "G"
disk_free = str(round(disk_free /1024/1024/1024)) + "G"
disk_used = str(round(disk_used /1024/1024/1024)) + "G"
return {
"disk":[
{"disk_total":disk_total},
{"disk_free":disk_free},
{"disk_used":disk_used},
{"disk_used_percent":disk_used_percent},
{"disk_free_percent":disk_free_percent}
],
"partitions": [
{"mount":(d1)},
{"total":(d2)},
{"free":(d3)},
{"used":(d4)},
{"percent":(d5)}
]
}
print('')
print(diskinfo())
#diskinfo() #获取网卡信息
def netinfo():
net_item = list(psutil.net_if_addrs())
for net in net_item:
if re.search(r'bond.*|em.*|eno.*|^eth.*',net):
network_card = net
ip = psutil.net_if_addrs()[net][0].address
recv_1,recv_2,send_1,send_2=0,0,0,0
with open ('/proc/net/dev','r') as f:
net_info = f.readlines()
net_list = str(net_info).lower().split()
if net_list[0] == net:
recv_1 = float(net_list[1])
send_1 = float(net_list[9])
time.sleep(NETT)
with open ('/proc/net/dev','r') as f:
net_info = f.readlines()
net_list = str(net_info).lower().split()
if net_list[0] == net:
recv_2 = float(net_list[1])
send_2 = float(net_list[9])
received = str(recv_2/1024 - recv_1/1024) + "kb/s"
transmit = str(send_2/1024 - send_1/1024) + "kb/s"
return {
"network":[
{"network_card":network_card},
{"ip":ip},
{"transmit":transmit},
{"received":received}
]
}
print('')
print(netinfo())
#获取TCP连接数
def tcpinfo():
status_list = ["LISTEN","ESTABLISHED","TIME_WAIT","CLOSE_WAIT","LAST_ACK","SYN_SENT"]
status_init = []
net_conn = psutil.net_connections()
n1 = []
for key in net_conn:
status_init.append(key.status)
for value in status_list:
num = status_init.count(value)
n1.append(num)
return {
"LISTEN":n1[0],
"ESTABLISHED":n1[1],
"TIME_WAIT":n1[2],
"CLOSE_WAIT":n1[3],
"LAST_ACK":n1[4],
"SYN_SENT":n1[5]
}
print('')
print(tcpinfo())

  

python3 系统监控脚本(2) (监控CPU,内存等信息)的更多相关文章

  1. tomcat监控脚本(监控进程,测试接口,告警动作为发送邮件)

    服务器环境:centos7.2 64位 tomcat8.5.6 tomcat 监控功能共需要两个脚本,如下: initMonitor.sh #!/bin/sh #初始化监控脚本相关变量 export ...

  2. shell监控脚本实例—监控mysql主从复制

    分享一例shell脚本,用于监测mysql数据库的主从复制,有需要的朋友不妨参考学习下. 转自:http://www.jbxue.com/article/14103.html(转载请注明出处) 本节内 ...

  3. Linux Shell 网络层监控脚本(监控包括:连接数、句柄数及根据监控反馈结果分析)

    脚本监控: 获取最大句柄数的进程: 链接分析: 脚本片段: case "$handle" in 2) echo "The handle of the process : ...

  4. Java程序员也应该知道的系统知识系列之(网卡,cpu,内存,硬盘,虚拟化)

    https://yq.aliyun.com/articles/1718?spm=5176.100240.searchblog.16.UaGd04 https://yq.aliyun.com/artic ...

  5. Zabbix Linux http 监控脚本

    说明:自定义监控脚本,监控内存是否启用主进程 创建文件:vim check_http.sh #!/bin/bash result=`ps -ef | grep httpd | grep -v grep ...

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

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

  7. Python 监控脚本(硬盘、cpu、内存、网卡、进程)

    #磁盘使用率disk = psutil.disk_partitions()for i in disk:    print "磁盘:%s   分区格式:%s"%(i.device,i ...

  8. Linux 性能监控之CPU&内存&I/O监控Shell脚本2

    Linux 性能监控之CPU&内存&I/O监控Shell脚本2   by:授客 QQ:1033553122 思路: 捕获数据->停止捕获数据->提取数据 备注:一些命令的输 ...

  9. Linux 性能监控之CPU&内存&I/O监控Shell脚本1

    Linux 性能监控之CPU&内存&I/O监控Shell脚本1   by:授客 QQ:1033553122   #!/bin/bash # 获取要监控的本地服务器IP地址 IP=`if ...

  10. linux系统中的基础监控(硬盘,内存,系统负载,CPU,网络等)

      Linux系统常见日常监控 系统信息 查看 CentOS 版本号:cat /etc/redhat-release 综合监控 nmon 系统负载 命令:w(判断整体瓶颈) 12:04:52 up 1 ...

随机推荐

  1. "多层感知器"--MLP神经网络算法

    提到人工智能(Artificial Intelligence,AI),大家都不会陌生,在现今行业领起风潮,各行各业无不趋之若鹜,作为技术使用者,到底什么是AI,我们要有自己的理解. 目前,在人工智能中 ...

  2. 快开宝PDA开单器出入库扫码:让批发零售变得更简单

    快开宝PDA开单器出现前 批发商户是这样开单和管理的 ★员工痛苦:需要记客户.价格.库存等等,应对报错价.错漏单.盘错货等各种状况. ★老板麻烦:每天要守店.对单.核账,经常因错漏单.库存乱.积压货. ...

  3. Canvas 绘制一个像素风电子时钟

    想法是在 Canvas 上绘制由小方块组成的数字. 第一步是实现绘制小方块的方法,先画出一个边长为 5 的 10x10 个方块,使用两个 for 循环很简单就能完成. for (let i = 0; ...

  4. vue实现组件切换的两种方式

    <!DOCTYPE html> <html> <head> <title>组件的切换</title> <meta charset=&q ...

  5. Android NDK 学习之Android.mk

    Android.mk file syntax specification Introduction: This document describes the syntax of Android.mk  ...

  6. Xshell 上传文件到Ubuntu

    打开Xshell,连上一台Linux服务器或者是虚拟机 如果要方便的上传文件,需要rz 先测试是否安装rz 命令行~$ rz 如果出现未安装(或者command not found)且建议sudo a ...

  7. 理解下所谓的ssh隧道

    目录 一.含义 二.功能 三.Linux下应用的案例 参考文章 一.含义 client为了访问到server的服务,但是由于防火墙的阻拦,client没有办法通过正常访问来进行,这就用到了ssh隧道. ...

  8. git使用方法(持续更新)

    2018/5/9 最基本的操作: 添加文件.文件夹.所有文件: git add test.py   //添加单个文件 git add src        //添加文件夹 git add .      ...

  9. 提速1000倍,预测延迟少于1ms,百度飞桨发布基于ERNIE的语义理解开发套件

    提速1000倍,预测延迟少于1ms,百度飞桨发布基于ERNIE的语义理解开发套件 11月5日,在『WAVE Summit+』2019 深度学习开发者秋季峰会上,百度对外发布基于 ERNIE 的语义理解 ...

  10. 25.C# 异步调用Web服务

    1.创建Web服务 1.1VS新建ASP.Net空Web应用程序 1.2添加Web服务新建项 1.3添加GetWeather方法和相关类 using System; using System.Coll ...