A ssh server on listens on port 2222. I know I can just add -p2222 or add an alias in ~/.bash_aliases, but is there a way to force a certain port when I ssh a specified IP?


Sure, you can put these settings in ~/.ssh/config.

Port 2222

You can take this opportunity to give the machine a nickname, and set other options, in particular the remote user name. For example, the following declaration makes ssh foo equivalent to ssh -p 2222 matt@ (Host foo means that the following options apply when you run ssh foo, and the HostName directive makes foo a nickname for with all the other options):

Host foo
Port 2222
User matt
  • Tried the bottom [with 'foo'] and it didn't work. ["port 22 refused"].. the other one works though – Matt Nov 18 '11 at 0:19
  • @Matt Did you run ssh foo and not ssh You use the nickname given after Host, I should have stated this more clearly in my answer. – Gilles 'SO- stop being evil' Nov 18 '11 at 1:03
  • 1
    ohh.. no, I guess I misunderstood. – Matt Nov 18 '11 at 1:23
  • Is it possible to add custom flags? I'd like to automatically have -q enabled – Alexander Jan 25 '14 at 23:54
  • 1
    @XAleXOwnZX You can't set custom flags, but you can set options. -q is equivalent to LogLevel QUIET. – Gilles 'SO- stop being evil' Jan 26 '14 at 0:03

You could add the host to your ssh configuration file. Run man ssh_config from a terminal for some nice reading.

In short place

Host <hostname>
Port 2222

in your ~/.ssh/config


For any ec2 instance IP, automatically picks useranme and key file.

Host *.*.*.* IdentityFile ~/.ssh/key.pem Port 22 CheckHostIP no PasswordAuthentication no User ec2-user UserKnownHostsFile /dev/null StrictHostKeyChecking no

  • Thank you but does it answer the question (port number)? – Marc Vanhoomissen May 17 '19 at 9:10
  • 1
    @MarcVanhoomissen thanks for pointing out. I have updated with port – Mohammad Selim Miah May 18 '19 at 1:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.