使用加密密码使用PLINK将SSH的密码用于多个服务器



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

我不想使用-pw输入纯文本的密码到PLINK命令行。相反,由于安全问题,我想使用密码加密并将密码存储到单独的文本文件中。

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

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

我希望批处理脚本可以使用加密密码在所有服务器上运行。但是有了当前代码,输出将使用普通密码显示。

很难用普通批处理文件实现此目的。

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

加密密码:

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
# ...

基于:

  • 我的文章保护用于自动化的凭据
  • 因此,问题将安全的字符串转换为纯文本

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

最新更新