python paramiko自动登录网络设备抓取配置信息

1,基本的paramiko(exec_command)
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(host, port=port, username=username, password=password, timeout=timeout)

stdin, stdout, stderr = ssh.exec_command("cd /home; pwd; cd /bridge; pwd")
print(stdout.read().decode('utf-8')) 

  

输出为:
/home
/home
假设linux目录结构是/home/bridge
本来是想进到home目录下pwd一下,再进到/home/bridge目录下pwd一下,却发现其实第二次cd /bridge时失败了,因为exec_command没有交互功能,第二次还是回到了根目录
同理,如果像网络设备这种登陆完还要enable,输入密码的也不行
 
2,判断回显的交互
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 

ssh.connect(hostname='192.168.1.2', port=22, username='cisco', password='cisco')   # 地址是192.168.1.2,用户名/密码都是cisco

client = ssh.invoke_shell()
def run_cmd(cmd, endswith):    # 形参:cmd命令,结束符
    buff = ''
    client.send(cmd)
    while not buff.endswith(endswith):
        resp = str(client.recv(1024), 'utf-8')
        buff += resp
    return buff
res = ''
res += run_cmd('enable\n', 'Password: ')
res += run_cmd('cisco\n', '#')
res += run_cmd('terminal length 0\n', '#')
res += run_cmd('show run\n', '#')
print(res)
ssh.close()

  

  

posted @ 2018-10-22 17:15  GUXH  阅读(4362)  评论(0编辑  收藏  举报