Last active
April 5, 2026 05:35
-
-
Save Littleor/32d31232a13efada1623bdbecdf39e80 to your computer and use it in GitHub Desktop.
Python Script for SSH Proxy without more packages.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import os | |
| import select | |
| import socket | |
| import sys | |
| def main() -> int: | |
| if len(sys.argv) != 5: | |
| sys.stderr.write( | |
| "Usage: http-connect.py <proxy_host> <proxy_port> <target_host> <target_port>\n" | |
| ) | |
| return 2 | |
| proxy_host = sys.argv[1] | |
| proxy_port = int(sys.argv[2]) | |
| target_host = sys.argv[3] | |
| target_port = int(sys.argv[4]) | |
| sock = socket.create_connection((proxy_host, proxy_port)) | |
| request = ( | |
| f"CONNECT {target_host}:{target_port} HTTP/1.1\r\n" | |
| f"Host: {target_host}:{target_port}\r\n" | |
| "Proxy-Connection: Keep-Alive\r\n" | |
| "\r\n" | |
| ) | |
| sock.sendall(request.encode("ascii")) | |
| response = b"" | |
| while b"\r\n\r\n" not in response: | |
| chunk = sock.recv(4096) | |
| if not chunk: | |
| sys.stderr.write("Proxy closed before CONNECT completed.\n") | |
| return 1 | |
| response += chunk | |
| header, _, rest = response.partition(b"\r\n\r\n") | |
| first_line = header.split(b"\r\n", 1)[0] | |
| if b" 200 " not in first_line: | |
| sys.stderr.write(header.decode("latin1", errors="replace") + "\n") | |
| return 1 | |
| if rest: | |
| os.write(sys.stdout.fileno(), rest) | |
| stdin_fd = sys.stdin.fileno() | |
| stdout_fd = sys.stdout.fileno() | |
| inputs = [sock, stdin_fd] | |
| while inputs: | |
| readable, _, _ = select.select(inputs, [], []) | |
| if sock in readable: | |
| data = sock.recv(65536) | |
| if not data: | |
| break | |
| os.write(stdout_fd, data) | |
| if stdin_fd in readable: | |
| data = os.read(stdin_fd, 65536) | |
| if not data: | |
| inputs.remove(stdin_fd) | |
| try: | |
| sock.shutdown(socket.SHUT_WR) | |
| except OSError: | |
| pass | |
| else: | |
| sock.sendall(data) | |
| sock.close() | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |
| # Add the following snippet to `~/.ssh/config` to route GitHub SSH through a proxy without needing to install `ncat` or other packages. | |
| # Host github.com | |
| # HostName ssh.github.com | |
| # User git | |
| # Port 443 | |
| # ProxyCommand python3 ~/.ssh/ssh_proxy.py 127.0.0.1 7890 %h %p | |
| # StrictHostKeyChecking no | |
| # UserKnownHostsFile /dev/null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment