使用 Plink 和批处理文件的多个命令用于 Cisco 交换机

Multiple commands using Plink and batch file for Cisco switch

我目前正在尝试编写一个脚本来更改 200 多台 Cisco 交换机的位置 (snmp)。

我的问题是我不能同时 运行 多个命令。我制作了一个批处理文件,它自动连接到交换机并读取列出命令的 .txt 文件。但无论我做什么,我得到的最好结果是只执行了第一个命令。

批处理文件:

cmd.exe /c echo n | "Filepath(plink)" -ssh Switch Hostname -l Username -pw "Password" -m "txt File"

txt 文件:

conf t
snmp-server location test
end
wr
exit

我已经在 txt 文件中尝试过其他分隔符,例如 ; | 等。 但似乎没有任何效果。

这实际上是 Cisco 的一个已知限制,它不支持 SSH "exec" 通道命令中的多个命令。

引用 PuTTY/Plink 手册的 3.8.3.6 -m: read a remote command or script from a file 部分:

With some servers (particularly Unix systems), you can even put multiple lines in this file and execute more than one command in sequence, or a whole shell script; but this is arguably an abuse, and cannot be expected to work on all servers. In particular, it is known not to work with certain ‘embedded’ servers, such as Cisco routers.


虽然实际上,您的命令可能不是独立的顶级 shell 命令。我猜 snmp-server(和其他)是 conf t 子命令 ,不是吗?所以你的代码将无法工作,即使 Cisco 在 "exec" 频道上支持多个命令。

详情见How to type commands in PuTTY by creating batch file?

您需要执行 conf t 然后将其子命令提供给其标准输入。

一种方法是这样的:

(
    echo snmp-server location test
    echo end
    echo wr
    echo exit
) | plink -ssh hostname -l username -pw password conf t

如果上述 Cisco 限制不影响此语法:

SET /P USERNAME=Enter remote Username:
SET "psCommand=powershell -Command "$pword = read-host 'Enter remote Password' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
    [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)"" for /f "usebackq delims=" %%p in (`%psCommand%`) do set PASSWORD=%%p
plink -t -pw %PASSWORD% %USERNAME%@Hostname "COMMAND1; COMMAND2; COMMAND3; ETC"

如果上面提到的 Cisco 限制确实影响了上面的语法:

SET /P USERNAME=Enter remote Username:
SET "psCommand=powershell -Command "$pword = read-host 'Enter remote Password' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
    [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)"" for /f "usebackq delims=" %%p in (`%psCommand%`) do set PASSWORD=%%p
plink -t -pw %PASSWORD% %USERNAME%@Hostname "COMMAND1"
plink -t -pw %PASSWORD% %USERNAME%@Hostname "COMMAND2"
plink -t -pw %PASSWORD% %USERNAME%@Hostname "COMMAND3"
plink -t -pw %PASSWORD% %USERNAME%@Hostname "Etc"

野蛮,是的,但我认为思科可以为此感谢 ;)(这是未经测试的,因为我没有思科设备可以戳,但理论应该是合理的)