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 root@192.168.5.45
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()

運行效果

 


免責聲明!

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



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