ssh-proxy.py
1086 bytes
1#!/usr/bin/env python3
2import os
3import subprocess
4import sys
5from urllib.parse import urlparse
6
7proxy = next(os.environ[_] for _ in ("HTTP_PROXY", "HTTPS_PROXY") if _ in os.environ)
8
9parsed = urlparse(proxy)
10
11proxy_protocols = {
12 "http": "connect",
13 "https": "connect",
14 "socks": "5",
15 "socks5": "5",
16 "socks4": "4",
17 "socks4a": "4",
18}
19
20if parsed.scheme not in proxy_protocols:
21 raise TypeError('unsupported proxy protocol: "{}"'.format(parsed.scheme))
22
23def make_argv():
24 yield "nc"
25 if sys.platform in {'linux', 'cygwin'}:
26 # caveats: the built-in netcat of most linux distributions and cygwin support proxy type
27 # caveats: macOS built-in netcat command not supported proxy-type
28 yield "-X" # --proxy-type
29 # Supported protocols are 4 (SOCKS v4), 5 (SOCKS v5) and connect (HTTP proxy).
30 # Default SOCKS v5 is used.
31 yield proxy_protocols[parsed.scheme]
32 yield "-x" # --proxy
33 yield parsed.netloc # proxy-host:proxy-port
34 yield sys.argv[1] # host
35 yield sys.argv[2] # port
36
37subprocess.call(make_argv())