Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

console

tty

I have an application that needs to behave differently if run directly from the linux console. So if a user connects with SSH to run FooBar, or the user walks over to the console and logs in directly to run FooBar, I want it to do something different.

What C API do I need to call to tell the difference between these two scenarios? I was thinking I'd have to look at the "tty/pts" information (such as what I see when I run "ps axf"), but I'm not certain if that is the best solution, nor what API to call to get that information.

Hints appreciated. :)

like image 588
Stéphane Avatar asked May 25 '10 19:05

Stéphane


4 Answers

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.

like image 67
developmentalinsanity Avatar answered Nov 14 '22 18:11

developmentalinsanity


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.

like image 39
ivans Avatar answered Nov 14 '22 17:11

ivans


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.

like image 5
Josh Kelley Avatar answered Nov 14 '22 16:11

Josh Kelley


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.

like image 3
Darien Avatar answered Nov 14 '22 17:11

Darien