#!/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等)的更多相关文章

  1. python3 系统监控脚本(2) (监控CPU,内存等信息)

    #!/usr/bin/env python3 #create at 2018-12-04 'this is a system monitor scripts' __author__="yjt ...

  2. Linux 服务器系统监控脚本 Shell【转】

    转自: Linux 服务器系统监控脚本 Shell - 今日头条(www.toutiao.com)http://www.toutiao.com/i6373134402163048961/ 本程序在Ce ...

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

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

  4. Prometheus Node_exporter 之 CPU Memory Net Disk

    1. CPU type: GraphUnit: shortmax: "100"min: "0"Label: PercentageSystem - cpu 在内核 ...

  5. jmeter监控linux cpu 内存 网络 IO

    下载地址:http://jmeter-plugins.org/downloads/all/ PerfMon: 用来监控Server的CPU.I/O.Memory等情况 ServerAgent-2.2. ...

  6. Nagios-Nagios-Nagios系统监控(centos7部署源码)

    一.Nagios简介 Nagios是一款开源的电脑系统和网络监视工具,能有效监控Windows.Linux和Unix的主机状态,交换机路由器等网络设置,打印机等.在系统或服务状态异常时发出邮件或短信报 ...

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

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

  8. linux 系统的负载与CPU、内存、硬盘、用户数监控脚本[marked]

    转载文章 原始出处  在没有nagios监控的情况下,只要服务器能上互联网,就可通过发邮件的方式来提醒管理员系统资源的使用情况. 一.编写linux系统告警邮件脚本 # vim /scripts/sy ...

  9. shell脚本监控系统负载、CPU和内存使用情况

    hostname >>/home/vmuser/xunjian/xj.logdf -lh >>/home/vmuser/xunjian/xj.logtop -b -n 1 | ...

随机推荐

  1. C# 用Redis实现的分布式锁

    Redis实现分布式锁(悲观锁/乐观锁) 对锁的概念和应用场景在此就不阐述了,网上搜索有很多解释,只是我搜索到的使用C#利用Redis的SetNX命令实现的锁虽然能用,但是都不太适合我需要的场景. 基 ...

  2. Vuex 刷新后数据丢失问题 Typescript

    问题描述:Vuex保存的数据在页面刷新后会全部丢失清除 问题解决方案:使用sessionstorage进行保存,在页面刷新时保存至sessionStorage,页面在加载时再进行填充   (另有vue ...

  3. wampserver的使用配置

    1.正常安装就不说了,只需要把安装位置改成需要的位置就可以了.其它的默认就可以了. 2.安装完成之后打开wampserver. 3.现在该修改密码了: (1)点击进入mysql控制台. (2)Wamp ...

  4. Privacy Description

    This application respects and protects the privacy of all users who use the service. In order to pro ...

  5. unity 刚体

    刚体属性(rigidbody)标明物体受物理影响,包括重力,阻力等等. mass为重量,当大质量物体被小重量物体碰撞时只会发生很小的影响.. Drag现行阻力决定组件在没有发生物理行为下停止移动的速度 ...

  6. Python——hashlib(加密模块)

    主要用于对字符串的加密,最常用的为MD5加密: import hashlib def get_md5(data): obj = hashlib.md5() obj.update(data.encode ...

  7. HTML基础之HTML常用标签

    下面小编为大家整理一些HTML的常用标签 a.布局标签 div标签定义文档中的分区或节(division/section),可以把文档分割为独立的.不同的部分,主要用于布局. aside标签的内容可用 ...

  8. 常用实验报告LaTex 模板

    目录 模板1-无首页有表格头 模板2-有首页 模板1-无首页有表格头 % -*- coding: utf-8 -*- \documentclass{article} \usepackage{listi ...

  9. C++(三十四) — 友元函数、友元类

    友元是可以访问类的私有成员和保护成员的外部函数.由 friend 修饰,不是本类的成员函数,但是在它的函数体中可以通过对象名访问本类的私有和保护成员.     友元关系不可传递,且是单向的.    友 ...

  10. 4.kafka生产者---向Kafka中写入数据(转)

    转:  https://www.cnblogs.com/sodawoods-blogs/p/8969513.html (1)生产者概览 (1)不同的应用场景对消息有不同的需求,即是否允许消息丢失.重复 ...