ssh-proxy.py 1.1 KB

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