当前位置: 首页 > 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()
http://www.xdnf.cn/news/327439.html

相关文章:

  • AI系列:智能音箱技术简析
  • void*在c语言中什么意思(非常详细)
  • scanpy处理:使用自定义 python 函数读取百迈客空间转录组数据(百创智造S1000)
  • 深度学习:智能车牌识别系统(python)
  • htop筛选进程时,出现重复进程
  • 德州仪器技术干货 | 48V 集成式热插拔电子保险丝:为现代 AI 数据中心高效供电
  • Python案例实战《水果识别模型训练及调用》
  • Linux 内核学习(7) --- 字符设备驱动
  • eFish-SBC-RK3576工控板CAN接口测试操作指南
  • leetcode 3341. 到达最后一个房间的最少时间 I 中等
  • Unity_JK框架【3】 事件系统的简单使用示例
  • 169.多数元素
  • openstack虚拟机状态异常处理
  • java集合菜鸟教程
  • 从 CodeBuddy Craft 到 edgeone-pages-mcp 上线算命网站的一次完整体验分享
  • 多语言网站的 UX 陷阱与国际化实践陷阱清单
  • 前端面试每日三题 - Day 27
  • 【Python】os模块
  • 使用 Gradio + Qwen3 + vLLM 部署 Text2SQL 多表查询系统
  • 【Prometheus】深入解析 Prometheus 特殊标签 `__param_<name>`:动态抓取参数的艺术
  • Android 数据持久化之数据库存储 Room 框架
  • 50个精选DeepSeek指令
  • ifconfig statistics
  • springboot使用阿里云OSS实现文件上传
  • 云上玩转Qwen3系列之二:PAI-LangStudio搭建联网搜索和RAG增强问答应用
  • C++初阶 —— 类和对象
  • C++ 中的 `it->second` 和 `it.second`:迭代器与对象访问的微妙区别
  • 如何延长电脑使用寿命?
  • Cadence 高速系统设计流程及工具使用二
  • 学习黑客 Linux用户管理