How can I specify a local port when establishing SSH connections?

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.

Tags:

Ssh

Networking