Python 运维脚本

发布于:2025-05-07 ⋅ 阅读:(13) ⋅ 点赞:(0)

1、备份文件

import os
import shutil

# 定义配置文件目录和备份目录的路径
config_dir = "/root/python/to/config/files/"
backup_dir = "/root/python/to/backup/"

# 遍历配置文件目录中的所有文件
for filename in os.listdir(config_dir):
    # 如果文件名以 ".conf" 结尾,则执行备份操作
    if filename.endswith('.conf'):
        # 构建完整的文件路径
        file_path = os.path.join(config_dir, filename)
        # 构建备份文件路径
        backup_path = os.path.join(backup_dir, filename)
        # 将文件复制到备份目录
        shutil.copy(file_path, backup_path)
        # 打印备份完成的消息
        print(f"Backup of {filename} completed")

2、安装pip

  • 根据不同的版本,安装不同的pip
wget https://bootstrap.pypa.io/pip/3.6/get-pip.py
python3 get-pip.py

在这里插入图片描述

3、将备份文件传送到远程主机上进行备份

import os
import shutil
import paramiko

# 定义配置
local_config_dir = "/root/python/to/config/files/"
remote_backup_dir = "/root/python/to/backup/"
remote_host = "192.168.1.101"
remote_username = "root"  # 根据实际情况修改用户名
remote_password = "your_password"  # 根据实际情况修改密码

# 检查本地配置目录是否存在
if not os.path.exists(local_config_dir):
    print(f"Local directory {local_config_dir} does not exist.")
    exit(1)

# 创建一个 SSH 客户端对象
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
    # 连接远程服务器
    print(f"Connecting to {remote_host}...")
    ssh.connect(remote_host, username=remote_username, password=remote_password)

    # 创建一个 SFTP 客户端对象
    sftp = ssh.open_sftp()

    # 检查远程目录是否存在,如果不存在则创建
    print(f"Checking remote directory {remote_backup_dir}...")
    try:
        sftp.stat(remote_backup_dir)
        print(f"Directory {remote_backup_dir} already exists.")
    except IOError:
        print(f"Directory {remote_backup_dir} does not exist. Creating...")
        sftp.mkdir(remote_backup_dir)

    # 遍历本地目录中的所有文件
    for filename in os.listdir(local_config_dir):
        file_path = os.path.join(local_config_dir, filename)
        backup_path = os.path.join(remote_backup_dir, filename)

        # 检查是否为文件(忽略目录)
        if os.path.isfile(file_path):
            print(f"Transferring {file_path} to {backup_path}...")
            sftp.put(file_path, backup_path)
            print(f"Transfer of {filename} completed.")

finally:
    # 关闭 SFTP 和 SSH 连接
    print("Closing SSH connection...")
    ssh.close()