batch-file - 使用 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
我希望批处理脚本使用加密密码在所有服务器上运行。但是对于当前代码,输出使用纯密码显示。
解决方案
使用普通的批处理文件很难做到这一点。
但是您可以将 PowerShell 与其ConvertTo-SecureString
和ConvertFrom-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
# ...
基于:
- 我的文章保护用于自动化的凭据
- 和 SO 问题将安全字符串转换为纯文本
尽管我必须重复一遍,使用公钥身份验证将是一种更好的解决方案。
推荐阅读
- javascript - 为什么我的 React 应用程序中没有呈现 Bootstrap Native 组件?
- ruby-on-rails - 为什么设计重定向我的登录请求?
- javascript - 谷歌工作箱库中的自定义获取事件?
- excel - 在执行宏时生成数字并将其传输到另一个表中,其中另一个表中没有现有数据
- javascript - auth.onAuthStateChanged 在 Firebase 中的 auth.currentUser.updateProfile 之后未触发
- python - 熊猫解析excel文件都在A列
- python - 提高图像分类模型的准确性
- android - 如何使用 iframe 在 Android 应用上播放 vemio 视频?
- jquery - 在选项卡之间自动切换 - 但在单击重新启动时
- python - 这种按位操作如何更改特定索引的单个位?