Did you know that if you press “~” then C while in an ssh session, you get access to several useful commands? You can set up new local and remote forwarding, or stop existing forwarding, all while the connection is still running. From inside the session. But one little-known fact is that you can also run arbitrary local commands too.
The in-session command menu
Also called the “escapechar menu”. With an ssh session running, press ENTER, then “~”, then “C”. A little command menu will appear. One of the options will be “
!args” (provided you have permitted local commands – see below).
To then run an arbitrary command locally (i.e., on the computer you initiated the ssh session from), type “!command”, where “command” is whatever command you want to run, including all paths, arguments, shell redirections and so on. Then press ENTER to run the command. The command is run using “
sh -c“, so whatever shell is configured on your local system as “sh” will be used.
The key thing that will help 90% of people who are led here by Uncle Google 🙂 is that
stdout is not what you think it is inside the command prompt environment. If you try to do something like
!echo "Hullo World!", it will appear to silently fail – no output, no error message. I don’t know where it goes, but it does not go to your local console. But if you do something like
!echo "Hullo World!" > /tmp/out.txt, you will see that the command did run and did work.
/tmp/out.txt will appear on your local computer, and will contain the text “Hello World!”
However, you do need to have first enabled local commands! Do this by setting the
PermitLocalCommand ssh client configuration item to “yes”.
PermitLocalCommand enables(or disables) both the
LocalCommand configuration item and the “!” command in the in-session command menu.
LocalCommand and the “!” command in the in-session command menu are otherwise unrelated.
As with all ssh configuration items, you can put
- in the global ssh configuration file
- in your personal
.ssh/configfile for a particular host
- on the ssh command line via “
If this item is set, then the given command will be executed once, locally, when the ssh connection has been established. Unlike the in-session command, this command will have access to your local
Once you have pressed “~” then “C” (in your running ssh session) to get to the in-session command menu, the “!” character introduces the command you want to run locally. Everything after the “!” is the command.