import paramiko
import datetime
import time
f=open('./hostnames.txt','r') #准备主机文件,一台主机占一行
hostnames=f.readlines()
for hostname in hostnames:
hostname=hostname.strip()
ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=hostname,username='python',password='123456') #连接并登录网络设备,此处用户名密码根据自己情况
print('Sucessfully conneted to ',hostname)
cmd=ssh_client.invoke_shell()
cmd.send('dis curr | include sysname\n') #查看网络设备主机名
time.sleep(2)
result=cmd.recv(66666) #设置接收字节的窗口大小
result=result.decode('utf-8')
items=result.splitlines()
for item in items:
item=item.strip()
if item.startswith('sysname'): #提取网络设备主机名
device_name=item.split(' ')[-1]
#print(device_name)
now_time=datetime.datetime.now()
now_time=now_time.strftime('%Y-%m-%d-%H:%M:%S') #获取当前时间
file_name=device_name+'-'+now_time+'-vrpcfg.zip' #拼接备份文件名(网络设备主机名+时间+后缀名)
cmd.send('ftp 192.168.99.211\n')
time.sleep(1)
cmd.send('ftpuser\n')
time.sleep(1)
cmd.send('huawei123456\n')
time.sleep(1)
cmd.send('put vrpcfg.zip '+file_name+'\n') #登录FTP服务器,并将网络设备的文件传送到FTP服务器
time.sleep(3)
print('files have uploaded to ftp server,And the connetion will be closed')
result2=cmd.recv(66666)
result2.decode('utf-8')
print(result2,'\n')
time.sleep(2)
ssh_client.close()
标签:hostname,Python,备份,cmd,send,sleep,time,网络设备
From: https://www.cnblogs.com/tang-learning/p/16846413.html