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?


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=
set remote_port=1580
set wait_for_tunnel_seconds=4
set ssh_host=user@example.com


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% >nul
tcping -n 1 localhost %local_port%
    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
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

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.