Execute a command on local computer from a connected remote SSH host?

Say I have connected to a remote computer via SSH. From a program on this remote computer, I need to execute a command on my local computer (the connection initiator).

Which raises the question: is it possible to leech onto the existing connection between the two computers to run a command on the local computer?

I have considered running the command ssh user@host-of-connecting-party <command> on the remote computer to establish a reversed connection. But this is harder to automate and will require user intervention. I was hoping I could fully automate it, or at least detect the user/hostname of the connected user.


Solution 1:

I'm having a similar need sometimes, as long as I connect over Putty to our VPN server and from there over ssh to some other host, which is not reachable for me directly due to VPN setup.

Sometimes I just need to quickly check something on a VPN server machine, while still having my "ssh-session" running. One approach is to run a ssh session under screen, which, as I've noticed, add some delay in comparison with "regular ssh". Another approach, which I'd like to share here, is the following:

While under SSH session, Press Enter, then ~, (make sure it's not displayed, i.e. you're in a command mode), then Ctrl-Z. This will put the ssh client process on a "host" to background, and you'll something along the lines of:

[root@client170 ~]# ~^Z [suspend ssh]

[1]+  Stopped                 ssh [email protected]
[root@vps291736 ~]#

Now you're on the "host", can do whatever you want (although, I am not sure how long ssh session will be kept alive), and then return to SSH session by running fg.

At least, this works for me while I am connected from a Win10 workstation via Putty on a CentOS-based VM, and from that VM connect over SSH to some other host.

Hope it helps someone!

Solution 2:

@62mkv's answer is a much better solution. Use that.

For completeness and curiosity though, if you have an ssh server running on your local machine, you could create an ssh tunnel to allow ssh connections from the remote host on port 20202 back to the local one on port 22. Example command:

ssh -R20202:localhost:22 [email protected]

This will start an ssh connection, but also set up a tunnel back to the ssh server running on your machine. Then you can do this, when ssh'ed into the remote host:

ssh -p 20202 localuser@localhost

Of course, this can quickly get confusing - especially if the technique is nested more than once. It adds a bit of latency, too - since everything you execute on your local machine is bounced through the remote host.

Additional information about ssh tunneling for those whose curiosity hasn't been satisfied yet can be found in answer to this unix stackexchange question.