百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

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

wptr33 2025-07-03 20:22 5 浏览

系统环境:支持 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例(收藏级)》!

相关推荐

「网络安全」JAVA代码审计——XXE外部实体注入

一、WEB安全部分想要了解XXE,在那之前需要了解XML的相关基础二、XML基础...

Web前端面试题目及答案汇总(web前端面试题最新)

Web前端面试题目及答案汇总来源:极客头条以下是收集一些面试中经常会遇到的经典面试题以及自己面试过程中无法解决的问题,通过对知识的整理以及经验的总结,重新巩固自身的前端基础知识,如有错误或更好的答案,...

什么是脚本文件?与可执行文件有什么不同?

今天的内容是脚本文件和可执行文件是两种不同类型的计算机文件,它们在结构和执行方式上有显著区别。脚本文件:定义与特性...

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

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

2026年前每个开发者都应该学习的技能

优秀开发者...

Linux 如何每 5、10、15 或 30 分钟运行一次 Cron 作业?

在Linux系统中,Cron是一个强大的工具,用于自动化重复性任务。通过合理配置...

Shell脚本编程进阶实战:从入门到高效自动化

Shell脚本编程进阶实战:从入门到高效自动化一、参数处理进阶:打造专业级CLI工具1.高级参数解析示例...

在Bash中按分隔符拆分字符串的方法

技术背景在Bash脚本编程中,经常会遇到需要按特定分隔符拆分字符串的需求,例如处理CSV文件、解析日志等。掌握字符串拆分的方法对于数据处理和脚本自动化非常重要。...

程序员用5分钟,把一个400多MB的苹果安装包削掉了187MB

丰色发自凹非寺量子位|公众号QbitAI前些日子,一个...

如何在 Windows 上编写批处理脚本

你知道如何使用命令提示符吗?如果这样做,您可以编写一个批处理文件。在最简单的形式中,批处理文件(或批处理脚本)是双击文件时执行的几个命令的列表。批处理文件一直回到DOS,但仍然适用于现代版本的Win...

一文搞懂shell脚本(shell脚本应用实战)

一文搞懂shell脚本1、shell脚本介绍什么是shell脚本...

一文讲清ShellScript脚本编程知识

摘要:本文详尽地讲述了ShellScript的基础内容,还有它在Linux系统里的运用情况,涵盖了它的基本语法、常用的命令以及高级的功能。ShellScript可是一种简单又非常实用的编...

在Bash脚本中获取自身所在目录的方法

技术背景在使用Bash脚本时,有时需要获取脚本自身所在的目录。比如,当脚本作为另一个应用程序的启动器时,需要将工作目录更改为脚本所在的目录,以便对该目录中的文件进行操作。然而,由于脚本的调用方式多样(...

shell中如何确定脚本的位置?这篇文章告诉你

我想从同一个位置读取一些配置文件,如何确定脚本的位置?。这个问题的出现主要是由两个原因引发的:一是您希望将脚本的数据或配置进行外部化,因此需要一种方式来寻找这些外部资源;二是您的脚本需要对某些捆绑资源...

bash shell 语法(bash命令用法)

下面是**Shell(Bash)语法的常用知识点总结**,适合初学者和日常脚本编写参考。内容涵盖变量、判断、循环、函数、重定向、正则、数组等常见用法。---#Shell(Bash)语法速查总结...