程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

20个实用Python运维脚本(收藏级)(python 运维脚本)

hfteth 2025-06-23 19:16:44 技术文章 1 ℃

系统环境:支持 Linux(Ubuntu / CentOS / Debian)和 Windows

适合人群:系统管理员、DevOps 工程师、Python 初中级用户

文章亮点:涵盖文件处理、系统监控、服务管理、日志分析、网络工具等多个维度,每个脚本都可直接落地使用。





01. 查看系统资源占用情况(跨平台)


import psutil


print(f"CPU 使用率:{psutil.cpu_percent()}%")

print(f"内存使用率:{psutil.virtual_memory().percent}%")

print(f"磁盘使用率:{psutil.disk_usage('/').percent}%")





02. 自动清理

/tmp

目录下7天前的文件(Linux)


import os, time


tmp_dir = "/tmp"

now = time.time()

for f in os.listdir(tmp_dir):

path = os.path.join(tmp_dir, f)

if os.path.isfile(path) and os.stat(path).st_mtime < now - 7 * 86400:

os.remove(path)





03. 检查某个端口是否开放


import socket


def check_port(host, port):

with socket.socket() as s:

result = s.connect_ex((host, port))

return result == 0


print("端口是否开放:", check_port("127.0.0.1", 22))





04. 自动备份指定文件夹


import shutil

from datetime import datetime


src = "/etc"

dst = f"/backup/etc_{datetime.now():%Y%m%d%H%M}.tar.gz"

shutil.make_archive(dst.replace('.tar.gz',''), 'gztar', src)





05. 监控某服务是否在线,若离线则重启


import subprocess


def restart_service(service):

subprocess.run(["systemctl", "restart", service])


def is_active(service):

status = subprocess.getoutput(f"systemctl is-active {service}")

return status.strip() == "active"


svc = "nginx"

if not is_active(svc):

restart_service(svc)





06. 获取公网 IP 地址


import requests


ip = requests.get("https://api.ipify.org").text

print(f"公网IP:{ip}")





07. 查看当前登录的所有用户


import os

print(os.popen("who").read())





08. 自动打包并上传日志到远程


import tarfile

import paramiko


with tarfile.open("logs.tar.gz", "w:gz") as tar:

tar.add("/var/log", arcname="log")


ssh = paramiko.Transport(("remote_host", 22))

ssh.connect(username="user", password="pass")

sftp = paramiko.SFTPClient.from_transport(ssh)

sftp.put("logs.tar.gz", "/remote/path/logs.tar.gz")

sftp.close()

ssh.close()





09. 分析日志文件中最常出现的错误


from collections import Counter


with open("/var/log/syslog") as f:

errors = [line for line in f if "error" in line.lower()]

keywords = [line.split()[0] for line in errors]

print(Counter(keywords).most_common(10))





10. 快速搭建一个本地Web服务(静态目录)


import http.server

import socketserver


PORT = 8000

handler = http.server.SimpleHTTPRequestHandler

httpd = socketserver.TCPServer(("", PORT), handler)

print(f"Serving at port {PORT}")

httpd.serve_forever()





11. 检查磁盘分区情况


import shutil


total, used, free = shutil.disk_usage("/")

print("总空间:", total // (2**30), "GB")

print("已用:", used // (2**30), "GB")

print("可用:", free // (2**30), "GB")





12. 获取指定用户的 UID 与 GID


import pwd


user = "root"

u = pwd.getpwnam(user)

print(f"{user} 的 UID: {u.pw_uid}, GID: {u.pw_gid}")





13. 定时执行脚本(配合 crontab)


# 编辑 crontab

# crontab -e


# 每天 2 点执行
/usr/local/bin/check_nginx.py

# 0 2 * * * /usr/bin/python3 /usr/local/bin/check_nginx.py





14. 发送告警通知到邮箱


import smtplib

from email.message import EmailMessage


msg = EmailMessage()

msg.set_content("服务异常,请检查!")

msg["Subject"] = "运维告警"

msg["From"] = "admin@example.com"

msg["To"] = "user@example.com"


with smtplib.SMTP("smtp.example.com", 25) as server:

server.login("admin", "password")

server.send_message(msg)





15. 检查 SSL 证书过期时间


import ssl, socket

from datetime import datetime


hostname = 'example.com'

context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:

with context.wrap_socket(sock, server_hostname=hostname) as ssock:

cert = ssock.getpeercert()

expire = datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')

print("证书过期时间:", expire)





16. 快速创建多个用户账号(批量)


import os


for i in range(10):

username = f"user{i}"

os.system(f"useradd {username} -m -s /bin/bash")





17. 检查文件MD5值


import hashlib


def get_md5(file_path):

with open(file_path, 'rb') as f:

return hashlib.md5(f.read()).hexdigest()


print(get_md5("/etc/passwd"))





18. 自动拉取 Git 仓库更新


import os


os.chdir("/opt/project")

os.system("git pull origin main")





19. 获取系统启动时间


import psutil

import time


boot = psutil.boot_time()

print("系统启动时间:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(boot)))





20. 查找大文件(>100MB)


import os


for root, dirs, files in os.walk("/"):

for file in files:

path = os.path.join(root, file)

try:

if os.path.getsize(path) > 100 * 1024 * 1024:

print(path)

except:

continue




如果你觉得这些脚本实用,记得收藏 + 关注我,后续会带来完整的《Python运维脚本100例(收藏级)》!

Tags:

最近发表
标签列表