When I ssh to a remote host, Is it possible that I get the remote bash pid in my local machine? or vice versa?

for example on local terminal, I simply do ssh and keep connection to run my tasks:

ssh user@remote.com

and the ps is like this on local machine:

ps faux
shunh    32683  0.1  0.0 121148  5116 pts/2    Ss   07:02   0:00  \_ -bash
shunh    33079  0.6  0.0 189360  8484 pts/2    S+   07:03   0:00      \_ ssh -X remote_host

and on remote_host:

ps faux
root     214679  0.0  0.0 158820  5724 ?        Ss   07:03   0:00  \_ sshd: shunh [priv]
shunh    214681  0.0  0.0 158820  2556 ?        S    07:03   0:00      \_ sshd: shunh@pts/1
shunh    214682  0.0  0.0 121124  3608 pts/1    Ss   07:03   0:00          \_ -bash

So can I get the pid number "214682" in my local machine?

  • The question is very strange. A direct, exact and completely useless answer would be: "ssh remote.system echo \$\$", which will print on local stdout a pid that bash had when it started on connection. That bash is immediately exited. But, why you want that pid? What do you want to achieve? – Nikita Kipriyanov Sep 24 '19 at 6:03


As @Nikita Kipriyanov commented, the simple way is

ssh user@remote.domain 'echo $$'

(using single quotes!), But seem not really usefull, because localhost will be able of reading process number only after they finish.

Use case:

There is some way of running ssh in order to foward ports, for sample: this will connect indirRem.remDom:22 via ssh proxy: user@rem.dom.

ssh -f -L2022:indirRem.remDom:22 user@rem.dom 'echo $$ $PPID;sleep 2' >/tmp/rpids.txt &&
    ssh -o HostKeyAlias=indirectRemote.remotedomain -p 2022 indUser@localhost

From there, if on localhost, you hit something like:

ssh user@rem.dom ps ef $(</tmp/rpids.txt)

You may see wich pid is used for current (open) session (while you don't close/end shell session on indirRem.remDom:22).

Mariadb/Mysql sample:

ssh -f -L 3306:localhost:3306 user@rem.dom 'echo $$ $PPID;sleep 2' >/tmp/rpids.txt &&
    mariadb -h -p"What a strong password" database

This will locally run mariadb client on local 3306 tcp port, but this port is a forwarded port from rem.dom (wich is normally listenning on loopback device only)

Same but forwarding UNIX socket instead of TCP service:

ssh -f -L 3306:/var/run/mysqld/mysqld.sock user@rem.dom 'echo $$ $PPID;sleep 2' >/tmp/rpids.txt &&
    mariadb -h -p"What a strong password" database


ssh user@rem.dom ps ef $(</tmp/rpids.txt)

will show the sshd process who hold forwarded ports.


Anyway, I don't see what to do with this /tmp/rpids.txt.

Read man ssh and man sshd, look for -M (master) and -S (slave) switches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.