Create a SOCKS proxy on a Linux server with SSH

OS:

cat /etc/redhat-release 
CentOS Linux release 7.8.2003 (Core)

uname -a
Linux xxx 3.10.0-1127.8.2.el7.x86_64 #1 SMP Tue May 12 16:57:42 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

SOCKS5 和 SOCKS5h 的区别仅用于 curl。在 curl 中,SOCKS5 会使用本地DNS,SOCKS5h 会使用代理提供的远程DNS。在其它软件中,SOCKS5h 基本不起作用,使用 SOCKS5 即可。一旦设置了代理,多数时候会采用远程DNS。

通过SSH可以创建tunnel连接到远程服务器,利用远程服务器来访问。首先看看SSH的命令:

ssh --help
unknown option -- -
usage: ssh [-1246AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
           [-D [bind_address:]port] [-E log_file] [-e escape_char]
           [-F configfile] [-I pkcs11] [-i identity_file]
           [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
           [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
           [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
           [user@]hostname [command]

You open an SSH connection to a remote server. As you open that connection, your SSH client will also open a local TCP port, available only to your computer. In this example, I’ll use local TCP port :2134.
You configure your browser (Chrome/Firefox/…) to use that local proxy instead of directly going out on the internet.
The remote SSH server accepts your SSH connection and will act as the _outgoing proxy for that SOCKS5 connection.
To start such a connection, run the following command in your terminal.

$ ssh -D 2134 -q -C -N user@ip

-D 2134: open a SOCKS proxy on local port :2134. If that port is taken, try a different port number. If you want to open multiple SOCKS proxies to multiple endpoints, choose a different port for each one.
-C: compress data in the tunnel, save bandwidth
-q: quiet mode, don’t output anything locally
-N: do not execute remote commands, useful for just forwarding ports
user@ip: the remote SSH server you have access to

If you prefer to keep it running in the background, add -f to fork it to a background command:

$ ssh -D 2134 -q -C -N -f user@ip

Now you have an SSH tunnel between your computer and the remote host,

如果要在Terminal使用proxy,需要设置

export http_proxy=socks5h://127.0.0.1:2134 https_proxy=socks5h://127.0.0.1:2134

还可以设置 ALL_PROXY=socks5h://127.0.0.1:2134

你可能感兴趣的:(linux)