2016-09-22 185 views
0

我下載了一些文件有以下SSH配置:SFTP與SSH ProxyCommand在python

Host proxy 
    Hostname  proxy.example.com 
    User   proxyuser 
    IdentityFile ~/.ssh/proxy_id_rsa 

Host target  # uses password auth 
    Hostname  target.example.com 
    User   targetuser 
    ProxyCommand ssh proxy nc %h %p 

我試圖自動下載文件 - 目前使用的paramiko,但如果它可以使用另一個庫會更容易。

這裏就是我基於一些其他答案嘗試:

from paramiko.proxy import ProxyCommand 
from paramiko.transport import Transport 
from paramiko.sftp_client import SFTPClient 

proxy = ProxyCommand('ssh -i /Users/ben/.ssh/proxy_id_rsa [email protected] nc target.example.com 22') 
client = SFTPClient(proxy) 
client.connect(username='targetuser', password='targetpassword') 

然而,這引發錯誤

Traceback (most recent call last): 
    File "sftp.py", line 6, in <module> 
    client = SFTPClient(proxy) 
    File "/Users/ben/.virtualenvs/venv/lib/python3.5/site-packages/paramiko/sftp_client.py", line 99, in __init__ 
    server_version = self._send_version() 
    File "/Users/ben/.virtualenvs/venv/lib/python3.5/site-packages/paramiko/sftp.py", line 105, in _send_version 
    t, data = self._read_packet() 
    File "/Users/ben/.virtualenvs/venv/lib/python3.5/site-packages/paramiko/sftp.py", line 177, in _read_packet 
    raise SFTPError('Garbage packet received') 
paramiko.sftp.SFTPError: Garbage packet received 

不幸的是,錯誤消息不是非常有幫助的,所以我在我可以改變的東西損失。我無法更改target上的配置,如果可以避免,我不希望更改proxy上的配置。有什麼建議麼?

回答

0

解決了以下內容:

class PatchedProxyCommand(ProxyCommand): 
    # work around https://github.com/paramiko/paramiko/issues/789 

    @property 
    def closed(self): 
     return self.process.returncode is not None 

    @property 
    def _closed(self): 
     # Concession to Python 3 socket-like API 
     return self.closed 

    def close(self): 
     self.process.kill() 
     self.process.poll() 

proxy = PatchedProxyCommand('ssh -i /Users/ben/.ssh/proxy_id_rsa ' 
          '[email protected] nc target.example.com 22') 

transport = Transport(proxy) 
key = HostKeyEntry.from_line('target.example.com ssh-rsa ' 
          'AAAAB3NzaC1yc2EAAAA/base64+stuff==').key 
transport.connect(hostkey=key, 
        username='targetuser', password='targetpass') 
sftp = SFTPClient.from_transport(transport) 

print(sftp.listdir())