Python|Ubuntu的后台远程监控

Ubuntu系统上的基于Python的后台监控脚本

@version: Python 3.8.5 + Ubuntu 18.0.4
@task: 完成 系统后台的内存与硬件的检测与监控

准备工作

所需模块

  1. psutil 模块 用来实现监控功能

    pip3 install psustil

    pip3进行安装,同时了解一下psutil内部的功能函数

    cpu _ count() ==> 捕获虚拟内核的信息
    如果cpu_count(logical=False ) 可以捕获实际物理内核的信息
    cpu _ percent() ==> 必要的参数 interval(间隔)=time 可以控制监控的次数与频率
    同时应该记得实现一个相对应的模块,假设可能不回滚来浪费不必要的cpu时间片
    virtual _ memory() ==> 追踪所占的虚拟内存
    disk _ usage() ==> 可以查看指定路径的的磁盘使用量,默认情况下是当前所在目录。
    psutil.disk _ usage().percent ==> 获取硬盘和内存的部分使用率
    psutil.memory _ usage().total ==> 获取硬盘和内存的总共容量(以字节为单位),可以进行转换,转换公式如下,value ☞ 函数所得返回值
    1 Gbytes = value / pow(1024,3)

    Tips:如果想在中断运行此脚本可以有三种方式

    1. 改变脚本权限,chmod +x script,然后在进行编译运行
    2. 在脚本开头增加编译器位置,script header #!/usr/bin/python3
    3. 在虚拟环境下直接使用run命令 ,如果存在虚拟环境的画要切换到指定的虚拟环境下进行执行。

    首先可以获得当前时间的时间戳 需要引入datetime模块

    #!/bin/bash
    import datetime
    current_time = datetime.datetime.now().strftime("%F %T")
    # strftime(格式化字符类型的占位符)
    # datetime.now()获取毫秒时间戳
    	
    
  2. 用*yagmail*模块来进行发送告警邮件
    pip3 install yagmail

    	#!/usr/bin/python3
    	import yagmail
    	# may possess receiver and sender
    	# create the obj(sender,sendercode,server)
    	ya_obj = yagmail.SMTP(user="emailcom",password="not passwd",host="mmtp.163.com") # server use 网易 
    	# may need the sendercode use python to finished the email to send
    	content = ""
    	# send(receiver,title,content)
    	ya_obj.send(receiver,"Warning",content)
    

    当cpu占比大于80%或者内存使用率大于90%,使用模块发送指定用户指定信息

    	#!/usr/bin/python3
    	import yagmail
    	# may possess receiver and sender
    	if cpu.per > 80 or memory_info.percent > 90:
    	
    		# create the obj(sender,sendercode,server)
    		ya_obj = yagmail.SMTP(user="emailcom",password="not passwd that email granted code",host="mmtp.163.com") # server use 网易 
    		#granted code 授权码 可以在网易邮箱内查找
    		# may need the sendercode use python to finished the email to send
    		# send(receiver,title,content)
    		ya_obj.send(receiver,"[Warning]: System Monitor Report",log_str)
    		
    

    将以上所提及的知识点进行结合,还缺少一种实时性,所以,如何实现呢?可以通过psutil内部的cpu.cpu_percent(interval=Time)通过修改参数Time间隔获取CPU的使用情况。
    同时,可以打印成日志表格log_str,而且可以写入log_back.txt来进行日志存档,一边来评估服务器或这PC的性能。

实现日志和本地存档

  1. 实现日志
    简单来说,日志方便记录一定阶段内的服务器的性能,其内容包括时间,CPU的内核数,内存和硬盘的使用量和总量,还有网络的吞吐量。

    	current_time = dt.datetime.now().strftime("%F %T") 
    	log_str = "|---------------------------------------------------------------------------|\n"
    	log_str += "|    	Time      | CPU %d core|Memory %.2f G| Disk %dG |     net_io  		|\n"%(psu.cpu_count(logical=False),memory_info.total/pow(TRANSFORM_KEY,3),disk_info.total/pow(TRANSFORM_KEY,3))
    	
    	log_str += "|---------------------------------------------------------------------------|\n"
    	log_str += "|%s|    %s%%    |   %s%%    |   %s%%  |    %s\%s |\n"%(current_time,cpu_per,memory_info.percent,disk_info.percent,net_info.bytes_recv,net_info.bytes_sent)
    	 
    	log_str += "|---------------------------------------------------------------------------|\n"
    	
    	log_str += "|---------------------------------------------------------------------------|\n"
    	
    	
    	print(log_str)
    
  2. 本地存档
    本地存档存在文档的IO流操作,可以回顾一下Python的文档的IO流操作。

    文档的操作常用的方法有open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)write(fd, str)close(fd)readlines(hint=-1)等。不过常用的就是把大象装进冰箱的三大步open<打开冰箱门>write<把大象放进去>close<关上冰箱门>
    Attention:

    1. 当然还需要注意打开文件后,无论是否对文件做如何的操作,一定要把文件关闭.如果有异常可以在文件指针不为空的时候,放在finally语句内。
    2. 打开文件可以有七种模式:
      ‘r’ open for reading (default)
      ‘w’ open for writing, truncating the file first
      ‘x’ open for exclusive creation, failing if the file already exists
      ‘a’ open for writing, appending to the end of the file if it exists
      ‘b’ binary mode
      ‘t’ text mode (default)
      ‘+’ open a disk file for updating (reading and writing)

    通过以上的知识补充可以知晓我们接下来要做的操作。

    f = open('log_back.txt','a')
    f.write(log_str)
    f.close()
    

结果展示

将脚本进行整合并封装,然后在命令行输出,可以得出以下结果.

|------------------------------------------------------------------------------|
|       Time        | CPU 4 core |Memory 15.80 G| Disk 255G |     net_io       |
|------------------------------------------------------------------------------|
|2022-07-04 15:19:49|    5.9%    |   33.2%      |   81.8%   | 11661002\2622110 |
|------------------------------------------------------------------------------|
|------------------------------------------------------------------------------|

|------------------------------------------------------------------------------|
|       Time        | CPU 4 core  |Memory 15.80 G| Disk 255G |     net_io      |
|------------------------------------------------------------------------------|
|2022-07-04 15:19:54|    10.7%    |   33.1%      |   81.8%   |11661195\2622277 |
|------------------------------------------------------------------------------|
|------------------------------------------------------------------------------|

最后

愿自己能真正静下心来,专一门喜爱的技术.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值