PowerShell,读/写SSH.NET流

时间:2013-11-08 17:03:48

标签: c# .net powershell ssh

我想通过SSH连接到服务器,使用PowerShell,,然后更改为其他用户

为了通过SSH实现与PowerShell的服务器连接,我使用了SSH from PowerShell using the SSH.NET libraryHow to connect via SSH from powershell。这很棒,并为我提供了简单的命令行开关,例如 new-sshsession invoke-sshcommand

接下来,我想 su 给不同的用户。当我尝试通过命令行开关执行此操作时,我收到错误:标准必须是tty

我知道我可以编辑服务器上的安全设置,让我 su 给用户,而不是处于交互模式。但是,我无法在我想要连接的所有服务器上更改该设置。

使用我在https://sshnet.codeplex.com/discussions/285853找到的C#示例,我把它放在一起:

$server = "server1"
$port = 22
$username = "user1"
$password = "password1"

$ssh = new-object Renci.SshNet.SshClient($server, $port, $username, $password)
$ssh.Connect()

$inputstream = new-object System.IO.MemoryStream
$streamwriter = new-object System.IO.StreamWriter($inputstream)
$outputstream = new-object System.IO.MemoryStream
$streamreader = new-object System.IO.StreamReader($outputstream)

$shell = $ssh.CreateShell($inputstream, $outputstream, $outputstream)
$shell.Start()
$streamwriter.WriteLine("echo hello > tempfile.txt")
$streamwriter.Flush()
$streamreader.ReadToEnd()

$shell.Stop()

跑步,我得到输出,如:

Last login: Fri Nov  8 11:37:45 2013 from 10.XXX.XXX.XXX
[user1@server1 /users/user1]

但是,/users/user1/tempfile.txt永远不会被写入,我不会得到任何进一步的输出。

你看到我做错了吗?

1 个答案:

答案 0 :(得分:7)

使用https://sshnet.codeplex.com/discussions/439210中的示例,我能够使用以下代码解决我的问题。主要问题是我正在为输入/输出创建两个不同的流,我只需要使用一个流。

$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()