Python实现运维案例

案例分析

概述 

          Python是一种跨平台编程语言,在多种平台都能得到很好的支持,在各种平台环境的运维过程中,有些工作是很繁琐重复的工作,可以编写脚本作为工具辅助运维工作,比如linux中使用shell脚本,但是shell脚本编写、调试比较困难,支持的辅助库少,编写稍微复杂些的功能就比较耗时、容易出错了。本文通过Python实现代码,作为学习和技术交流。

Python基础环境准备

参见:https://blog.youkuaiyun.com/yan_dk/article/details/89528463

案例实现

文件目录按关键词备份迁移

说明:工程目录中的附件有很多文件,积累了多年,导致整个应用目录非常庞大,历年记录基本上是不会读取的,只保留当年或当月的记录,这样太大不方便应用迁移,本例实现将附件文件的历史目录迁移备份到目标备份目录。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import  os
import shutil
#
# 处理文件及目录
# @a_srcPath 目录路径
# # copyOrMove 复制操作还是移动操作 False为复制操作,True为移动操作

allfile = []
def handle_dir(a_srcPath, a_findKey, a_copyOrMove=False):
    srcPathList = os.listdir(a_srcPath)
    #print(str(srcPathList))
    for sPath in srcPathList:
        filepath = os.path.join(a_srcPath, sPath)
        # print("filepath="+filepath)
        # 判断是目录
        if os.path.isdir(filepath):
          handle_dir(filepath, a_findKey, a_copyOrMove)
          if filepath.find(a_findKey)>=0:
             len_asrcPath = len(srcPath_root)
             destPath= destPath_root+filepath[len_asrcPath:]
             # destPath = filepath
             #print("destPath="+destPath)
             #print("filepath=" + filepath)
             allfile.append(destPath)
             if a_copyOrMove:  
                 shutil.move(filepath, destPath)    #移动目录
             else:
                 shutil.copytree(filepath, destPath) #复制目录

    return allfile

findKey='2018-'
srcPath_root='/home/mysoft/attachments'
destPath_root='/home/mysoft/bk/attachments_history/'+findKey

allfiles=handle_dir(srcPath_root,findKey,False)

for item in allfiles:
   print(item)

这样,就实现了复制、或者移动目录来迁移备份历史文件夹,而且按照指定关键词来建立文件夹,目录能得到比较完整的备份迁移,非常安全、方便。

 

持续完善,待续...

### Python运维脚本示例 以下是几个常见的Python运维脚本案例,涵盖了端口监控、多线程任务以及文件分块处理等功能。 #### 1. 检测80端口状态并自动恢复HTTPD服务 此脚本用于检测本地机器上的80端口是否处于打开状态。如果未开启,则会尝试重新启动`httpd`服务,并发送一封电子邮件通知管理员[^2]。 ```python import socket import subprocess import smtplib from email.mime.text import MIMEText def check_port(host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((host, port)) sock.close() return True if result == 0 else False def restart_httpd(): try: subprocess.run(["sudo", "systemctl", "restart", "httpd"], check=True) print("Httpd service restarted successfully.") except Exception as e: print(f"Failed to restart httpd: {e}") def send_email(subject, body, recipient): msg = MIMEText(body) msg['Subject'] = subject msg['From'] = 'admin@example.com' msg['To'] = recipient with smtplib.SMTP('smtp.example.com', 587) as server: server.starttls() server.login('username', 'password') server.sendmail(msg['From'], [msg['To']], msg.as_string()) if __name__ == "__main__": host = '127.0.0.1' port = 80 if not check_port(host, port): restart_httpd() send_email("Port 80 Down Alert", "The HTTP service was down and has been restarted.", "admin@example.com") ``` --- #### 2. 多线程并发执行任务 通过`threading`模块实现多线程操作,提升脚本运行效率。以下是一个简单例子,展示如何同时运行多个独立的任务[^3]。 ```python import threading import time def task(name, duration): print(f"{name} starting...") time.sleep(duration) print(f"{name} completed after {duration}s.") threads = [] for i in range(5): t = threading.Thread(target=task, args=(f"Task-{i}", (i + 1))) threads.append(t) for t in threads: t.start() for t in threads: t.join() print("All tasks have finished.") ``` --- #### 3. 文件分块读取与处理 当需要高效地处理大文件时,可以将其分割成若干个小块分别处理。这种方法特别适用于日志分析或批量数据转换场景[^5]。 ```python def split_file_into_blocks(file_path, block_size=1024 * 1024): # 默认每块大小为1MB blocks = [] with open(file_path, 'r') as file: while True: chunk = file.read(block_size) if not chunk: break blocks.append(chunk) return blocks file_path = "/path/to/large/file.txt" blocks = split_file_into_blocks(file_path) for idx, block in enumerate(blocks): print(f"Processing Block #{idx}") # 对每个block进行具体的操作... ``` --- #### 4. 自动化定时任务调度 利用`schedule`库设置周期性任务,比如每隔一段时间清理临时目录或者备份数据库[^4]。 安装依赖: ```bash pip install schedule ``` 代码如下: ```python import os import shutil import schedule import time def clean_temp_directory(temp_dir="/tmp"): for root, dirs, files in os.walk(temp_dir): for name in files: path = os.path.join(root, name) try: os.remove(path) print(f"Deleted {path}.") except Exception as e: print(f"Error deleting {path}: {str(e)}") def backup_database(db_name="mydb.sql", dest_folder="/backups"): timestamp = time.strftime("%Y%m%d-%H%M%S") backup_filename = f"{db_name}.{timestamp}" shutil.copy(db_name, os.path.join(dest_folder, backup_filename)) print(f"Database backed up to {backup_filename}.") # 安排每天凌晨2点执行清洁任务 schedule.every().day.at("02:00").do(clean_temp_directory) # 每小时备份一次数据库 schedule.every().hour.do(backup_database) while True: schedule.run_pending() time.sleep(1) ``` --- ### 总结 上述脚本覆盖了多种实际运维需求,包括但不限于端口监测、多线程优化、大数据量处理以及日常维护工作的自动化安排。这些工具能够显著减少人工干预频率,从而提高工作效率和稳定性。 问题
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云焰

你的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值