簡體   English   中英

與Paramiko嵌套的SSH會話

[英]Nested SSH session with Paramiko

我正在重寫我寫到Python中的Bash腳本。 該腳本的關鍵是

ssh -t first.com "ssh second.com very_remote_command"

我在使用paramiko進行嵌套身份驗證時遇到問題。 我找不到適合我具體情況的任何示例,但是我能夠在遠程主機上找到帶有sudo的示例。

第一種方法寫入標准輸入

ssh.connect('127.0.0.1', username='jesse', password='lol')
stdin, stdout, stderr = ssh.exec_command("sudo dmesg")
stdin.write('lol\n')
stdin.flush()

第二個創建通道並使用類似於套接字的sendrecv

我能夠使stdin.writesudo一起使用 ,但在遠程主機上的ssh上卻不起作用。

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('first.com', username='luser', password='secret')
stdin, stdout, stderr = ssh.exec_command('ssh luser@second.com')
stdin.write('secret')
stdin.flush()
print '---- out ----'
print stdout.readlines()
print '---- error ----'
print stderr.readlines()

ssh.close()

...印刷品...

---- out ----
[]
---- error ----
['Pseudo-terminal will not be allocated because stdin is not a terminal.\r\n', 'Permission denied, please try again.\r\n', 'Permission denied, please try again.\r\n', 'Permission denied (publickey,password,keyboard-interactive).\r\n']

偽終端錯誤使我想起了原始命令中的-t標志,因此我使用Channel切換到第二種方法。 我沒有ssh.exec_command和更高版本,而是:

t = ssh.get_transport()
chan = t.open_session()
chan.get_pty()
print '---- send ssh cmd ----'
print chan.send('ssh luser@second.com')
print '---- recv ----'
print chan.recv(9999)
chan = t.open_session()
print '---- send password ----'
print chan.send('secret')
print '---- recv ----'
print chan.recv(9999)

...但是它會打印'---- send ssh cmd ----'並掛起,直到我終止該進程。

我是Python的新手,對網絡的了解也不多。 在第一種情況下,為什么發送密碼只能用於sudo但不能用於ssh 提示是否不同? paramiko甚至是正確的庫嗎?

我設法找到一個解決方案,但是需要一些手動工作。 如果有人有更好的解決方案,請告訴我。

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('first.com', username='luser', password='secret')

chan = ssh.invoke_shell()

# Ssh and wait for the password prompt.
chan.send('ssh second.com\n')
buff = ''
while not buff.endswith('\'s password: '):
    resp = chan.recv(9999)
    buff += resp

# Send the password and wait for a prompt.
chan.send('secret\n')
buff = ''
while not buff.endswith('some-prompt$ '):
    resp = chan.recv(9999)
    buff += resp

# Execute whatever command and wait for a prompt again.
chan.send('ls\n')
buff = ''
while not buff.endswith('some-prompt$ '):
    resp = chan.recv(9999)
    buff += resp

# Now buff has the data I need.
print 'buff', buff

ssh.close()

需要注意的是

t = ssh.get_transport()
chan = t.open_session()
chan.get_pty()

...你要這個

chan = ssh.invoke_shell()

這讓我想起了我小時候放棄編寫代碼十年的嘗試編寫TradeWars腳本的過程。 :)

這是一個僅使用paramiko(和端口轉發)的小示例:

import paramiko as ssh

class SSHTool():
    def __init__(self, host, user, auth,
                 via=None, via_user=None, via_auth=None):
        if via:
            t0 = ssh.Transport(via)
            t0.start_client()
            t0.auth_password(via_user, via_auth)
            # setup forwarding from 127.0.0.1:<free_random_port> to |host|
            channel = t0.open_channel('direct-tcpip', host, ('127.0.0.1', 0))
            self.transport = ssh.Transport(channel)
        else:
            self.transport = ssh.Transport(host)
        self.transport.start_client()
        self.transport.auth_password(user, auth)

    def run(self, cmd):
        ch = self.transport.open_session()
        ch.set_combine_stderr(True)
        ch.exec_command(cmd)
        retcode = ch.recv_exit_status()
        buf = ''
        while ch.recv_ready():
            buf += ch.recv(1024)
        return (buf, retcode)

# The example below is equivalent to
# $ ssh 10.10.10.10 ssh 192.168.1.1 uname -a
# The code above works as if these 2 commands were executed:
# $ ssh -L <free_random_port>:192.168.1.1:22 10.10.10.10
# $ ssh 127.0.0.1:<free_random_port> uname -a
host = ('192.168.1.1', 22)
via_host = ('10.10.10.10', 22)

ssht = SSHTool(host, 'user1', 'pass1',
    via=via_host, via_user='user2', via_auth='pass2')

print ssht.run('uname -a')

您可以使用來自另一個ssh連接的通道來創建ssh連接。 有關更多詳細信息,請參見此處

要獲得現成的解決方案,請從pxpect項目中檢查pxssh。 查看sshls.py和ssh_tunnel.py示例。

http://www.noah.org/wiki/Pexpect

Sinas的答案效果很好,但是沒有為我提供很長命令的所有輸出。 但是,使用chan.makefile()可以檢索所有輸出。

以下內容適用於需要tty的系統,並提示輸入sudo密碼

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.WarningPolicy())
ssh.connect("10.10.10.1", 22, "user", "password")
chan=ssh.get_transport().open_session()
chan.get_pty()
f = chan.makefile()
chan.exec_command("sudo dmesg")
chan.send("password\n")
print f.read()
ssh.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM