How to tell if running in a linux console versus an ssh session?

ttyname will tell you the name of the terminal connected to a given file descriptor; for example, ttyname(0) will tell you stdin's terminal.

This will of course fail if input or output is redirected.

Barring that, you can check various environment variables (SSH_CONNECTION, SSH_CLIENT, REMOTEHOST, DISPLAY, SESSIONNAME). Wireshark has logic to detect if it's being run remotely so that it doesn't capture network traffic that it generates; you might be interested in the logic that its get_conn_cfilter function uses to implement this.


Checking the return value of ttyname(3) against your stdin should give you the name of the terminal which is feeding the input of your process.

It will be /dev/console if the program is being run on the console (and doesn't have it's input redirected). You can also check stdout to see if it is connected to /dev/console - see which fits your usage scenario better.


I'd look at environment variables as a reasonable sign of what's going on. I'm not sure what C API you'd want for that, but I'm sure one exists.

For example, both the SSH_CLIENT or SSH_CONNECTION environment variables are set on my machine regardless of the SSH client being used.

It may be worth checking how universal these are based on the SSH server running on the machine.


Depending on how much you're worried about it being spoofed, an easy check would be for the presence/absence of the SSH_CLIENT and SSH_CONNECTION environment variables, in which case you'd want the getenv function.

Tags:

Linux

Console

Tty