3

So I have been scratching my head trying to figure this one out, and I'm a little stuck.

I'm using Python's subprocess module and Popen to open a PuTTY session, (using plink.exe), and connect to a remote host. This means I have access to the session output.

I'm trying to find a command, or write a script I can execute that will tell me the PID of the remote sshd process handling the session. If there were only one SSH session, I could use "ps -f | grep sshd" to list the sshd process, and find the PID from parsing that line.

The problem is, there are multiple SSH connections to this host simultaneously, and thus there are multiple instances of sshd running. Does anyone know a way I can determine the process running a particular session, by running a command from that same session?

Note: The following script will work for OS X and many forms of Linux.

#!/bin/sh TTY=$(tty) TTYID=${TTY##*/} ps -f | grep $TTYID 

This returns the line with the correct PID, which can then be parsed with Python. Unfortunately, I am using QNX, which does not have the TTY field implemented in "ps", so everything in that field just shows up a a '?'. Any other ideas?

Thanks!

1 Answer 1

8

Full format print pid of the shell you are running, and print third field that is the PPID (parent pid).

ps --no-headers -fp $$ | awk '{print $3}' 
Sign up to request clarification or add additional context in comments.

2 Comments

It worked! I didn't know that "$$" could be used to retrieve the PID like that. Thanks!
@static_void_meringue, @Sami Kerola, I have found that there is a little bit simpler solution: ps --no-headers -eo ppid -fp $$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.