首页 > 解决方案 > 使用 Plink 使用加密密码通过 SSH 连接到多个服务器

问题描述

我的批处理文件代码需要使用 SSH 在多个服务器上运行一些 shell 命令。为此,我正在使用for循环中的 Plink。

我不想使用纯文本将密码输入到 Plink 命令行-pw。相反,出于安全考虑,我想对我的密码使用密码加密并将密码存储到单独的文本文件中。

我尝试使用sshpass,但批量不支持。由于运行代码的请求将在多台服务器上,所以我不想为每台服务器生成 SSH 密钥对,因为环境中的数百台服务器是不可能的。

@echo off
for /f "delims=" %%a in (path\to\servers.txt) DO (
    plink -v -ssh user@%%a -pw MY_PASSWORD echo %%a ; cat /path/to/config_file
)
pause

我希望批处理脚本使用加密密码在所有服务器上运行。但是对于当前代码,输出使用纯密码显示。

标签: batch-filefor-loopsshpassword-encryptionplink

解决方案


使用普通的批处理文件很难做到这一点。

但是您可以将 PowerShell 与其ConvertTo-SecureStringConvertFrom-SecureStringcmdlet 一起使用。

要加密密码,请使用:

Read-Host -AsSecureString | ConvertFrom-SecureString

输入密码并将输出保存到文件 ( encryptedpassword.txt)。

要使用加密密码,请使用:

$encrypted = ConvertTo-SecureString(Get-Content ".\encryptedpassword.txt")
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($encrypted)
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)

foreach ($hostname in (Get-Content ".\servers.txt"))
{
    .\plink user@$hostname -pw "$password"
}

在 PowerShell 7 中,您可以将代码简化为:

$encrypted = ConvertTo-SecureString(Get-Content ".\encryptedpassword.txt")
$password = ConvertFrom-SecureString -SecureString $encrypted -AsPlainText
# ...

基于:


尽管我必须重复一遍,使用公钥身份验证将是一种更好的解决方案。


推荐阅读