check-system-info/bin/get_system_info.py

179 lines
6.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/python3
import _load
import psutil
import smtplib
import os
import argparse
import yaml
from datetime import datetime
from pathlib import Path
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
# 定义公共的部分
path = Path(__file__)
report_dir = path.parent.parent / "report"
# 初始化目录
if not report_dir.exists():
# shutil.rmtree(data_dir)
report_dir.mkdir()
#报告文件
week=str(datetime.now().isocalendar()[1])
file_name = "ComputerInfos-week-" + week + ".txt"
file_path = report_dir/file_name
#发邮件
def send_mail():
#发件人
sender = 'mh@unamail.com'
# 接收邮件,可以发给多人
receivers = ['mh@unamail.com']
# 邮件主体
msg = MIMEMultipart()
#正文
message = "{0}周,{1}运行信息检测已完成,详情请查看附件!".format(week,get_IP())
msg.attach(MIMEText(message, 'plain', _charset="utf-8"))
# 发送者
msg['From'] = Header(sender, 'utf-8')
# 接收者
msg['To'] = Header(receivers[0], 'utf-8')
# 主题
subject = '【长期任务】第{0}{1}系统运行信息'.format(week,get_IP())
msg['Subject'] = Header(subject, 'utf-8')
#附件信息
att = MIMEText(open(str(file_path), 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="{}"'.format(file_name)
msg.attach(att)
try:
smtpObj = smtplib.SMTP('10.10.110.102')
smtpObj.sendmail(sender, receivers, msg.as_string())
print ("邮件发送成功")
except smtplib.SMTPException:
print ("Error: 无法发送邮件")
#写入文件
def save_txt(datas):
with open(str(file_path),'a+',encoding='utf-8',newline='') as file_txt:
[file_txt.write(str(item)+'\n') for item in datas]
# 获取本机磁盘使用率和剩余空间G信息
def get_disk_info():
# 循环磁盘分区
content = []
for disk in psutil.disk_partitions():
# 读写方式 光盘 or 有效磁盘类型
if 'cdrom' in disk.opts or disk.fstype == '':
continue
disk_name_arr = disk.device.split(':')
disk_name = disk_name_arr[0]
disk_info = psutil.disk_usage(disk.device)
# 磁盘剩余空间单位G
free_disk_size = disk_info.free//1024//1024//1024
# 磁盘总空间单位G
total_disk_size = disk_info.total//1024//1024//1024
# 当前磁盘使用率、剩余空间G和磁盘总空间信息
info = " {0}盘使用率:{1}% 剩余空间:{2}G 总大小:{3}G".format(disk_name, str(disk_info.percent),free_disk_size,total_disk_size)
# print(info)
# 拼接多个磁盘的信息
content.append(info)
print(content)
save_txt(content)
# 获取某个目录的大小
dir_content=[]
def get_dir_size(path):
list1 = []
fileList = os.listdir(path) # 获取path目录下所有文件
for filename in fileList:
pathTmp = os.path.join(path,filename) # 获取path与filename组合后的路径
if os.path.isdir(pathTmp): # 判断是否为目录
print("---------------")
dir_content.append(" ---------------")
get_dir_size(pathTmp) # 是目录就继续递归查找
elif os.path.isfile(pathTmp): # 判断是否为文件
filesize = os.path.getsize(pathTmp) # 如果是文件,则获取相应文件的大小
str_tex = ' {0}文件的大小为:{1}字节'.format(pathTmp,filesize)
print(str_tex)
dir_content.append(str_tex)
list1.append(filesize) # 将文件的大小添加到列表
str_dir_tex = ' {0} 目录的大小为: {1:.4f} MB'.format(path, (sum(list1)/1024/1024))
print(str_dir_tex)
dir_content.append(str_dir_tex)
# cpu信息
def get_cpu_info():
cpu_percent = psutil.cpu_percent(interval=1)
cpu_info = ["","CPU使用率{0}%".format(cpu_percent),""]
print(cpu_info)
# return cpu_info
save_txt(cpu_info)
# 内存信息
def get_memory_info():
virtual_memory = psutil.virtual_memory()
used_memory = virtual_memory.used/1024/1024/1024
free_memory = virtual_memory.free/1024/1024/1024
memory_percent = virtual_memory.percent
memory_info = ["内存使用:{0:0.2f}G使用率{1:0.1f}%,剩余内存:{2:0.2f}G".format(used_memory, memory_percent, free_memory),""]
print(memory_info)
# return memory_info
save_txt(memory_info)
def get_IP():
"""获取ipv4地址"""
dic = psutil.net_if_addrs()
ipv4_list = []
for adapter in dic:
snicList = dic[adapter]
for snic in snicList:
# if snic.family.name in {'AF_LINK', 'AF_PACKET'}:
# mac = snic.address
if snic.family.name == 'AF_INET':
ipv4 = snic.address
if ipv4 != '127.0.0.1':
ipv4_list.append(ipv4)
# elif snic.family.name == 'AF_INET6':
# ipv6 = snic.address
print(ipv4_list)
return(ipv4_list[0])
def main():
commoninfo = []
if not file_path.exists():
t1 = "本周是第{0}".format(week)
commoninfo.append(t1)
commoninfo.append("")
commoninfo.append("--------------------START--------------------------")
commoninfo.append("检测时间: {0}".format(datetime.now()))
commoninfo.append("检测IP {0}".format(get_IP()))
save_txt(commoninfo)
save_txt(["","磁盘使用情况:",""])
get_disk_info()
get_cpu_info()
get_memory_info()
path = "D:\\agent\\ubackup\\uagent\\logs"
get_dir_size(path)
save_txt(["{0}目录大小:".format(path)])
save_txt(dir_content)
save_txt(['----------------------END----------------------------'])
if __name__ == '__main__':
main()
#默认不发邮件,通过参数控制
parser = argparse.ArgumentParser(description='send email')
parser.add_argument("--send-mail", type=bool, default=False)
args = parser.parse_args()
if args.send_mail:
send_mail()