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('sys\n')
cmd.send('acl number 3000\n')
cmd.send(f'rule 10 permit ip source 192.168.99.0 0.0.0.255 destination {hostname} 0\n')
cmd.send('rule 20 deny ip\n') #通过ACL规则只允许源地址为192.168.99.0网段的主机连接
cmd.send('user-interface vty 0 4\n')
cmd.send('acl 3000 inbound\n')
cmd.send('rsa local-key-pair create\n')
cmd.send('y\n')
cmd.send('2048\n')
result=cmd.recv(66666)
result=result.decode('ascii')
print(result)
print('The operation has finished!!!')
time.sleep(2)
ssh_client.close()