使用python脚本每天下午6点保存一次华为交换机配置
python脚本:
#!/bin/python
import paramiko
import time
# 定义多个设备的IP地址列表
username = 'user'
hosts = ['192.168.0.2']
password = 'password'
# 创建一个函数,用于连接到主机并执行命令
def execute_commands(host, username, password):
try:
# 创建 SSH 连接
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接主机
ssh.connect(host, username=username, password=password)
# 执行 save 命令
stdin, stdout, stderr = ssh.exec_command('save')
# 等待命令执行完成并发送 'y'
time.sleep(3)
stdin.write('y\n')
stdin.flush()
# 输出命令执行结果
print(f"Output from {host} (save):")
print(stdout.read().decode('utf-8'))
# 关闭 SSH 连接
ssh.close()
except paramiko.AuthenticationException:
print(f"Authentication failed when connecting to {host}")
except paramiko.SSHException as ssh_ex:
print(f"Unable to establish SSH connection to {host}: {ssh_ex}")
except Exception as ex:
print(f"Error: {ex}")
# 主函数
def main():
for host in hosts:
execute_commands(host, username, password)
if __name__ == "__main__":
main()
配置定时任务,下午六点执行脚本
crontab -e
0 18 * * * "python3 /root/huawei.py"