1. 系统监控
1.1 CPU 使用率监控
import psutil
import time
def monitor_cpu_usage(interval=1):
while True:
cpu_percent = psutil.cpu_percent(interval=interval)
print(f"CPU Usage: {cpu_percent}%")
time.sleep(interval)
if __name__ == "__main__":
monitor_cpu_usage(interval=5)
1.2 内存使用率监控
import psutil
import time
def monitor_memory_usage(interval=1):
while True:
mem_info = psutil.virtual_memory()
print(f"Total Memory: {mem_info.total / (1024 ** 3):.2f} GB")
print(f"Available Memory: {mem_info.available / (1024 ** 3):.2f} GB")
print(f"Memory Usage: {mem_info.percent}%")
time.sleep(interval)
if __name__ == "__main__":
monitor_memory_usage(interval=5)
2. 日志分析
2.1 日志文件解析
import re
def parse_log_file(log_file):
pattern = r'\[(?P\d{2}/\w{3}/\d{4}:\d{2}:\d{2}:\d{2})\] \[(?P\w+)\] (?P.*)'
with open(log_file, 'r') as file:
for line in file:
match = re.match(pattern, line)
if match:
timestamp = match.group('timestamp')
level = match.group('level')
message = match.group('message')
print(f"Timestamp: {timestamp}, Level: {level}, Message: {message}")
if __name__ == "__main__":
log_file = "/var/log/syslog"
parse_log_file(log_file)
3. 文件备份
3.1 定时备份文件
import os
import shutil
import time
def backup_file(source_file, backup_dir, interval=3600):
while True:
timestamp = time.strftime("%Y%m%d_%H%M%S")
backup_file = os.path.join(backup_dir, f"{timestamp}_{os.path.basename(source_file)}")
shutil.copy2(source_file, backup_file)
print(f"Backup created: {backup_file}")
time.sleep(interval)
if __name__ == "__main__":
source_file = "/path/to/source/file"
backup_dir = "/path/to/backup/directory"
backup_file(source_file, backup_dir, interval=3600)
4. 系统更新
4.1 自动化系统更新
import subprocess
def update_system():
print("Updating system...")
subprocess.run(['sudo', 'apt-get', 'update'])
subprocess.run(['sudo', 'apt-get', 'upgrade', '-y'])
print("System updated successfully.")
if __name__ == "__main__":
update_system()
5. 网络监控
5.1 网络流量监控
import psutil
import time
def monitor_network_traffic(interval=1):
while True:
net_info = psutil.net_io_counters()
bytes_sent = net_info.bytes_sent
bytes_recv = net_info.bytes_recv
print(f"Bytes Sent: {bytes_sent}, Bytes Received: {bytes_recv}")
time.sleep(interval)
if __name__ == "__main__":
monitor_network_traffic(interval=5)
6. 系统服务管理
6.1 启动和停止服务
import subprocess
def manage_service(service_name, action):
if action == "start":
subprocess.run(['sudo', 'systemctl', 'start', service_name])
print(f"Service '{service_name}' started.")
elif action == "stop":
subprocess.run(['sudo', 'systemctl', 'stop', service_name])
print(f"Service '{service_name}' stopped.")
else:
print("Invalid action. Use 'start' or 'stop'.")
if __name__ == "__main__":
service_name = "nginx"
manage_service(service_name, "start")
manage_service(service_name, "stop")
7. 系统重启
7.1 自动重启系统
import subprocess
def reboot_system():
print("Rebooting system...")
subprocess.run(['sudo', 'reboot'])
if __name__ == "__main__":
reboot_system()
8. 用户管理
8.1 添加和删除用户
import subprocess
def manage_user(username, action):
if action == "add":
subprocess.run(['sudo', 'useradd', username])
print(f"User '{username}' added.")
elif action == "remove":
subprocess.run(['sudo', 'userdel', '-r', username])
print(f"User '{username}' removed.")
else:
print("Invalid action. Use 'add' or 'remove'.")
if __name__ == "__main__":
username = "newuser"
manage_user(username, "add")
manage_user(username, "remove")
9. 系统日志管理
9.1 清理日志文件
import os
def clean_logs(directory):
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".log"):
file_path = os.path.join(root, file)
with open(file_path, 'w') as f:
f.truncate(0)
print(f"Log file '{file_path}' cleared.")
if __name__ == "__main__":
log_directory = "/var/log"
clean_logs(log_directory)
10. 系统资源监控
10.1 综合监控脚本
import psutil
import time
def monitor_system(interval=1):
while True:
cpu_percent = psutil.cpu_percent(interval=interval)
mem_info = psutil.virtual_memory()
net_info = psutil.net_io_counters()
print(f"CPU Usage: {cpu_percent}%")
print(f"Total Memory: {mem_info.total / (1024 ** 3):.2f} GB")
print(f"Available Memory: {mem_info.available / (1024 ** 3):.2f} GB")
print(f"Memory Usage: {mem_info.percent}%")
print(f"Bytes Sent: {net_info.bytes_sent}, Bytes Received: {net_info.bytes_recv}")
time.sleep(interval)
if __name__ == "__main__":
monitor_system(interval=5)
11. 文件权限管理
11.1 修改文件权限
import os
def change_file_permissions(file_path, mode):
os.chmod(file_path, mode)
print(f"Permissions of '{file_path}' changed to {mode:o}")
if __name__ == "__main__":
file_path = "/path/to/file"
mode = 0o755
change_file_permissions(file_path, mode)
12. 系统信息收集
import platform
import psutil
def collect_system_info():
print(f"System: {platform.system()}")
print(f"Release: {platform.release()}")
print(f"Version: {platform.version()}")
print(f"Machine: {platform.machine()}")
print(f"CPU Usage: {psutil.cpu_percent(interval=1)}%")
print(f"Total Memory: {psutil.virtual_memory().total / (1024 ** 3):.2f} GB")
print(f"Available Memory: {psutil.virtual_memory().available / (1024 ** 3):.2f} GB")
print(f"Memory Usage: {psutil.virtual_memory().percent}%")
if __name__ == "__main__":
collect_system_info()
总结
通过以上介绍,我们详细讲解了 Python 运维工程师常用的脚本,包括系统监控、日志分析、文件备份、系统更新、网络监控、系统服务管理、系统重启、用户管理、系统日志管理、系统资源监控、文件权限管理和系统信息收集等方面。这些脚本可以帮助运维工程师更高效地管理和维护系统。
python入门虽然简单,很多新手依然卡在基础安装阶段,大部分教程对一些基础内容都是一带而过,好多新手朋友,对一些基础知识常常一知半解,需要在网上查询很久。
扎实的基础知识,对之后的学习、工作都是非常必要的。从这400集的Python视频教程中由易到难,平常所有的疑难点都可以从中找到答案(比培训机构讲的都详细)。另外还配套Python中文手册这最基础的编程环境搭建就做了200多页的详细讲解!其他基础语法、函数、模块和包均一一精细解答。新手必备!
还分享Python 50G大礼包,里面还有Python面试真题,里面干货满满,一次全拿走!
01,Python大礼包
02,Python电子书
03,Python面试集锦
04
Python小白必备手册
05,Python安装包
06,数据分析全套资源
这只是冰山一角,想要完整版的小伙伴下图获取~