Skip to content
shellhacks.dev
Network

Connect to a Non-Standard SSH Port with ssh -p

Connect to a non-standard port with ssh -p 2222 or a Port line in ssh_config, and check the result with ssh -G without connecting. scp uses a capital P.

1 min read
Summarize in AI

A server listens for SSH on a port other than 22, and you want to stop typing the option every time.

Shell
ssh -G example.com | grep '^port '
ssh -p 2222 -G example.com | grep '^port '
cat > cfg <<'EOF'
Host web
  HostName 192.0.2.10
  Port 2222
EOF
ssh -F cfg -G web | grep -E '^(hostname|port) '
ssh -F cfg -p 22 -G web | grep '^port '
Text
port 22
port 2222
hostname 192.0.2.10
port 2222
port 22

ssh -G host prints the configuration ssh would use after merging the command line, the config file and the defaults, and it connects to nothing, so the effect of an option can be checked first. The run shows the default of 22, then -p 2222 giving 2222, then a Host web block with Port 2222, and finally -p 22 on the command line winning over the file. Options on the command line beat the file. See ssh_config.

scp and sftp take the port as -P with a capital letter, because lowercase -p already means preserve times there. A Host block matches the name you type, not the resolved name, so a short alias in the config needs the same alias on the command line.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.