将 Paramiko 与 SOCKS 代理结合使用

Min*_*iMe 5 python ssh proxy paramiko socks

我尝试将 Paramiko 与 SOCKS 代理一起使用(SecureCRT 或 PuTTY 配置为 SOCKS 代理)。我正在使用下面的代码

import paramiko,socks

host, port = '127.0.0.1', 1080

# Set up your proxy information for this socket
sock=socks.socksocket()
sock.set_proxy(
    proxy_type=socks.SOCKS4,
    addr=host,
    port=port,
)

# Connect the socket
sock.connect((host, port))

# Create your Paramiko Transport
transport = paramiko.Transport(sock)
transport.connect(
    username='username',     #<------not sure if it is needed, the socks proxy needs no username/password
    password='secret',
)
client = paramiko.client.SSHClient.connect('remotedevice', username='usernameonremotedevice',sock=sock)
stdin, stdout, stderr=client.exec_command("ls -la")
# Do stuff

# Clean up
client.close()
transport.close()
Run Code Online (Sandbox Code Playgroud)

上述方法似乎让 Paramiko 感到困惑,因为它同时使用 127.0.0.1。我的问题起源于 Exscript 使用的 Paramiko 库,所以我想简化一下看看这是否可行......

这是 SecureCRT 每次尝试时显示的日志

import paramiko,socks

host, port = '127.0.0.1', 1080

# Set up your proxy information for this socket
sock=socks.socksocket()
sock.set_proxy(
    proxy_type=socks.SOCKS4,
    addr=host,
    port=port,
)

# Connect the socket
sock.connect((host, port))

# Create your Paramiko Transport
transport = paramiko.Transport(sock)
transport.connect(
    username='username',     #<------not sure if it is needed, the socks proxy needs no username/password
    password='secret',
)
client = paramiko.client.SSHClient.connect('remotedevice', username='usernameonremotedevice',sock=sock)
stdin, stdout, stderr=client.exec_command("ls -la")
# Do stuff

# Clean up
client.close()
transport.close()
Run Code Online (Sandbox Code Playgroud)

该脚本失败如下:

[LOCAL] : Starting port forward from 127.0.0.1 on local 127.0.0.1:1080 to remote 127.0.0.1:1080.  
[LOCAL] : Could not start port forwarding from local service 127.0.0.1:3106 to 127.0.0.1:1080.  Reason: The channel could not be opened because the connection failed.  Server error details:     Connection refused  
Run Code Online (Sandbox Code Playgroud)

Cae*_*sar 9

@pynexj 的答案是正确的,但有一个完整的工作示例总是好的:

\n
import socks\nimport paramiko\n\nsock=socks.socksocket()\nsock.set_proxy(\n    proxy_type=socks.SOCKS5,\n    addr="proxy.host.name.example",\n    port=1080,\n    username="blubbs",\n    password="blabbs"\n)\nsock.connect((\'ssh.host.name.example\', 22))\n\nssh = paramiko.SSHClient()\nssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\nssh.connect(\'ignored without host key verification\', username=\'caesar\', sock=sock)\nprint((ssh.exec_command(\'ls\')[1]).read().decode())\nssh.close()\n
Run Code Online (Sandbox Code Playgroud)\n

(很高兴知道是否sock必须单独关闭\xe2\x80\xa6)

\n

旁注:确保不要将密码身份验证与AutoAddPolicy. 最好根本不使用密码身份验证。(看评论。)

\n


pyn*_*exj 3

sock.connect((host, port))应使用 SSH 服务器的主机名(与您使用的主机相同SSHClient.connect())和端口(默认22)。