paramiko交互测试提示
>>> import paramiko
>>> import time
>>> ssh = paramiko.SSHClient() # 创建SSH Client
>>> ssh.load_system_host_keys() # 加载系统SSH密钥
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 添加新的SSH密钥
>>> ssh.connect('192.168.80.110',username='admin',password='admin123',timeout=5) # SSH连接
>>> shell = ssh.invoke_shell() # 激活交互式shell
>>> time.sleep(1) # 等待网络设备回应
>>> shell.recv(1024).decode() # 获取路由器返回的信息
>>> shell.send('dis ip int br' + '\n') # 发送命令
>>> time.sleep(1)
>>> result = shell.recv(1024).decode() # 获取路由器返回的信息
>>> print(result) # 打印返回信息
import paramiko
import time
def ssh(ip, username, passwd, port=22,cmd='dis ip int br'):
ssh1 = paramiko.SSHClient()
ssh1.load_system_host_keys()
ssh1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh1.connect(ip, port, username=username, password=passwd, timeout=2, compress=True)
except Exception:
print('无法连接到设备')
else:
shell = ssh1.invoke_shell()
shell.send(cmd + '\n')
time.sleep(1)
z = shell.recv(1024).decode()
return z
ssh1.close()
if __name__ == '__main__':
print(ssh('192.168.80.100', 'user1', '123456',))