如何在PowerShell中处理键盘交互式身份验证提示?

时间:2017-03-01 03:08:06

标签: c# powershell events eventhandler ssh.net

我正在使用PowerShell与SSH.Net库连接到ssh服务器并运行命令。大多数情况下工作正常,但我的系统只启用了键盘交互式身份验证(我无法更改)。

我发现an answer描述了如何在C#中使用EventHandler来执行键盘交互式身份验证,但是我无法将其成功移植到PowerShell。它似乎与我正在处理事件的方式有关,但我不确定究竟是什么。任何帮助将不胜感激!

当我尝试运行以下代码时,我收到此错误:

Exception calling "Connect" with "0" argument(s): "Value cannot be null.
Parameter name: data"
At C:\Users\nathan\Documents\ssh-interactive-test.ps1:35 char:1
+ $Client.connect()
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

这是我正在运行的相关代码部分:

$scriptDir = $(Split-Path $MyInvocation.MyCommand.Path)
[reflection.assembly]::LoadFrom((Resolve-Path "$scriptDir\Renci.SshNet.3.5.dll")) | Out-Null

$ip = "ip address"
$user = "username"
$pass = "password"

$kauth = New-Object Renci.SshNet.KeyboardInteractiveAuthenticationMethod($user)
$pauth = New-Object Renci.SshNet.PasswordAuthenticationMethod($user, $pass)
$action = { 
    foreach ($prompt in $event.SourceEventArgs.Prompts) {
        if ($prompt.Request -like 'Password:*') {
            $prompt.Response = $pass
        }
    }
}
$oe = Register-ObjectEvent -InputObject $kauth -EventName AuthenticationPrompt -Action $action
$connectionInfo = New-Object Renci.SshNet.ConnectionInfo($ip, 22, $user, $pauth, $kauth)
$Client = New-Object Renci.SshNet.SshClient($connectionInfo)
$Client.connect()

感谢阅读!

1 个答案:

答案 0 :(得分:2)

此交互式键盘登录在PowerShell中适用于您。 Renci.SshNet从C#代码示例中获取的想法 下面将运行一个示例命令并获取每行的输出:

$scriptDir = $(Split-Path $MyInvocation.MyCommand.Path)
$ip = "ip address"
$user = "username"
$pass = "password"
$port = 22
Add-Type -Path "$scriptDir\Renci.SshNet.dll"

$action = {
    param([System.Object]$sender, [Renci.SshNet.Common.AuthenticationPromptEventArgs]$e)
    foreach ($prompt in $e.Prompts) {
        if ($prompt.Request.tolower() -like '*password:*') {
            prompt.Response = $pass;
        }
    }
}
$connectionInfo = [Renci.SshNet.KeyboardInteractiveConnectionInfo]::new($ip, $port, $user);
$oe = Register-ObjectEvent -InputObject $connectionInfo -EventName AuthenticationPrompt -Action $action
[Renci.SshNet.SshClient]$client = [Renci.SshNet.SshClient]::new($ip, $port, $user,$pass);
$client.Connect();
[Renci.SshNet.ShellStream]$shellStream = $client.CreateShellStream("dumb", 80, 24, 800, 600, 1024);
$shellStream.WriteLine("ps ax");
$result = $shellStream.ReadLine([System.TimeSpan]::FromMilliseconds(200));
while($result -ne $null) {
    Write-Host $result;
    if($result.Length -gt 1) {
        $result = $shellStream.ReadLine([System.TimeSpan]::FromMilliseconds(200));
    }
}
$client.Disconnect();