使用 .bat 文件中的 plink.exe 在 SSH 服务器上执行命令

问题描述

我对批处理脚本很陌生,批处理文件中有以下内容

echo off
setlocal

SET cluster="cluster"

( 
    cd "C:\path"
    python script.py -nodes %cluster% -type worker -index 1 -batch 64 > log.log 2>&1
) | plink.exe -ssh user@host -pw password 

cd "C:\path2" 
python worker.py -nodes %cluster% -type worker -index 0 -batch 64 > log.log 2>&1
pause

但是,有些事情发生了:

( 
    cd "C:\path"
    python script.py -nodes %cluster% -type worker -index 1 -batch 64 > log.log 2>&1
) | plink.exe -ssh user@host -pw password 

python 文件似乎没有在远程服务器上运行(或者如果是,则日志文件没有保存)。另外,plink.exe 给了我一些奇怪的输出——下面是我看到的:

Using username "user".
[2J[?25l[m[H

[H]0;c:\windows\system32\cmd.exe[?25h[?25lMicrosoft Windows [Version 10.0.18363.1377][9X[9C
(c) 2019 Microsoft Corporation. All rights reserved.
[52X[52C
user@host C:\Users\user>[10X[10C[4;43H]0;Administrator: c:\windows\system32\cmd.exe[?25h
^

如果我要在 cmd.exe 上 plink.exe -ssh user@host -pw password,我也会得到上面的输出

然而,我更感兴趣的是理解命令的原因

cd "C:\path"
python script.py -nodes %cluster% -type worker -index 1 -batch 64 > log.log 2>&1
do not seem to be executed on the server.

命令

cd "C:\path2"  
python worker.py -nodes %cluster% -type worker -index 0 -batch 64 > log.log 2>&1

似乎工作正常,因为我看到正在保存日志文件。 ssh 时的命令没有。

解决方法

要使用 Plink 执行命令,请使用 -m switch,您可以使用它来提供文件路径以及要执行的命令列表:

plink.exe [email protected] -pw password -no-antispoof -m c:\local\path\commands.txt

在您的情况下,commands.txt 将包含:

cd "C:\path"
python script.py -nodes %cluster% -type worker -index 1 -batch 64 > log.log 2>&1

Plink (plink.exe) 也可以在其命令行上接受命令,例如:

plink.exe [email protected] -pw password -no-antispoof "cd C:\path && python script.py -nodes %cluster% -type worker -index 1 -batch 64 > log.log 2>&1"