Guides

ssh command: -i key file, port, jump host, remote commands and how to exit

The ssh command options you need: ssh -i for a key file, -p, -J jump hosts, running remote commands with -t, -v debugging and how to exit a frozen session.

Published ~9 min read
On this page

Short answer: ssh -i ~/.ssh/KEY -p PORT USER@HOST logs in with a specific key on a non-default port. Put a command after the host to run only that command and come back, add -t when that command is interactive, and leave a session with exit, or with Enter, ~, . when it is frozen.

Linux · macOS · Windows (OpenSSH)
ssh -i ~/.ssh/deploy_ed25519 -p 2222 deploy@203.0.113.10   # key file and port
ssh -J admin@198.51.100.5 deploy@10.0.0.12                   # through a jump host
ssh deploy@203.0.113.10 'df -h /'                            # run one command, then return
ssh -t deploy@203.0.113.10 'sudo apt upgrade'                # interactive command: needs -t
ssh -v deploy@203.0.113.10                                   # show every step of the login

The outputs below come from OpenSSH 9.2p1 (Debian 12) on our own server, without contacting any other host. Windows 10 and 11 ship Microsoft's port of the OpenSSH client; see SSH on Windows.

ssh options at a glance

OptionWhat it doesExample
-i FILEPrivate key to log in withssh -i ~/.ssh/deploy_ed25519 HOST
-p PORTServer port, 22 if not givenssh -p 2222 HOST
-J HOSTHop through a jump host firstssh -J admin@bastion HOST
-L, -R, -DForward a port, or act as a SOCKS proxyssh -N -L 5432:127.0.0.1:5432 HOST
-N, -fNo remote command; go to the backgroundssh -f -N -D 1080 HOST
-t, -tt, -TTerminal on, forced, or offssh -t HOST htop
-v, -vv, -vvvDebug output, up to three levelsssh -v HOST
-o KEY=VALUEAny ssh_config option for this one runssh -o ConnectTimeout=5 HOST
-GPrint the resolved settings, do not connectssh -G HOST

ssh -i: choose the key file

Without -i, OpenSSH 9.2 tries seven standard names in ~/.ssh (id_rsa, id_ecdsa, id_ed25519 and variants). A key with any other name needs -i or an IdentityFile line, and ssh -G shows that -i replaces the list:

Output · OpenSSH 9.2p1, ssh -F none reads no config file
$ ssh -F none -G 203.0.113.10 | grep -c '^identityfile'
7
$ ssh -F none -G -i ./deploy_ed25519 203.0.113.10 | grep '^identityfile'
identityfile ./deploy_ed25519

A wrong path does not stop the login. ssh prints Warning: Identity file ./missing_key not accessible: No such file or directory. and carries on with the default names, so read the first line of the output when a key "is ignored". A key file that others can read is refused outright. We gave a throwaway key mode 644, and ssh-keygen -y, which loads keys with the same check, printed:

Output · private key with mode 0644
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'deploy_ed25519' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "deploy_ed25519": bad permissions

chmod 600 ~/.ssh/deploy_ed25519 fixes it. One more trap: -i does not stop ssh from also offering every key loaded in your ssh-agent. With many keys loaded, the server can give up before it reaches the right one (sshd allows 6 attempts by default, set by MaxAuthTries). Add -o IdentitiesOnly=yes to offer only the file you named. When the server still answers Permission denied (publickey), the publickey guide walks through the server side.

Port, user and jump host: -p, -l and -J

  • ssh -p 2222 deploy@203.0.113.10, ssh -p 2222 -l deploy 203.0.113.10 and ssh ssh://deploy@203.0.113.10:2222 are the same login; scp and sftp spell the port option as a capital -P. Without a user, ssh sends your local user name.
  • ssh -J admin@198.51.100.5 deploy@10.0.0.12 logs in to the jump host, then opens a forwarded TCP connection from there to the private address. Several hops are separated by commas, and a hop on another port takes it inline: -J admin@198.51.100.5:2222. Other options on the command line apply to the final host only, so a jump host that needs its own key belongs in ~/.ssh/config with ProxyJump.

Run a command on the server: ssh host 'command'

Linux · macOS
ssh deploy@203.0.113.10 'uptime'
ssh deploy@203.0.113.10 'df -h / && free -h'
ssh deploy@203.0.113.10 'tar czf - /srv/site' > site.tar.gz    # stream a backup home
ssh deploy@203.0.113.10 'bash -s' < ./check.sh                 # run a local script remotely
ssh deploy@203.0.113.10 'exit 3'; echo $?                      # prints 3
  • The command runs in your login shell on the server, without a terminal, so its output is clean for pipes and files.
  • Quote the whole command in single quotes. In ssh host "echo $HOME" your local shell replaces $HOME before ssh even starts; ssh host 'echo $HOME' prints the home directory on the server. Anything after the closing quote, such as a pipe, runs on your side.
  • ssh exits with the remote command's exit status, or with 255 when ssh itself failed, so scripts can tell "the command failed" from "could not log in".
  • In a while read host loop, use ssh -n: without it, ssh reads the rest of the loop's input and the loop stops after the first host.

-t: interactive commands like sudo, top and tmux

Because a command runs without a terminal, anything that needs one fails. sudo 1.9.13 (Debian 12) answers a password prompt it cannot show with sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper, and full-screen programs like htop cannot draw. -t requests a terminal:

Linux · macOS
ssh -t deploy@203.0.113.10 'sudo systemctl restart nginx'
ssh -t deploy@203.0.113.10 'tmux attach || tmux new'

If your own input is not a terminal (a script, cron, a pipe), ssh skips the request and says Pseudo-terminal will not be allocated because stdin is not a terminal. -tt forces it anyway. A session without a terminal is transparent for binary data, which is why the tar stream above arrives intact; -T disables the terminal explicitly.

Port forwarding: -L, -R and -D in one line each

Linux · macOS · Windows
ssh -N -L 5432:127.0.0.1:5432 deploy@203.0.113.10   # server's PostgreSQL on your localhost:5432
ssh -N -R 8080:127.0.0.1:3000 deploy@203.0.113.10   # your local port 3000 on the server's port 8080
ssh -N -D 1080 deploy@203.0.113.10                  # SOCKS5 proxy on your localhost:1080

-N skips the shell, -f sends ssh to the background, and a -R port listens only on the server's loopback unless sshd allows GatewayPorts. Bind addresses, autossh and systemd units are in the SSH tunnel guide.

Debug a login with -v

-v prints each step; -vv and -vvv print more, and -E ssh.log writes it to a file. This run went to a test listener on our server that sends an SSH greeting and then hangs up:

Output, shortened · ssh -v -F none -p 52222 -i ./deploy_ed25519 deploy@127.0.0.1
OpenSSH_9.2p1 Debian-2+deb12u…, OpenSSL 3.0.22 25 Aug 2026
debug1: Connecting to 127.0.0.1 [127.0.0.1] port 52222.
debug1: Connection established.
debug1: identity file ./deploy_ed25519 type 3
debug1: identity file ./deploy_ed25519-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_9.2p1 Debian-2+deb12u…
debug1: Remote protocol version 2.0, remote software version OpenSSH_9.2p1 Debian-2+deb12u…
debug1: Authenticating to 127.0.0.1:52222 as 'deploy'
debug1: SSH2_MSG_KEXINIT sent
Connection closed by 127.0.0.1 port 52222

Find the last line that worked. No Connection established means the network or a firewall stopped you; type -1 after a key you meant to use means ssh could not load that file (on the -cert line it only means you have no certificate, which is normal); a hang-up during key exchange, as here, is explained in the server's log (journalctl -u ssh on Debian and Ubuntu). On a real login the next lines list the keys offered and the methods the server accepts.

How to exit an SSH session

  • Type exit (or logout), or press Ctrl+D on an empty line. bash treats Ctrl+D as end of input unless IGNOREEOF is set.
  • Frozen session (no key does anything after a network drop or a sleeping laptop): press Enter, then ~, then .. ssh only reads an escape at the start of a line, which is why Enter comes first.
  • Nested sessions: ~. closes the outer one, and everything inside it. ~~. sends the escape one level down and closes only the inner session.
  • Nothing happens? Escapes need a terminal (a command run without -t has none), and -e none or EscapeChar none turns them off.
Type after EnterEffect
~.Disconnect
~?List the escape sequences
~^ZSuspend ssh (Ctrl+Z); fg brings it back
~CCommand line for adding or removing forwards; off by default since OpenSSH 9.2 (EnableEscapeCommandline)
~~Send a literal ~

Sessions that drop by themselves when idle are a different problem, fixed with keepalives: see SSH broken pipe.

-o: any config option for a single command

Every keyword from ssh_config works as -o Keyword=value. Command-line options are read before ~/.ssh/config and /etc/ssh/ssh_config, and the first value found wins, so -o overrides your files for that one run:

OptionEffect
StrictHostKeyChecking=accept-newAccepts the key of a new host without asking, still refuses a changed key
ConnectTimeout=5Gives up after 5 seconds, for the TCP connect and the handshake
BatchMode=yesNever prompts, fails instead: for scripts and cron (on Debian it also sets ServerAliveInterval to 300)
IdentitiesOnly=yesOffers only the keys from -i or IdentityFile

ssh -G -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new HOST printed connecttimeout 5 and stricthostkeychecking accept-new. An option you type every time belongs in ~/.ssh/config instead.

ssh-agent basics

ssh-agent holds unlocked keys in memory, so you type a passphrase once per session instead of once per login. If ssh-add -l answers Could not open a connection to your authentication agent., none is running in this shell, so start one:

Linux · macOS
eval "$(ssh-agent -s)"                # start an agent for this shell
ssh-add ~/.ssh/deploy_ed25519         # unlock and load a key
ssh-add -l                            # list loaded keys
ssh-add -t 1h ~/.ssh/deploy_ed25519   # load with a one-hour lifetime
ssh-add -D                            # remove every key
Output · ssh-add 9.2p1 with a throwaway key
$ ssh-add ./deploy_ed25519
Identity added: ./deploy_ed25519 (throwaway)
$ ssh-add -l
256 SHA256:3RpjmArhRPlgbG62ll6cImCRQzcMcqnXzLzegHRvt/0 throwaway (ED25519)
$ ssh-add -D
All identities removed.

An empty agent answers ssh-add -l with The agent has no identities. and status 1, and AddKeysToAgent yes in your config loads a key the first time ssh uses it. On Windows the agent is a service that has to be enabled first, as SSH on Windows shows.

On a new VPS or dedicated server, install your own key with ssh-copy-id first, and keep one session open while you change sshd_config, so a mistake cannot lock you out.

Frequently asked

How do I use ssh -i with a private key?

Run ssh -i ~/.ssh/KEY user@host with the path to the private key file, the one without .pub. The file must not be readable by other users (chmod 600); otherwise ssh ignores it and prints a WARNING: UNPROTECTED PRIVATE KEY FILE! banner. If your ssh-agent holds several keys, add -o IdentitiesOnly=yes so that only this key is offered.

How do I exit an SSH session?

Type exit, or press Ctrl+D on an empty line. If the session is frozen and no key responds, press Enter and then type ~. (tilde, period), which makes your local ssh client close the connection. In a session opened from inside another one, ~~. closes only the inner session.

How do I run a command on a server over SSH?

Put the command after the host in single quotes, for example ssh user@host 'df -h /'. ssh runs it in your login shell on the server, prints the output and exits with the command's exit status, or with 255 when ssh itself failed. Add -t for interactive programs such as sudo with a password prompt, top or tmux.

What does ssh -t do?

It makes ssh request a pseudo-terminal for the session. A command given after the host normally runs without one, which is right for scripts and pipes but breaks sudo password prompts and full-screen programs. Use -tt when ssh itself runs without a terminal, for example from a script or cron job.

Related articles

All guides