I have two servers hosted in IDC. I can only use ports 20/21/22/23/3389/33101-33109 to establish connections between two servers. The IDC network device will block any other packets whose source or destination port is not in the 20/21/22/23/80/3389/33101-33109 list/range. But the source port of SSH is random.

Using the command ssh username@server -p remote_port one can easily specify a remote port.

So is there an ssh command parameter or some other way to specify a local source port so I can use, for example, port 33101 to establish the SSH connection?

My network topology is like this:
network topology

2 Answers 2


You can not specify the source port for ssh client.

But you can use nc as a proxy, like this:

ssh -p 33101 -o 'ProxyCommand nc -p 33101 %h %p' $SERVER_2

From How can i set the source port for SSH on unbuntu server? (on ServerFault).


For one-off, or anyway occasional, situations the ProxyCommand approach is easily a very convenient one.

On the other hand, if you need several simultaneous connections, or when perhaps you need to use that command frequently for daily work, you might also instead consider to set a network-address-translation (NAT) rule on your server.

This requires superuser (typically root) access on your server to first apply the one single NAT rule. Note that it might not be allowed (or effective) at all to apply the NAT rule, even when you have superuser access, if your "server" is actually a container (like a Docker one) instead of a machine.

Speaking of a typical Linux system with the iptables suite, the NAT rule to apply on your server1 for your sample case could be like:

iptables -t nat -I POSTROUTING -d <server2-ip-address> -p tcp --dport <server2-port> -j SNAT --to :33101-33109

That command instructs the Linux kernel to make any connections towards port server2-port of server2-ip-address to go out using a source port chosen within the range 33101-33109 that is available at that moment.

Once that rule is in place, you connect to your server2 just with your usual:

ssh username@server2 -p remote_port

and you could use this same ssh command also concurrently for as many times as you need, as long as there are available ports in the range specified in the NAT rule.

Note however that a netstat (or equivalent command) run on your server reports the connection's local address as being the unmodified, randomly chosen, source port number even though the actual traffic that is delivered to your server2 carries the modified source port number.

To undo the NAT rule, the command is the same except for a -D option in place of the -I.

To have the NAT rule applied automatically at boot depends on what Linux distribution you have on your server, and on whether it already has some firewall configuration in place or not.

I have no experience with BSD-like systems, but I trust there is an equivalent.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .