gpt4 book ai didi

python - 使用SSH中的SSH ProxyCommand的SFTP

转载 作者:行者123 更新时间:2023-12-02 14:32:58 33 4
gpt4 key购买 nike

我正在使用以下SSH配置下载一些文件:

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 proxyuser@proxy.example.com 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上的配置。有什么建议么?

最佳答案

解决了以下问题:

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 '
'proxyuser@proxy.example.com 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())

关于python - 使用SSH中的SSH ProxyCommand的SFTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39629209/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com