I was experimenting with my .bashrc
file while remotely logged in to a server over SSH. I inadvertently left an exit
in there that caused all subsequent logins to immediately disconnect. I was effectively locked out. I was able to recover access with intervention from someone with root privileges, but would it have been possible without help from someone else?
I tried doing stuff like running ssh <server> 'bash --norc --noprofile'
and ssh <server> 'mv .bashrc bashrc-backup'
, and even trying to forcibly overwrite it with scp empty-file <server>:.bashrc
. However, all of these options seem to rely on first sourcing the broken .bashrc
before running the command, so none of them worked.
It may well be the case that there is no way out of this kind of a situation. But is that by design? Is there a reason for why it's so easy to lock oneself out a system, e.g. just by running ssh <server> 'echo exit > .bashrc'
? Are there ways to mitigate this kind of mistake?
Best Answer
As discussed in the other answer, when an SSH client connects to the OpenSSH server, the OpenSSH server will generally start a shell session on the client's behalf, using the user's login shell:
scp
,rsync
, andgit
which use ssh for transport will request a command to be run on the remote system, so they fall under #2.If you have something in the remote user's shell startup files which causes the shell to exit, then you will have trouble getting in.
SFTP however is a special case. The OpenSSH server may be configured to support SFTP without launching an external command. If that's the case, then you'd be able to use sftp to connect to the server and delete, rename, or alter the
.bashrc
file which is causing the problem.It depends on how the server is configured to support sftp. It can service sftp sessions by launching an external program (named
sftp-server
). In this case you'd have the same problem getting in that you have with programs likescp
. Or, the server can service sftp session by something referred to "internal-sftp", which doesn't require invoking a shell. It just depends on how the particular SSH server is configured.