2017-03-01 156 views
0

我使用powershell与SSH.Net库连接到ssh服务器并运行命令。大多数情况下工作正常,除了我有一个系统只启用了键盘交互式身份验证(并且我无法更改它)。如何在PowerShell中处理键盘交互式身份验证提示?

我发现了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() 

感谢您的阅读!

+0

基于它看起来像connect方法期待一个输入的被叫数据,其需要的错误放在括号内。建议查看该方法的文档以确定应该是什么类型/内容“数据”。 –

+0

这是我的想法之一,然而我链接到的工作C#代码没有任何这种称为数据的输入。 –

回答

1

此交互式键盘登录将在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(); 
相关问题