You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

能否使用sshtunnel Python模块实现类似ssh -N -D 9000 username@serverip的动态SSH端口转发?

Can I replicate ssh -N -D 9000 username@serverip with the sshtunnel Python module?

Absolutely! You can fully replicate the dynamic SOCKS proxy behavior of that SSH command using the sshtunnel library. This is a well-supported use case for the module, and it’s straightforward to implement.

Working Code Example

from sshtunnel import SSHTunnelForwarder

# Replace these with your actual server credentials
SERVER_IP = "your_server_ip"
USERNAME = "your_username"
LOCAL_PROXY_PORT = 9000

# Set up and run the dynamic tunnel
with SSHTunnelForwarder(
    (SERVER_IP, 22),  # SSH server address + default SSH port
    ssh_username=USERNAME,
    # Optional: Add authentication details here
    # ssh_password="your_password" or ssh_pkey="/path/to/your/private/key"
    local_bind_address=('localhost', LOCAL_PROXY_PORT),
    remote_bind_address=None,  # Key for enabling dynamic SOCKS forwarding
) as tunnel:
    print(f"Dynamic SOCKS proxy active on localhost:{LOCAL_PROXY_PORT}")
    print("Press Ctrl+C to shut down the tunnel...")
    tunnel.block()  # Keeps the tunnel running without remote commands (matches -N flag)

How This Matches Your SSH Command

Let’s break down the parallels to ssh -N -D 9000 username@serverip:

  • -D 9000: The combination of local_bind_address=('localhost', 9000) and remote_bind_address=None tells sshtunnel to create a SOCKS proxy on your local port 9000, routing all traffic through the SSH server.
  • -N: The tunnel.block() call keeps the tunnel alive without executing any remote shell commands, exactly like the -N flag in the original SSH command.
  • username@serverip: Maps directly to ssh_username=USERNAME and the (SERVER_IP, 22) address parameter.

Key Notes

  • Ensure your SSH server allows dynamic forwarding: Check the server’s sshd_config file for AllowTcpForwarding yes (this is typically enabled by default).
  • Authentication: Use password auth with ssh_password or (preferably) key-based auth with ssh_pkey for better security.
  • Alternative setup (without with statement): If you prefer manual control, initialize and start the tunnel like this:
    tunnel = SSHTunnelForwarder(...)
    tunnel.start()
    tunnel.block()
    # Remember to run tunnel.stop() when you're done to clean up resources
    

Once the tunnel is running, you can configure your browser or applications to use localhost:9000 as a SOCKS5 proxy—just as you would after running the original SSH command.

内容的提问来源于stack exchange,提问作者EMA

火山引擎 最新活动