如何消除PowerShell SSH脚本不必要的Windows凭据请求?
问题
我用PowerShell脚本通过密钥文件建立SSH会话,已经提供了用户名和密钥文件路径,但脚本仍会弹出凭据请求窗口。点击确定(不输入密码)后连接能正常工作,说明这个弹窗完全没必要。请问怎么修改脚本移除这个凭据提示?
原脚本如下:
$sshParams = @{ Credential="user_name" HostName = $sshHostName KeyFile = $sshIdentityFile # .pem file } $sshSession = New-SSHSession @sshParams if ($null -ne $sshSession) { Write-Output "Connected to $sshHost" } else { $errorMessage = "SSH connection failed!" Write-Output $errorMessage throw $errorMessage } Write-Output "Closing SSH session..." Remove-SSHSession -SessionId $sshSession.SessionId
解决方案
问题出在你直接把字符串作为Credential参数传入,New-SSHSession会将这种情况识别为需要交互式获取凭据,因此弹出窗口。要移除弹窗,只需做以下修改:
- 替换
Credential参数为UserName,直接用该参数指定用户名 - 保留
KeyFile参数指向你的.pem密钥文件
修改后的脚本如下:
$sshParams = @{ UserName = "user_name" HostName = $sshHostName KeyFile = $sshIdentityFile # .pem file } $sshSession = New-SSHSession @sshParams if ($null -ne $sshSession) { Write-Output "Connected to $sshHostName" } else { $errorMessage = "SSH connection failed!" Write-Output $errorMessage throw $errorMessage } Write-Output "Closing SSH session..." Remove-SSHSession -SessionId $sshSession.SessionId
注:原脚本中$sshHost是未定义变量,已改为$sshHostName避免运行报错。
内容的提问来源于stack exchange,提问作者Gonzalo Sambucaro
相关产品推荐
相关产品推荐

