ssh exits with status 255: an SSH error, not your remote command
ssh returns the remote command's exit status, or 255 when ssh itself failed: no connection, refused login, bad host key or a killed command. Read stderr.
In a script, ssh passes on the exit status of the command it ran on the host:
ssh [email protected] 'exit 3'
echo $?
prints 3. The ssh manual adds one rule: ssh exits with 255 if an error occurred. So 255 usually means that ssh itself failed and your command may never have run.
What gives 255
- No connection: the name did not resolve, the port was refused, or the connection timed out.
- No login: "Permission denied", a host key that does not match, or a host key that could not be confirmed because no one was there to answer (for example with
BatchMode yes). - A failed jump host or ProxyCommand. See SSH "Connection closed by UNKNOWN port 65535": the ProxyJump or ProxyCommand failed.
- The remote command was killed by a signal, for example with
kill -9. The host then reports a signal instead of an exit status, and ssh exits with 255. - The remote command itself exited with 255. ssh passes that on, and you cannot tell it apart from an ssh error by the number alone.
Tell them apart
- Read stderr. ssh writes its own errors there, such as
ssh: connect to host host.example.com port 22: Connection refusedorPermission denied (publickey). Capture it in the script instead of throwing it away. - Add
-v. The last lines show how far the connection got. With-v, ssh also printsdebug1: Exit status 3when the command ran and returned a status. - Avoid 255 in your own scripts on the host, so that 255 always means an SSH failure.
Scripts and unattended runs
BatchMode yes (or -o BatchMode=yes) makes ssh fail at once instead of waiting for a password or a host key question that nobody will answer. The result is still 255, but it comes straight away with a clear message.
When there is no remote command at all, an interactive login, ssh returns the exit status of your login shell, which is the status of the last command you ran before exit.
Related
- SSH error messages, what each one means
- Connection abort, reset and timed-out errors in SSH and Telnet clients
- SSH "Connection closed by UNKNOWN port 65535": the ProxyJump or ProxyCommand failed
- ssh "Could not resolve hostname": Name or service not known
- Automate IBM i green-screen tasks: job scheduler, SBMJOB, SSH and screen scripts