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