如何通过经过身份验证的HTTP代理通过SSH执行远程命令?

时间:2019-08-21 14:06:37

标签: python ssh proxy paramiko http-proxy

我还发布了问题和答案,以防它对某人有所帮助。以下是我的最低要求:

1. Client machine is Windows 10 and remote server is Linux
2. Connect to remote server via SSH through HTTP Proxy
3. HTTP Proxy uses Basic Authentication
4. Run commands on remote server and display output

该脚本的目的是登录到远程服务器,运行服务器上存在的bash脚本(check.sh)并显示结果。 Bash脚本只运行显示服务器整体运行状况的命令列表。

这里,关于如何使用Paramiko实现HTTP代理或运行远程命令的讨论很多。但是,我找不到两者的组合。

from urllib.parse import urlparse
from http.client import HTTPConnection
import paramiko
from base64 import b64encode

# host details
host = "remote-server-IP"
port = 22

# proxy connection & socket definition
proxy_url = "http://uname001:passw0rd123@HTTP-proxy-server-IP:proxy-port"
url = urlparse(proxy_url)
http_con = HTTPConnection(url.hostname, url.port)
auth = b64encode(bytes(url.username + ':' + url.password,"utf-8")).decode("ascii")

headers = { 'Proxy-Authorization' : 'Basic %s' % auth }

http_con.set_tunnel(host, port, headers)
http_con.connect()
sock = http_con.sock

# ssh connection
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
        ssh.connect(hostname=host, port=port, username='remote-server-uname', password='remote-server-pwd', sock=sock)
except paramiko.SSHException:
        print("Connection Failed")
        quit()

stdin,stdout,stderr = ssh.exec_command("./check")

for line in stdout.readlines():
        print(line.strip())
ssh.close()

由于我是网络分析师而不是编码人员,但热衷于学习和改进,因此欢迎对代码提出任何建议。

1 个答案:

答案 0 :(得分:0)

我认为您的代理代码不正确。

有关有效的代理代码,请参见How to ssh over http proxy in Python?,尤其是answer by @tintin

似乎您需要对代理进行身份验证,在CONNECT命令之后,添加一个Proxy-Authorization标头,如:

Proxy-Authorization: Basic <credentials>

其中<credentials>是base-64编码的字符串username:password

cmd_connect = "CONNECT {}:{} HTTP/1.1\r\nProxy-Authorization: Basic <credentials>\r\n\r\n".format(*target)