question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

SSH/SFTP connection via a SOCKS5 proxy

See original GitHub issue

Hi, thanks so much for the library.

Apologies if what I’m asking has been answered elsewhere. I’ve read through the docs and searched issues, but cannot find an answer to my question.

I’m trying to connect to an SFTP server via a SOCKS5 proxy (the client is running on heroku so needs to use a proxy like this to connect to a server which needs a static IP to whitelist).

I’m wondering if this is something asyncssh is able to do?

The only mention I can find of something related is forward_socks but that seems to be related to creating a socks proxy, not connecting through one.


To make the question more concrete, here’s an example using paramiko and socks of what I’m trying to do with asyncssh:

import paramiko
import socks


def with_paramiko():
    sock = socks.socksocket()

    sock.set_proxy(
        proxy_type=socks.SOCKS5,
        addr=proxy_host,
        port=proxy_port,
        username=proxy_username,
        password=proxy_password,
    )

    sock.connect((server_host, 22))

    transport = paramiko.Transport(sock)
    transport.connect(username=server_username, password=server_password)
    client = paramiko.SFTPClient.from_transport(transport)
    try:
        # do lots of stuff here
        print(client.listdir('/root/'))
    finally:
        client.close()
        transport.close()

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
samuelcolvincommented, Oct 25, 2021

For anyone else coming to this, there’s a working solution 🎉:

import asyncio
import stat

import aiosocks
import asyncssh
from asyncssh import SFTPClient

proxy_host = '...'
proxy_port = 123
proxy_username = '...'
proxy_password = '...'

server_host = '...'
server_port = 22
server_username = '...'
server_password = '...'


class SocksClientConnection:
    @staticmethod
    async def create_connection(session_factory, host, port):
        socks5_addr = aiosocks.Socks5Addr(proxy_host, proxy_port)
        socks5_auth = aiosocks.Socks5Auth(proxy_username, proxy_password)
        return await aiosocks.create_connection(
            session_factory, proxy=socks5_addr, proxy_auth=socks5_auth, dst=(host, port)
        )


async def tree(sftp_client: SFTPClient, path: str, indent: int = 0):
    """
    recursively print files and directories
    """
    async for file in sftp_client.scandir(path):
        if file.filename in ('.', '..'):
            continue
        file_path = f'{path}/{file.filename}'
        if stat.S_ISDIR(file.attrs.permissions):
            print(' ' * indent * 2, file_path, ':', sep='')
            await tree(sftp_client, file_path, indent + 1)
        else:
            print(' ' * indent * 2, file_path, ' (file)', sep='')
            async with sftp_client.open(file_path) as f:
                content = await f.read()
            print(f'"""\n{content!r}\n"""')


async def main():
    async with asyncssh.connect(
        server_host,
        tunnel=SocksClientConnection(),
        username=server_username,
        password=server_password,
        known_hosts=None,
    ) as conn:
        async with conn.start_sftp_client() as sftp:
            print('cwd:', await sftp.getcwd())
            await tree(sftp, '.')


if __name__ == '__main__':
    asyncio.run(main())
0reactions
ronfcommented, Oct 23, 2021

Yeah - it’s related. The example in #376 basically came out of what was discussed in #104. AsyncSSH also now supports specifying an external program to run to act as a proxy you can tunnel SSH requests over. However, that would be a lot less efficient than using aiosocks as shown in #376 for this use case.

Read more comments on GitHub >

github_iconTop Results From Across the Web

shell - SFTP using SOCKS proxy command with password ...
According to Is there a built-in way to proxy SSH through socks5?, this should do: sftp -o ProxyCommand='ncat --proxy-type socks5 ...
Read more >
Tunneling through proxy & SSH server - Unix Stack Exchange
I tried connecting through proxy option and SSH tunneling option in Winscp but the problem is as below: The SOCKS5 proxy is used...
Read more >
how to sftp using a SOCKS v5 proxy - LinuxQuestions.org
This is an old post. Thought my input will help subsequent visitors to this forum. Below is the command I used to connect...
Read more >
Java SFTP using SOCKS Proxy - Chilkat Example Code
Demonstrates how to connect to an SFTP/SSH server through a SOCKS4 or SOCKS5 proxy. Chilkat Java Downloads. Java Libs for Windows, Linux, Alpine...
Read more >
Proxies and custom sockets - Rebex SFTP - Rebex.NET
To connect through SOCKET4, SOCKET4a or SOCKS5 proxy servers, set Sftp.Proxy properties before calling the Connect method. Use ProxyType property to specify ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found