python3 系统监控脚本(CPU,memory,网络,disk等)
#!/usr/bin/env python3
#create at 2018-11-30
'this is a system monitor scripts'
__author__="yjt" import os
import time
import sys
import datetime
import socket #用于获取主机名
import psutil #用于获取CPU等信息(该模块属于第三方模块,需要安装;或者安装anaconda3,anaconda3默认已经安装好改模块)
import re #以下是变量值,自己定义
CPUT = 2 #计算CPU利用率的时间间隔
NETT = 2 #计算网卡流量的时间间隔
LOOPT = 2 #脚本循环时间间隔 #获取系统基本信息
def baseinfo():
hostname = socket.gethostname()
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]
print("\033[31mbase_info:\033[0m")
print("hostname: %-10s"%(hostname))
print("start_time: %-15s"%(start_time))
print("now_time: %-15s"%(now_time))
print("sys_runtime: %-10s"%(sys_runtime))
def userconninfo():
print("\033[31muser_conn_info:\033[0m")
user_conn = len(psutil.users())
print("user_conn_num:%s"%(user_conn))
print("conn_user%-10s conn_terminal%-10s remmote_ip%-10s start_time%-15s pid%-15s"%('','','','',''))
for info in range(user_conn):
user = psutil.users()[info].name
terminal = psutil.users()[info].terminal
host = psutil.users()[info].host
start_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(psutil.users()[0].started))
pid = psutil.users()[info].pid
#print("conn_user:%-10s conn_terminal:%-10s from_host:%-15s start_time:%-20s pid:%-10d"%(user,terminal,host,start_time,pid))
print("%-19s %-23s %-20s %-25s %-15d"%(user,terminal,host,start_time,pid))
#获取CPU信息
def cpuinfo():
ave_load = os.popen('uptime').readline().split(":")[-1].split()
ave_load = ' '.join(ave_load) #CPU平均负载
#以下四项值都是获取的瞬时值
user_use = psutil.cpu_times().user #用户态使用CPU时间
sys_use = psutil.cpu_times().system #系统态使用CPU时间
idle = psutil.cpu_times().idle #CPU空闲时间
iowait = psutil.cpu_times().iowait #IO等待时间
total_cpu = 0
for i in range(len(psutil.cpu_times())):
total_cpu += psutil.cpu_times()[i]
cpu_pre = psutil.cpu_percent(CPUT)
logical_cpu = psutil.cpu_count()
pyhsical_cpu = psutil.cpu_count(logical=False)
print("\033[31mcpu_info:\033[0m")
print("cpu_ave_load: %-20s" %ave_load)
print("cpu_user_use: %-.2f%%" %(user_use / total_cpu * 100))
print("cpu_sys_use: %-.2f%%" %(sys_use / total_cpu * 100))
print("cpu_idle: %-.2f%%" %(idle / total_cpu * 100 ))
print("cpu_iowait: %-.2f%%" %(iowait / total_cpu * 100 ))
print("cpu_ave_use: %-.2f%%" %cpu_pre)
print("logica_cpu: %-4d"%logical_cpu) #获取逻辑CPU个数
print("pyhsical_cpu: %-4d"%pyhsical_cpu)#获取物理CPU个数
#获取内存信息
def meminfo():
total_mem = psutil.virtual_memory().total
use_mem = psutil.virtual_memory().used
mem_percent = psutil.virtual_memory().percent
free_mem = psutil.virtual_memory().free
swap_mem = psutil.swap_memory().total
swap_use = psutil.swap_memory().used
swap_free = psutil.swap_memory().free
swap_percent = psutil.swap_memory().percent
print("\033[31mmem_info:\033[0m")
print("total_mem: %d M"%(total_mem / 1024 /1024))
print("use_mem: %d M"%(use_mem / 1024 /1024))
print("free_mem: %d M"%(free_mem / 1024 /1024))
print("mem_percent: %s%%"%(mem_percent))
print("swap_mem: %d M"%(swap_mem / 1024 /1024))
print("swap_use: %d M"%(swap_use / 1024 /1024))
print("swap_free: %d M"%(swap_free / 1024 /1024))
print("swap_percent: %s%%"%(swap_percent))
#获取磁盘信息
def diskinfo():
print("\033[31mdisk_info:\033[0m")
print("disk%-10s total%-10s free%-10s used%-10s percent%-10s"%('','(G)','(G)','(G)','(%)'))
disk_len = len(psutil.disk_partitions())
for info in range(disk_len):
disk = psutil.disk_partitions()[info][1]
if len(disk) < 10:
total = str(round(psutil.disk_usage(disk).total /1024/1024/1024)) + 'G'
free = str(round(psutil.disk_usage(disk).free /1024/1024/1024)) + 'G'
used = str(round(psutil.disk_usage(disk).used /1024/1024/1024)) + 'G'
percent = str(psutil.disk_usage(disk).percent) + '%'
print('%-15s'%(disk),end='')
#print(' %-10s total: %-10s free: %-10s used:%-10s percent:%-s'%('',total,free,used,percent))
print('%-13s %-13s %-13s %-s'%(total,free,used,percent))
#获取网卡信息
def netinfo():
print('\033[31mnet_info\033[0m')
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])
print("network_card%-10s ip%-20s received%-10s transmit%-10s "%('','','(kb/s)','(kb/s)'))
#print("network_card: %-10s ip: %-20s received: %-.3f Kb/s transmit: %-.3f kb/s" % (network_card,ip,(recv_2/1024 - recv_1/1024),(send_2/1024 - send_1/1024)))
print("%-21s %-22s %-.3f%13s %-.3f " % (network_card,ip,(recv_2/1024 - recv_1/1024),'',(send_2/1024 - send_1/1024)))
#获取TCP连接数
def tcpinfo():
print('\033[31mtcp_info\033[0m')
status_list = ["LISTEN","ESTABLISHED","TIME_WAIT","CLOSE_WAIT","LAST_ACK","SYN_SENT"]
status_init = []
net_conn = psutil.net_connections()
for key in net_conn:
status_init.append(key.status)
for value in status_list:
print(value,status_init.count(value)) if __name__ == '__main__':
while True:
try:
os.system('clear')
baseinfo()
print("********************************************************")
userconninfo()
print("########################################################")
cpuinfo()
print("========================================================")
meminfo()
print("########################################################")
diskinfo()
print("********************************************************")
netinfo()
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
tcpinfo()
time.sleep(LOOPT)
except KeyboardInterrupt as e:
print ('')
print("Bye-Bye")
sys.exit(0)
或者:
#!/usr/bin/env python3
#create at 2018-11-29
'this is a system monitor scripts'
__author__="yjt" import os
import time
import sys
import datetime
import socket #用于获取主机名
import psutil #用于获取CPU信息
def sysinfo():
hostname = socket.gethostname()
sys_runtime = os.popen('w').readline().split('users')[0].split('up')[1].strip()[:-1].strip()[:-1]
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()))
user_conn = os.popen('w').readline().split('users')[0].split('up')[1].strip()[-1]
print("\033[31msysinfo:\033[0m")
print("Hostname: {0}".format(hostname))
print("Sys_runtime: {0}".format(sys_runtime))
print("start_Time: {0}".format(start_time))
print("now_Time: {0}".format(now_time))
print("User_Conn: {0}".format(user_conn))
def cpuinfo():
""" get cpuinfo from '/proc/stat' """
with open('/proc/stat','r') as f:
#f = open('/proc/stat','r')
cpu = f.readline()
#f.close()
cpu = cpu.split(' ')
total_1 = 0
for info in cpu:
if info.isdigit():
total_1 += float(info)
cpu_1 = float(cpu[5]) #空闲态占用CPU时间
#以下三种状态计算瞬时值
cpu_2 = float(cpu[2]) #用户态占用CPU时间
cpu_3 = float(cpu[4]) #系统态占用CPU时间
cpu_4 = float(cpu[6]) #IO等待时间 time.sleep(2)
total_2 = 0
with open('/proc/stat','r') as f:
cpu = f.readline()
cpu = cpu.split(' ')
total_2 = 0
for info in cpu:
if info.isdigit():
total_2 += float(info)
cpu_5 = float(cpu[5])
cpu_idle = cpu_5 - cpu_1
total_time = total_2 - total_1
cpu_use = 1 - cpu_idle / total_time
ave_load = os.popen('uptime').readline().split(":")[-1].split()
ave_load = ' '.join(ave_load) #CPU平均负载
logical_cpu = psutil.cpu_count()
pyhsical_cpu = psutil.cpu_count(logical=False)
print("\033[31mcpuinfo: \033[0m")
print("cpu_ave_load: %s" %ave_load)
print("cpu_user_use: %.2f%%" %(cpu_2/total_1 * 100))
print("cpu_sys_use: %.2f%%" %(cpu_3/total_1 * 100))
print("cpu_io_wait: %.2f%%" %(cpu_4/total_1 * 100))
print("cpu_ave_use: %.2f%%" %cpu_use)
print("logica_cpu: %d"%logical_cpu) #获取逻辑CPU个数
print("pyhsical_cpu: %d"%pyhsical_cpu)#获取物理CPU个数 def meminfo():
with open('/proc/meminfo','r') as f:
mem = f.readlines()
total,free,buffers,cached,swap_total,swap_free = 0,0,0,0,0,0
for info in mem:
mem_item = info.lower().split()
if mem_item[0] == 'memtotal:':
total = float(mem_item[1])
if mem_item[0] == 'memfree:':
free = float(mem_item[1])
if mem_item[0] == 'buffers:':
buffers = float(mem_item[1])
if mem_item[0] == 'cached:':
cached = float(mem_item[1])
if mem_item[0] == 'swaptotal:':
swap_total = float(mem_item[1])
if mem_item[0] == 'swapfree:':
swap_free = float(mem_item[1])
user_use = total - buffers - cached
user_use_swap = swap_total - swap_free
user_usemem_rate = user_use / total * 100
user_useswap_rate = user_use_swap / swap_total * 100
print("\033[31mmeminfo:\033[0m")
print("total_mem: %d M"%(total / 1024))
print("free_mem: %d M"%(free / 1024))
print("user_use_rate: %.2f%%"%user_usemem_rate)
print("swap_total: %d M"%(swap_total / 1024))
print("swap_free: %d M"%(swap_free / 1024))
print("user_useswap_rate: %.2f%%"%user_useswap_rate) def diskinfo():
# pass
disk = os.popen('df -h').readlines()
for info in disk:
disk_item = info.split()
if disk_item[-1] == '/':
disk_root = disk_item[-1]
disk_root_total = disk_item[1]
disk_root_use = disk_item[2]
disk_root_rate = disk_item[4]
if disk_item[-1] == '/home':
disk_home = disk_item[-1]
disk_home_total = disk_item[1]
disk_home_use = disk_item[2]
disk_home_rate = disk_item[4]
if disk_item[-1] == '/boot':
disk_boot = disk_item[-1]
disk_boot_total = disk_item[1]
disk_boot_use = disk_item[2]
disk_boot_rate = disk_item[4]
if disk_item[-1] == '/data':
disk_data = disk_item[-1]
disk_data_total = disk_item[1]
disk_data_use = disk_item[2]
disk_data_rate = disk_item[4] #disk_io = psutil.disk_io_counters(perdisk=True) print("\033[31mdiskinfo:\033[0m")
print("root: %-10s root_total: %-5s root_use: %-5s root_use_pre: %-5s"%(disk_root,disk_root_total,disk_root_use,disk_root_rate))
print("home: %-10s home_total: %-5s home_use: %-5s home_use_pre: %-5s"%(disk_home,disk_home_total,disk_home_use,disk_home_rate))
print("boot: %-10s boot_total: %-5s boot_use: %-5s boot_use_pre: %-5s"%(disk_boot,disk_boot_total,disk_boot_use,disk_boot_rate))
print("data: %-10s data_total: %-5s data_use: %-5s data_use_pre: %-5s"%(disk_data,disk_data_total,disk_data_use,disk_data_rate))
def netinfo():
pass if __name__ == '__main__':
while True:
try:
os.system('clear')
sysinfo()
print("********************************************************")
cpuinfo()
print("========================================================")
meminfo()
print("########################################################")
diskinfo()
time.sleep(5)
except KeyboardInterrupt as e:
print ('')
print("Bye-Bye")
sys.exit(0)
python3 系统监控脚本(CPU,memory,网络,disk等)的更多相关文章
- python3 系统监控脚本(2) (监控CPU,内存等信息)
#!/usr/bin/env python3 #create at 2018-12-04 'this is a system monitor scripts' __author__="yjt ...
- Linux 服务器系统监控脚本 Shell【转】
转自: Linux 服务器系统监控脚本 Shell - 今日头条(www.toutiao.com)http://www.toutiao.com/i6373134402163048961/ 本程序在Ce ...
- linux系统中的基础监控(硬盘,内存,系统负载,CPU,网络等)
Linux系统常见日常监控 系统信息 查看 CentOS 版本号:cat /etc/redhat-release 综合监控 nmon 系统负载 命令:w(判断整体瓶颈) 12:04:52 up 1 ...
- Prometheus Node_exporter 之 CPU Memory Net Disk
1. CPU type: GraphUnit: shortmax: "100"min: "0"Label: PercentageSystem - cpu 在内核 ...
- jmeter监控linux cpu 内存 网络 IO
下载地址:http://jmeter-plugins.org/downloads/all/ PerfMon: 用来监控Server的CPU.I/O.Memory等情况 ServerAgent-2.2. ...
- Nagios-Nagios-Nagios系统监控(centos7部署源码)
一.Nagios简介 Nagios是一款开源的电脑系统和网络监视工具,能有效监控Windows.Linux和Unix的主机状态,交换机路由器等网络设置,打印机等.在系统或服务状态异常时发出邮件或短信报 ...
- linux系统CPU,内存,磁盘,网络流量监控脚本
前序 1,#cat /proc/stat/ 信息包含了所有CPU活动的信息,该文件中的所有值都是从系统启动开始累积到当前时刻 2,#vmstat –s 或者#vmstat 虚拟内存统计 3, #cat ...
- linux 系统的负载与CPU、内存、硬盘、用户数监控脚本[marked]
转载文章 原始出处 在没有nagios监控的情况下,只要服务器能上互联网,就可通过发邮件的方式来提醒管理员系统资源的使用情况. 一.编写linux系统告警邮件脚本 # vim /scripts/sy ...
- shell脚本监控系统负载、CPU和内存使用情况
hostname >>/home/vmuser/xunjian/xj.logdf -lh >>/home/vmuser/xunjian/xj.logtop -b -n 1 | ...
随机推荐
- Windows Mobile设备中心不能正常运行
1.开始-->运行,输入services.msc回车 2.在打开的服务界面中,找到“基于Windows Mobile 2003的连接设备” 3.打开的属性 ,找到登录项,登录身份选择“本地系统账 ...
- Pytorch 1.0升级到Pytorch 1.1.0
Pytorch 1.0Pytorch 1.0于2018-12-8发布,详见https://github.com/pytorch/pytorch/releases/tag/v1.0.0 主要更新JIT全 ...
- 1+x证书学习日志——css常用属性
## css常用属性: 1:文本属性: 文本大小: font-size:18px; 文本颜色 colo ...
- var img = new Image()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- element table中使用el-select
效果: 然后看代码: 注意事项: el-select的v-model要和option的value值对应,注意是string还是number类型哦- 此文转载别人
- javascript_08-while 和 do while
while 和 do while for 当循环次数已知 while 先判断再执行 do while 先执行一次再判断 //1-100 之间所有数字的和 //while // var i = 1; / ...
- servlet版本与tomcat版本对应关系,各版本web.xml头信息写法
The mapping between the specifications and the respective Apache Tomcat versions is: Servlet Spec JS ...
- 【问题】man命令打开的手册上链接怎么展开?
参考:How to follow links in linux man pages? 前言 在使用man查看命令帮助的时候,有些文字下面会有下划线.给人的感觉是一个链接,但是又打不开.那么到底是不是链 ...
- IOTA私有链简单搭建
IOTA 参考:https://github.com/iotaledger/wallet 参考:https://github.com/iotaledger/iota.js 参考:https://git ...
- Python 写入训练日志文件并控制台输出
1. 背景 在深度学习的任务中,通常需要比较长时间的训练,因此我们会选择离开电脑.笔者在跟踪模型表现, 观察模型accuracy 以及 loss 的时候,比较传统的方法是在控制台print输出或者直接 ...