SSH Tunnel from Windows as a background process?

Viewed 3400

On Windows server we have a working OpenSSH SSH Tunnel to our MySQL database:

ssh -l <USER> -i <PUBLIC_KEY_FILE> -L 127.0.0.1:3306:localhost:3306 <SERVER_IP>

We would need to script it:

  1. set the tunnel up as backgound process
  2. do some stuff in foreground process, including but not limited to loading data from the database to local Windows machine
  3. then close the backgound ssh tunnel/process once foreground stuff have been done How would we do this?

With cmd/.bat we achieve the first two points by launching the ssh in separate cmd with start: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/start

START ssh -l <USER> -i <PUBLIC_KEY_FILE> -L 127.0.0.1:3306:localhost:3306 <SERVER_IP> -T

Then we can do our stuff part, but then we have not figured out how to close that concrete tunnel, without killing all the running ssh.exe processes. We do not want to kill all of them. Is there some way?

Then we were thinking about Powershell:

Start-Job -Name "RUN_SSH_TUNNEL_X1" -ScriptBlock {ssh...
...stuff...
Stop-Job -Name "RUN_SSH_TUNNEL_X1"

But this does not seem to work, the job "RUN_SSH_TUNNEL_X1" seems to stop right after it is started, so the tunnel does not stay up. Is there some way to keep the job up and running to close it after our stuff part is done?

Or should it be done with some other method? NB! Would like not to have to use 3rd party tools like Putty etc.

1 Answers

We left the tunnel creation in the bat file.

From Powershell then checked the running tasks run statement to check if the SSH tunnel was created/running. If not then called the tunnel create bat file.

Once work done called the same SSH tunnel task check and if was running, then killed the task.

Related