1. 程式人生 > 實用技巧 >python使用paramiko實現ssh連線跳板機

python使用paramiko實現ssh連線跳板機

由於幹java的,公司要求使用python實現跳板機連線,就上網找資料,最後終於實現了

import paramiko
import sys

hostname = ""  # 業務主機ip
username = ""
password = ""

blip = ""  # 堡壘機ip
bluser = ""
blpasswd = ""

port = 22
login = 'login: '  # telnet 登陸輸入使用者名稱
passinfo = 'Password: '  # 登陸輸入密碼時的字首
paramiko.util.log_to_file('syslogin.log')   #
將資訊放到日誌中 ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=blip, username=bluser, password=blpasswd) # 堡壘機連線 # new session channel = ssh.invoke_shell() channel.settimeout(20) buff = '' resp = '' channel.sendall('telnet ' + hostname + '\n') #
傳送ssh [email protected] while not buff.endswith(login): # 是否以字串 'login' 結尾 try: resp = channel.recv(9999) except Exception as e: print('Error info:%s 連線超時.' % (str(e))) channel.close() ssh.close() sys.exit() buff += resp.decode() channel.send('root
' + '\n') # 傳送使用者名稱 buff = '' while not buff.endswith(passinfo): # 是否以字串 'password 結尾 try: resp = channel.recv(9999) # except Exception as e: print('Error info:%s 連線超時.' % (str(e))) channel.close() ssh.close() sys.exit() buff += resp.decode() # 獲取的resp是bytes型別,測試的時候一直報錯,最後才發現這個原因 if not buff.find('yes/no') == -1: # 模擬登陸是輸入yes channel.sendall('yes\n') buff = '' channel.send('123456' + '\n') # 傳送密碼 buff = '' while not buff.endswith('# '): resp = channel.recv(9999) if not resp.decode().find(passinfo) == -1: print('Error info: 認證失敗.') channel.close() ssh.close() sys.exit() buff += resp.decode() # 通過迴圈實現連續輸入 while True: ml = input('請輸入命令:') channel.sendall(ml + '\n') # 傳送測試命令 buff = '' try: while buff.find('# ') == -1: resp = channel.recv(9999) buff += resp.decode() except Exception as e: print("錯誤:" + str(e)) print(buff) channel.close() ssh.close()

執行效果