3

I am interested to know if there is any way that I can find out if I am in a nested SSH session and how many of them?

For example, From host2 ssh user1@host1 then from host1 ssh user1@host2 ends up in host1, but actually I can exit to go to host2.

How can I know that I am in such a situation (in a nested ssh session), other than exit command of course?

1 Answer 1

2

Not a perfect solution because not all SSH clients support this; and these that do can be configured differently. Still…

ssh from OpenSSH supports the following:

ESCAPE CHARACTERS

When a pseudo-terminal has been requested, ssh supports a number of functions through the use of an escape character.

A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option.

The supported escapes (assuming the default ~) are:

[…]

~^Z
Background ssh.

[…]

~C
Open command line. […] !command allows the user to execute a local command if the PermitLocalCommand option is enabled in ssh_config(5). Basic help is available, using the -h option.

[…]

Assuming all the chained SSH clients support this, and assuming pseudo-terminals have been requested, you can tell the number of connections by observing how many tilde characters are "consumed" before the actual tilde appears in the current command line. Remember the tilde must always follow a newline to be interpreted as special. My tests show that each connection consumes one escape character.

E.g. if after Enter you need to send ~ four times to get one ~ on the screen, then it means there are three chained connections.

You can background any of them by sending Enter, a respective number of ~ and then Ctrl+Z. This will place you in the respective shell where you can investigate where you came from (env | grep ^SSH_), where you are (uname -a, hostname, …), what the backgrounded command is (jobs). Run fg to get the connection back. What you can do depends on the shell and how you did run the respective ssh, I won't elaborate.

It would be nice if there was an escape function that makes ssh itself print basic information about the connection (similar to ~#). It seems there is no such functionality (yet).

With ~C (C here means capital C, Shift+C) and !command you may be able to investigate without sending any ssh to the background. Note the default value of PermitLocalCommand is no. AFAIK you cannot change it after the connection is established, so think ahead.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .