您可以使用任何预先建立的会话sock
通过SSHClient.connect(hostname,username,password,...,sock)
.
下面是通过 HTTP-Proxy-Tunnel (HTTP-CONNECT) 建立 SSH 隧道的代码片段。首先建立到代理的连接,并指示代理连接到 localhost:22。结果是已建立会话上的 TCP 隧道,通常用于隧道 SSL,但可用于任何基于 tcp 的协议。
此方案适用于默认安装tinyproxy
withAllow <yourIP>
并ConnectPort 22
设置为/etc/tinyproxy.conf
. 在我的示例中,代理和 sshd 在同一主机上运行,但您只需要任何允许您访问CONNECT
ssh 端口的代理即可。通常这仅限于端口 443(提示:如果您让 sshd 在 443 上侦听,这将适用于大多数公共代理,即使出于互操作和安全原因我不建议这样做)。如果这最终允许您绕过防火墙,则取决于采用哪种防火墙。如果不涉及 DPI/SSL 拦截功能,你应该没问题。如果涉及 SSL 拦截,您仍然可以尝试通过 ssl 或作为 HTTP 有效负载的一部分进行隧道传输:)
import paramiko
import socket
import logging
logging.basicConfig(loglevel=logging.DEBUG)
LOG = logging.getLogger("xxx")
def http_proxy_tunnel_connect(proxy, target,timeout=None):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect(proxy)
LOG.debug("connected")
cmd_connect = "CONNECT %s:%d HTTP/1.1\r\n\r\n"%target
LOG.debug("--> %s"%repr(cmd_connect))
sock.sendall(cmd_connect)
response = []
sock.settimeout(2) # quick hack - replace this with something better performing.
try:
# in worst case this loop will take 2 seconds if not response was received (sock.timeout)
while True:
chunk = sock.recv(1024)
if not chunk: # if something goes wrong
break
response.append(chunk)
if "\r\n\r\n" in chunk: # we do not want to read too far ;)
break
except socket.error, se:
if "timed out" not in se:
response=[se]
response = ''.join(response)
LOG.debug("<-- %s"%repr(response))
if not "200 connection established" in response.lower():
raise Exception("Unable to establish HTTP-Tunnel: %s"%repr(response))
return sock
if __name__=="__main__":
LOG.setLevel(logging.DEBUG)
LOG.debug("--start--")
sock = http_proxy_tunnel_connect(proxy=("192.168.139.128",8888),
target=("192.168.139.128",22),
timeout=50)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname="192.168.139.128",sock=sock, username="xxxx", password="xxxxx")
print "#> whoami \n%s"% ssh.exec_command("whoami")[1].read()
输出:
DEBUG:xxx:--start--
DEBUG:xxx:connected
DEBUG:xxx:--> 'CONNECT 192.168.139.128:22 HTTP/1.1\r\n\r\n'
DEBUG:xxx:<-- 'HTTP/1.0 200 Connection established\r\nProxy-agent: tinyproxy/1.8.3\r\n\r\n'
#> whoami
root
这里 有一些关于如何通过代理隧道的其他资源。只需做建立隧道所需的一切并将套接字传递给SSHClient.connect(...,sock)