利用Python实现系统监控脚本

利用Python实现系统监控脚本

简介

该 Python 脚本,用于监控计算机或网络的性能和状态。该脚本可用于跟踪各种指标,例如 CPU 使用率、内存使用率、磁盘空间、网络流量和系统正常运行时间。该脚本还可用于监视某些事件或条件,例如错误的发生或特定服务的可用性。
该脚本使用 psutil 模块中的 cpu_percent、virtual_memory 和 disk_usage 函数分别检索当前的 CPU 使用率、内存使用率和磁盘使用率。virtual_memory 函数返回一个具有各种属性的对象,例如内存总量以及已用和空闲内存量。disk_usage 函数将路径作为参数并返回一个对象,该对象具有诸如磁盘上的总空间量以及已用和可用空间量等属性。

代码
import psutil

# Get the current CPU usage
cpu_usage = psutil.cpu_percent()

# Get the current memory usage
memory_usage = psutil.virtual_memory().percent

# Get the current disk usage
disk_usage = psutil.disk_usage("/").percent

# Get the network activity
# Get the current input/output data rates for each network interface
io_counters = psutil.net_io_counters(pernic=True)
for interface, counters in io_counters.items():
    print(f"Interface {interface}:")
    print(f"  bytes sent: {counters.bytes_sent}")
    print(f"  bytes received: {counters.bytes_recv}")

# Get a list of active connections
connections = psutil.net_connections()
for connection in connections:
    print(f"{connection.laddr} <-> {connection.raddr} ({connection.status})")

# Print the collected data
print(f"CPU usage: {cpu_usage}%")
print(f"Memory usage: 1.11MB%")
print(f"Disk usage: {disk_usage}%")

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值