Home > other >  use existing SSH_AUTH_SOCK to execute commands on remote server
use existing SSH_AUTH_SOCK to execute commands on remote server

Time:01-15

I connect to my work server (workserver1.com) from my local PC (localhost) using SSH and execute a bunch of commands on workserver1. Below are the commands I execute using SSH

1) run script on server collect production data and put it in a txt
   ssh -A workserver1.com 'python3 /usr/local/collect_data_online.py 2>&1 | tee /home/myname/out.txt'
   $ please input your dynamic token: <manually input credential token generated every 15s>
    
2) filter lines I need and put in a dat file
    ssh -A workserver1.com "grep 'my-keyword-cron' out.txt | grep -oP '({.*})' | tee workserver2.dat"
    $ please input your dynamic token: <manually input credential token again>
    
3) send data collected in 2) and send to workserver2 which could only access through workserver1**
    ssh -A workserver1.com 'curl workserver2.com --data-binary "@workserver2.dat" --compressed' "
    $ please input your dynamic token: <manually input credential token 3rd time>

In each steps above , I actually created 3 completed different socket with workserver1.com. I got this info from running command below on remote server

$ ssh -A workserver1.com 'printenv | grep SSH'
SSH_CLIENT=10.126.192.xxx 58276 22
SSH_SESSION_ID=787878787878787878
SSH_TTY=/dev/pts/0
SSH_AUTH_SOCK=/tmp/ssh-XXXXKuJLEX/agent.29291
SSH_AUTH_CERT_SERIAL=666666666
SSH_AUTH_CERT_KEY=myname
# SSH_CONNECTION changes each time I make a SSH request to workserver1.com. so I need repeatedly input dynamic token manually
SSH_CONNECTION=10.126.192.xxx 58276 10.218.35.yyy 22 

On my localhost I can also see SSH sock which used for the SSH connection

$ SSH_AUTH_SOCK=/tmp/ssh-localhost/agent.12345

My question is , is there a way to using single existing socket to avoid making multiple SSH connections and just input the dynamic token once. I hope I could use existing sock to interactively type commands to this SSH server and collect outpu/data as I want , just like on my localhost

What's in my mind is

1) socat can I run some command on localhost like
socat UNIX-CONNECT:$SSH_AUTH_SOCK,exec:'commands I want to execute' - ==> possible to get an interactive client&server shell?
2) is there any ssh option I could use ?

I am new to socat and not familiar with ssh except some commonly used commands Thank you for your help in advance

CodePudding user response:

The solution is open the first connection with '-M' First use ControlMaster and ControlPath in ~/.ssh/config as below:

host *
ControlMaster auto
ControlPath ~/.ssh/ssh_mux_%h_%p_%r

And when connect toremote host the very first time, add '-M'

ssh -M $remotehost

Then in follow ssh connection with the same host you could just use

ssh $remotehost
  • Related