Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a batch script that synchronizes data between a local machine and a machine that can be reached over an SSH tunnel. Rather than leaving the tunnel open all the time, I'd like it to start when the batch script starts and end when the synchronization is complete.

How can I start and stop plink from a batch script, executing Windows commands in the middle that take advantage of the tunnel plink creates?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

I was able to combine the start and taskkill commands to integrate plink into my batch script:

@echo off

set local_port=1580
set remote_ip=10.19.0.241
set remote_port=1580
set wait_for_tunnel_seconds=4
set ssh_host=user@example.com

min.exe

echo --- Closing any active tunnels
taskkill /f /fi "imagename eq plink.exe"

echo --- Opening tunnel from local port %local_port% to remote %remote_ip%:%remote_port%
start /min plink -T -L %local_port%:%remote_ip%:%remote_port% %ssh_host%
ping -n %wait_for_tunnel_seconds% 127.0.0.1 >nul
tcping -n 1 localhost %local_port%
IF %ERRORLEVEL% neq 0 (
    echo --- Failed to open tunnel. Canceling.
    taskkill /f /fi "imagename eq plink.exe"
    rem Use the port number as the exit code (makes it obvious in scheduled task last run result)
    EXIT /b %local_port%
)

echo --- Starting synchronization
set error_=0
sync_command.exe
set error_=%ERRORLEVEL%
if %error_% neq 0 (
    echo --- Sync completed, but with errors. Exit result: %error_%
) else (
    echo --- Sync completed
)

echo --- Closing tunnel
taskkill /f /fi "imagename eq plink.exe"

exit /b %error_%

Other tools used:

  • MIN.EXE for minimizing the command window immediately (this is called as a scheduled task)
  • TCPING.EXE for verifying that the tunnel is alive
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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