Using a proxy for ssh connections based on netcat
Sometimes, we need to forward our ssh connection through a proxy, For example, you want to connect your cloud server through socks5 proxy. When you try to specify a proxy by executing export all_proxy=socks5://127.0.0.1:123
command through terminal, you will find that it does not take effect for ssh connection. Fortunately, netcat
can easily achieve your purpose.
Install netcat
1 | homebrew |
Configure ssh config
vim ~/.ssh/config
(Create it if it doesn’t exist.)1
2
3
4
5
6Host alliot_server-01 # specify a alias for this host
Hostname 192.168.1.123 # the IP/Hostname of this ssh connection
User root # ssh username
ForwardAgent yes
Port 22 # port
ProxyCommand /usr/bin/nc -X 5 -x 127.0.0.1:7890 %h %p # This configuration represents a proxy using the SOCKS v.5 protocol, and the proxy address is 127.0.0.1:1234
After do this, You can establish a connection on the basis of this proxy directly through ssh alliot_server-01
.
Dry-run
If you’re only connecting temporarily and don’t need persistence, you can directly use the following command:1
ssh -o ProxyCommand="/usr/bin/nc -X 5 -x 127.0.0.1:1234 %h %p" root@192.168.1.123 -p 22