网站首页 > 技术文章 正文
系统环境:支持 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例(收藏级)》!
猜你喜欢
- 2025-06-23 python3实现线程和进程的状态转换的模块及应用示例
- 2025-06-23 原来Python的协程有2种实现方式(python协程gevent)
- 2025-06-23 python线程start、run方法本质和区别
- 2025-06-23 Python模块datetime、calendar、logging、argparse、re用法
- 2025-06-23 Python常见模块机os、sys、pickle、json、time用法
- 2025-06-23 python类库configparser(python class库)
- 2025-06-23 python字典常用初始化方式、增加元素及遍历
- 2025-06-23 python运算符重载和上下文管理(python重载加号)
- 2025-06-23 《第32天》运维工程师分享:web服务器如何解析python
- 2025-06-23 Linux面试题Python(linux面试题大全)
- 06-23python3实现线程和进程的状态转换的模块及应用示例
- 06-23原来Python的协程有2种实现方式(python协程gevent)
- 06-23python线程start、run方法本质和区别
- 06-23Python模块datetime、calendar、logging、argparse、re用法
- 06-23Python常见模块机os、sys、pickle、json、time用法
- 06-23python类库configparser(python class库)
- 06-23python字典常用初始化方式、增加元素及遍历
- 06-23python运算符重载和上下文管理(python重载加号)
- 270℃Python短文,Python中的嵌套条件语句(六)
- 268℃python笔记:for循环嵌套。end=""的作用,图形打印
- 266℃PythonNet:实现Python与.Net代码相互调用!
- 262℃Python实现字符串小写转大写并写入文件
- 261℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 121℃原来2025是完美的平方年,一起探索六种平方的算吧
- 101℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 95℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
-
- python3实现线程和进程的状态转换的模块及应用示例
- 原来Python的协程有2种实现方式(python协程gevent)
- python线程start、run方法本质和区别
- Python模块datetime、calendar、logging、argparse、re用法
- Python常见模块机os、sys、pickle、json、time用法
- python类库configparser(python class库)
- python字典常用初始化方式、增加元素及遍历
- python运算符重载和上下文管理(python重载加号)
- 《第32天》运维工程师分享:web服务器如何解析python
- Linux面试题Python(linux面试题大全)
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)