Search code examples
pythonpython-2.7sshsftpssh-tunnel

Connecting to SFTP client using proxy command in Python


I need to connect to SFTP server using proxy command.

I know how to connect to SFTP server directly:
paramiko's sshclient with sftp

I can open an SSH connection via proxy command using this code:

import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
target_host = 'sftp.XXXXX.co'
target_port = 22
proxy = paramiko.proxy.ProxyCommand('/usr/bin/nc --proxy proxy_host:8080 %s %d' % (target_host, target_port) )
client.connect(hostname=target_host,username='username', port=target_port, password='XXXXXXXX', sock=proxy)

But I need to create SFTPClient, not SSHClient. But I do not know how to pass the ProxyCommand to the SFTPClient.


Solution

  • To connect to SFTP server using a "custom socket", do:

    proxy = paramiko.proxy.ProxyCommand(...)
    transport = paramiko.Transport(proxy)
    transport.connect(username = username, password = password)
    sftp = paramiko.SFTPClient.from_transport(transport)