PowerShell, read/write to SSH.NET streams

前端 未结 1 1526
耶瑟儿~
耶瑟儿~ 2020-12-11 09:03

I would like to connect to a server via SSH, with PowerShell, and then change to a different user.

In order to accomplish connecting to a server wit

相关标签:
1条回答
  • 2020-12-11 09:24

    Using an example from https://sshnet.codeplex.com/discussions/439210, I was able to solve my problem with the below code. The main issue was that I was creating two different streams for input/output and I needed to just use one stream.

    $server = "server1"
    $port = 22
    $username = "user1"
    $password = "password1"
    
    ###############################################################
    
    function ReadStream($reader)
    {
        $line = $reader.ReadLine();
        while ($line -ne $null)
        {
            $line
            $line = $reader.ReadLine()
        }
    }
    
    function WriteStream($cmd, $writer, $stream)
    {
        $writer.WriteLine($cmd)
        while ($stream.Length -eq 0)
        {
            start-sleep -milliseconds 500
        }
    }
    
    ###############################################################
    
    $ssh = new-object Renci.SshNet.SshClient($server, $port, $username, $password)
    $ssh.Connect()
    
    $stream = $ssh.CreateShellStream("dumb", 80, 24, 800, 600, 1024)
    
    $reader = new-object System.IO.StreamReader($stream)
    $writer = new-object System.IO.StreamWriter($stream)
    $writer.AutoFlush = $true
    
    while ($stream.Length -eq 0)
    {
        start-sleep -milliseconds 500
    }
    ReadStream $reader
    
    WriteStream "su - root" $writer $stream
    ReadStream $reader
    
    WriteStream "password" $writer $stream
    ReadStream $reader
    
    WriteStream "pwd" $writer $stream
    ReadStream $reader
    
    $stream.Dispose()
    $ssh.Disconnect()
    $ssh.Dispose()
    
    0 讨论(0)
提交回复
热议问题