简体   繁体   English

Python、paramiko 和转发代理 ssh

[英]Python, paramiko and forward agent ssh

I am learning python.我正在学习蟒蛇。 I am at a step where I must connect with SSH and retrieve information.我正处于必须与 SSH 连接并检索信息的阶段。 Direct connection to server A is OK.直接连接到服务器 A 是可以的。 Direct connection to server B is OK.直接连接到服务器 B 是可以的。 Now I'd like to make it work to connect to SSH to A and via A connect to SSH to B (because outside of my lab, there are security features that make me do that).现在我想让它连接到 SSH 到 A,并通过 A 连接到 SSH 到 B(因为在我的实验室之外,有一些安全功能让我这样做)。

I went far, looked everything on the internet, but Paramiko and SSH agent don't seem to work for me.我走了很远,在互联网上查看了所有内容,但 Paramiko 和 SSH 代理似乎对我不起作用。 I use public key authentication on my linux servers (all linux servers btw).我在我的 linux 服务器(顺便说一句,所有 linux 服务器)上使用公钥身份验证。

I enabled detailed logs, and Here is the full error message anonymized:我启用了详细的日志,这是匿名的完整错误消息:

INFO:paramiko.transport:Authentication (publickey) successful!
DEBUG:paramiko.transport:[chan 0] Max packet in: 32768 bytes
DEBUG:paramiko.transport:[chan 0] Max packet out: 32768 bytes
DEBUG:paramiko.transport:Secsh channel 0 opened.
DEBUG:paramiko.transport:[chan 1] Max packet in: 32768 bytes
DEBUG:paramiko.transport:[chan 1] Max packet out: 32768 bytes
DEBUG:paramiko.transport:Secsh channel 1 opened.
DEBUG:paramiko.transport:[chan 1] Sesch channel 1 request ok
DEBUG:paramiko.transport:[chan 1] Sesch channel 1 request ok
('[SEND ] >>', 'hostname')
('[RECEIVE] <<', u'Last login: Wed Jan 9 19:51:01 2019 from myserver')
('[RECEIVE] <<', u'hostname ; echo CLIENT_EXPECT_CMD_OK')
('[RECEIVE] <<', u'/----- Welcome to proxy jump server ----------')
('[RECEIVE] <<', u'| CentOS release 6.6 (Final)')
('[RECEIVE] <<', u'[mylogin@proxy_jump_server ~]$ hostname ; echo 
CLIENT_EXPECT_CMD_OK')
('[RECEIVE] <<', u'proxy_jump_server')
('[SEND ] >>', 'ssh mylogin@final_server hostname')
('[RECEIVE] <<', u'[mylogin@proxy_jump_server ~]$ ssh mylogin@final_server 
hostname ; echo CLIENT_EXPECT_CMD_OK')
DEBUG:paramiko.transport:Incoming forward agent connection
DEBUG:paramiko.transport:[chan 2] Max packet in: 32768 bytes
DEBUG:paramiko.transport:[chan 2] Max packet out: 16384 bytes
DEBUG:paramiko.transport:Secsh channel 2 (auth-agent@openssh.com) opened.
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/site-packages/paramiko/agent.py", line 122, in run
raise AuthenticationException("Unable to connect to SSH agent")
AuthenticationException: Unable to connect to SSH agent

On final_server login log (looks fine =/ !):在 final_server 登录日志上(看起来不错 =/ !):

2019-01-09T19:50:12.417066+00:00 final_server sshd[7968]: Accepted 
publickey for mylogin from IP port 42360 ssh2
2019-01-09T19:50:12.428465+00:00 final_server sshd[7968]: 
pam_unix(sshd:session): session opened for user mylogin by (uid=0)
2019-01-09T19:50:12.521360+00:00 final_server sshd[7968]: 
pam_unix(sshd:session): session closed for user mylogin

Full code anonymized ( adapted from DSA key forwarding using Paramiko? ):完整代码匿名(改编自使用 Paramiko 的 DSA 密钥转发? ):

#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
import paramiko
class SSHSession:


    def __init__(self, server_address, user='mylogin', port=22):
        self.connected = False
        self.server_address = server_address
        self.user = user
        self.port = port


    def connect(self):

        try:
            k = paramiko.RSAKey.from_private_key_file("/mypath/mykey.ppk",password='blabla')
            self.ssh_client = paramiko.SSHClient()
            paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG) 
            self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh_client.connect(self.server_address, username=self.user, pkey=k)
            self.transport = self.ssh_client.get_transport()
            self.agent_channel = self.transport.open_session()
            self.agent_handler = paramiko.agent.AgentRequestHandler(self.agent_channel)
            self.channel= self.ssh_client.invoke_shell()

        except:
            self.connected = False

        else:
            self.connected = True
            return self.connected

    def exec_command(self, command, newline='\r'):
        if not self.connected:
            raise Exception('Not connected')

        else:
            timeout = 31536000 # 365 days in seconds
            self.channel.settimeout(timeout)
            line_buffer = ''
            channel_buffer = ''
            end_string = 'CLIENT_EXPECT_CMD_OK'
            print('[SEND ] >>', command)
            self.channel.send(command + ' ; echo ' + end_string + newline)

            while True:
                channel_buffer = self.channel.recv(1).decode('UTF-8')
                if len(channel_buffer) == 0:
                    raise Exception('connection lost with server: ' + self.server_address)
                    break
                channel_buffer = channel_buffer.replace('\r', '')
                if channel_buffer != '\n':
                    line_buffer += channel_buffer
                else:
                    if line_buffer == end_string:
                        break
                    print('[RECEIVE] <<', line_buffer)
                    line_buffer = ''


    def disconnect(self):
        self.ssh_client.close()

    def __enter__(self):
        self.connect()
        return self



    def __exit__(self, _type, value, traceback):
        self.disconnect()



    if __name__ == "__main__":
        server_address = 'proxy_jump_server'
        ssh_user = 'mylogin'
        with SSHSession(server_address) as ssh_session:
            ssh_session.exec_command('hostname')
            ssh_session.exec_command('ssh mylogin@final_server hostname' )

Any feedback is welcome !欢迎任何反馈! Been stuck for the whole day on that point.在那一点上被困了一整天。

Why do you run command-line ssh for the second step?为什么要在第二步运行命令行ssh

Use port forwarding instead.改用端口转发。

See Nested SSH using Python Paramiko .请参阅使用 Python Paramiko 的嵌套 SSH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM