当前位置: 首页 > news >正文

Python 运维脚本

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()

相关文章:

  • seata 1.5.2 升级到2.1.0版本
  • 力扣HOT100之链表:146. LRU 缓存
  • Inference-Time Scaling for Generalist Reward Modeling
  • (四)Java逻辑运算符和位运算符全面解析
  • 通配符 DNS 记录:应用场景与相关风险
  • SEO关键词与长尾词精准布局策略
  • 【Bootstrap V4系列】学习入门教程之 组件-折叠(Collapse)
  • mysql修改root密码
  • C++20新特新——02特性的补充
  • 性能比拼: Redis Streams vs Pub/Sub
  • 解决使用lettuce连接Redis超时的问题(tcpUserTimeout 参数失效问题)
  • YOLOv1:开创实时目标检测新纪元
  • Wireshark抓账号密码
  • 普通笔记本与军用加固笔记本电脑的区别,探索防水、防爆、防摔的真·移动工作站!
  • 在线PDF阅读方案:jQuery + PDF.js
  • 内网和外网怎么互通?外网访问内网的几种简单方式
  • 解决HomeAssistant 无法安装 samba share问题
  • 【数据库原理及安全实验】实验六 角色访问控制
  • 《C++ Templates》:有关const、引用、指针的一些函数模板实参推导的例子
  • C#——NET Core 中实现汉字转拼音
  • 一生要出片的年轻人,买爆相机
  • 云南省安委会办公室:大理州安全生产形势比较严峻,事故总量一直居高不下
  • 4月证券私募产品备案量创23个月新高,股票策略占比超六成
  • 时隔14个月北京怀柔区重启供地,北京建工以3.59亿元摘得
  • 无人机穿越大理千年古塔落券洞内,涉事“飞手”被行拘10日
  • 宁合两大都市圈交汇之城含山:要想身体好,常往含山跑