How to connect ssh from a specified port?

That is not easily possible. How that can be done depends on where the source port shall be seen: Locally, too, or is it enough if it's the right port from the perspective of the external network?

You can run the SSH client in an LXC container. I have never done that thus I cannot explain it to you in detail. But you create a virtual network interface and attach it to this container so that ssh uses this interface because it is the only (external) interface it sees.

On the host system it should be possible to detect that a packet comes from this interface. Thus you can use Netfilter's NAT (SNAT) for rewriting the source address with something like:

iptables -t nat -A POSTROUTING -o vnet0 -p tcp --dport 22 -j SNAT --to-source :1234

Of course, this does not work (or becomes more complicated) if you connect to ports different from 22.


The command syntax you're looking for perhaps is this. ssh -p XXX user@remotehostip You have to change option's order. Try it now, it works for me. Best regards.


A simple solution for this if you are port forwarding through your router is to set the inbound port to whatever you want and the local port to 22. Your machine will still be taking ssh connection on 22 like normal but to actually connect from outside your network you would use your inbound port. If you're just trying to stop bots from hammering your machine on 22 this should do it.

This might not help for your specific problem but I would imagine a lot of people end up here for this reason.

Tags:

Ssh

Tcp

Openssh