Python日常运维脚本

1    扫描Windows系统CPU、内存、磁盘利用率

1.1    实现代码

#!usr/bin/env python
#-*- coding:utf-8 _*-

"""
@author:T-guoh
@file: server_monitor.py
@time: 2019/03/18
"""

import psutil
import os
import socket

cpu = {'user':0,'system':0,'idle':0,'percent':0}
mem = {'total' : 0, 'avaiable' : 0, 'percent' : 0, 'used' : 0, 'free' : 0}
disk_id = []
disk_total = []
disk_used = []
disk_free = []
disk_percent = []

#获取CPU信息
def get_cpu_info():
    cpu_times = psutil.cpu_times()
    cpu['user'] = cpu_times.user
    cpu['system'] = cpu_times.system
    cpu['idle'] = cpu_times.idle
    cpu['percent'] = psutil.cpu_percent(interval=2)

#获取Memory信息
def get_mem_info():
    mem_info = psutil.virtual_memory()
    mem['total'] = mem_info.total
    mem['avaiable'] = mem_info.available
    mem['percent'] = mem_info.percent
    mem['used'] = mem_info.percent
    mem['free'] = mem_info.free
#获取Disk信息
def get_disk_info():
    for id in psutil.disk_partitions():
        if 'cdrom' in id.opts or id.fstype == '':
            continue
        disk_name = id.device.split(':')
        s = disk_name[0]
        disk_id.append(s)
        disk_info = psutil.disk_usage(id.device)
        disk_total.append(disk_info.total)
        disk_used.append(disk_info.used)
        disk_percent.append(disk_info.percent)
        disk_free.append(disk_info.free)
#定义主函数
def main():
    get_cpu_info()
    cpu_status = cpu['percent']
    get_mem_info()
    mem_status = mem['percent']
    hostname = os.environ['COMPUTERNAME']
    username = os.environ['USERNAME']
    ip_addr = socket.gethostbyname(hostname)
    print('======基本信息======')
    print('主机名:'+ hostname+ '\nIP地址:' + ip_addr + '\n用户名:' + username)
    print('====================')
    print('\n=====资源使用率=====')
    print('CPU使用率:%s %%' % cpu_status)
    print('Mem使用率:%s %%' % mem_status)
    get_disk_info()
    for i in range(len(disk_id)):
        print('%s盘空闲率:%s %%' % (disk_id[i], round(100 - disk_percent[i], 2)))
    print('====================')
    os.system('pause')

if __name__ == '__main__':
    main()

1.2    运行结果

2    扫描Windows系统Top目录与文件大小

2.1    实现代码

#!usr/bin/env python
#-*- coding:utf-8 _*-

"""
@author:T-guoh
@file: server_monitor.py
@time: 2019/03/18
"""

import os

#统计指定目录下各个文件夹的大小,方便观察具体目录的大小
def CountDirSize(srcDir):
    dirSizeDict = {}
    fileSizeDict = {}
    for fileList in os.listdir(srcDir):
        filePath = os.path.join(srcDir,fileList)
        if os.path.isdir(filePath):
            size = 0
            for roots,dirs,files in os.walk(filePath):
                for fileName in files:
                    fileNamePath = os.path.join(roots,fileName)
                    sizetemp = 0
                    try:
                        sizetemp = os.path.getsize(fileNamePath)
                        if sizetemp > 1024*1024:
                            fileSizeDict[fileNamePath] = sizetemp
                    except:
                        sizetemp = 0
                    size += sizetemp
            dirSizeDict[fileList] = size
    #按照从大到小的顺序降序排列
    dirSizeDict = sorted(dirSizeDict.items(),key = lambda dirSizeDict:dirSizeDict[1],reverse = True)
    Sum = 0
    #各个目录占用空间
    print("Each directory takes up space:")
    for ele in dirSizeDict:
        temp = ele[1]/1024/1024
        Sum += temp
        #以单位为M,输出大小
        print(ele[0] + ":" + str(temp) + " M")
    #以单位为G,输出大小
    print("Total use:" + str(Sum / 1024) +" G")
    print("")
    #前20个大文件占用空间
    print("Top 20 large file takes up space:")
    fileSizeDict = sorted(fileSizeDict.items(),key = lambda fileSizeDict:fileSizeDict[1],reverse = True)
    for ele in fileSizeDict[:20]:
        print(ele[0] + ":" +str(ele[1]/1024/1024) + " M")

if __name__ == "__main__":
    srcDir = "c:\\"
    CountDirSize(srcDir)

2.2    运行结果

 

转载于:https://www.cnblogs.com/Wolf-Dreams/p/10693429.html

### 如何用 Python 编写运维脚本 以下是基于需求编写的 Python 运维脚本示例,该脚本用于检测本地主机的 80 端口状态。如果端口未打开,则会尝试重新启动 HTTPD 服务,并通过电子邮件发送通知。 #### 脚本功能描述 此脚本实现的功能如下: 1. 定期检查本地主机的 80 端口是否处于监听状态。 2. 如果端口关闭,则重启 `httpd` 或 `apache2` 服务(具体取决于操作系统和服务名称)。 3. 发送一封邮件通知管理员当前的状态变化。 --- #### 实现代码 ```python import socket import smtplib from email.mime.text import MIMEText import subprocess import time def check_port(host, port): """ 检查指定端口是否开放 """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.settimeout(3) s.connect((host, port)) return True except Exception: return False def restart_httpd(): """ 重启 httpd/apache2 服务 """ try: result = subprocess.run(["sudo", "service", "httpd", "restart"], capture_output=True, text=True) if "failed" in result.stderr or "error" in result.stdout.lower(): raise RuntimeError("Service Restart Failed") except Exception as e: send_email(f"Error restarting service: {e}") def send_email(message): """ 发送邮件通知 """ sender = 'your-email@example.com' receiver = 'admin@example.com' password = 'your-password' msg = MIMEText(message) msg['Subject'] = 'Port Check Alert!' msg['From'] = sender msg['To'] = receiver try: server = smtplib.SMTP('smtp.example.com', 587) server.starttls() server.login(sender, password) server.sendmail(sender, [receiver], msg.as_string()) server.quit() except Exception as e: print(f"Failed to send email: {e}") if __name__ == "__main__": host = '127.0.0.1' # 本地主机 port = 80 # 需要监控的端口号 interval = 30 # 检测间隔时间 (秒) while True: if not check_port(host, port): # 如果端口不可达 message = f"{time.strftime('%Y-%m-%d %H:%M:%S')} - Port {port} is closed! Attempting to restart the service..." print(message) send_email(message) restart_httpd() # 尝试重启服务 else: print(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - Port {port} is open.") time.sleep(interval) # 设置检测间隔 ``` --- #### 功能说明 1. **端口检查逻辑** 使用 `socket` 库创建 TCP 套接字连接到目标主机和端口,验证其连通性[^1]。 2. **服务管理** 利用 `subprocess` 执行系统命令来控制服务的启停操作。这里假设 Linux 平台下的 Apache Web Server 的服务名为 `httpd`[^1]。 3. **邮件通知机制** 结合 SMTP 协议向预设邮箱地址发送告警消息,在异常情况下及时告知维护人员[^2]。 4. **定时任务支持** 主程序运行在一个无限循环中,每次迭代之间暂停固定时间段以减少资源消耗[^3]。 --- #### 注意事项 - 替换模板中的占位符如 `your-email@example.com`, `password` 和 SMTP 地址等内容为实际可用配置项。 - 对于不同平台可能需要调整服务名参数;例如 Ubuntu 上通常称为 `apache2`. - 此外还需赋予适当权限以便能够成功调用特权指令 (`sudo`) 来完成某些动作比如停止/启动服务器进程等行为.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值