使用paramiko与socks代理

时间:2017-11-22 18:11:57

标签: paramiko socks

我试图使用配置为socks代理的socks代理(SecureCRT或putty)的paramiko。我使用以下代码和

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()

以下是我遇到的错误

上述方法似乎混淆了paramiko,因为它两者都使用127.0.0.1 我的问题起源于exscript使用的paramiko库,所以我想简化一下,看看这是否有效....

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

 [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  

脚本失败如下:

Traceback (most recent call last):
  File "C:\Users\Username\Documents\Eclipse\ESNetworkDiscovery\ParamikoProxyTest.py", line 24, in <module>
    sock.connect((host, port))
  File "C:\Utils\WPy2.7-32\python-2.7.13\lib\site-packages\socks.py", line 96, in wrapper
    return function(*args, **kwargs)
  File "C:\Utils\WPy2.7-32\python-2.7.13\lib\site-packages\socks.py", line 813, in connect
    negotiate(self, dest_addr, dest_port)
  File "C:\Utils\WPy2.7-32\python-2.7.13\lib\site-packages\socks.py", line 667, in _negotiate_SOCKS4
    raise SOCKS4Error("{0:#04x}: {1}".format(status, error))
socks.SOCKS4Error: 0x5b: Request rejected or failed

2 个答案:

答案 0 :(得分:1)

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

import socks
import paramiko

sock=socks.socksocket()
sock.set_proxy(
    proxy_type=socks.SOCKS5,
    addr="proxy.host.name.example",
    port=1080,
    username="blubbs",
    password="blabbs"
)
sock.connect(('ssh.host.name.example', 22))

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('ignored without host key verification', username='caesar', sock=sock)
print((ssh.exec_command('ls')[1]).read().decode())
ssh.close()

答案 1 :(得分:0)

sock.connect((host, port))应该使用SSH服务器的主机名(用于SSHClient.connect()的主机)和端口(默认22用于SSH)​​。

相关问题