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