我有一个批处理脚本,用于在本地计算机和可通过 SSH 隧道访问的计算机之间同步数据。我希望隧道在批处理脚本启动时启动,在同步完成时结束,而不是一直保持隧道打开。
如何从批处理脚本启动和停止 plink,并在中间执行利用 plink 创建的隧道的 Windows 命令?
答案1
我能够结合start
和taskkill
命令将 plink 集成到我的批处理脚本中:
@echo off
set local_port=1580
set remote_ip=10.19.0.241
set remote_port=1580
set wait_for_tunnel_seconds=4
set [email protected]
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_%
使用的其他工具: