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()

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM