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 with PowerShell via SSH, I used SSH from PowerShell using the SSH.NET library and How to connect via SSH from powershell. That was great and gave me simple commandlets such as new-sshsession and invoke-sshcommand to work with.
Next, I wanted to su to a different user. When I tried to do that via the commandlets, I got the error: standard in must be a tty.
I understand that I can edit the security settings on the server to let me su to a user without being in interactive mode. However, I can't change that setting on all the servers I want to connect to.
Working off of a C# example I found at https://sshnet.codeplex.com/discussions/285853, I put together:
$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()
Running, that I get output such as:
Last login: Fri Nov 8 11:37:45 2013 from 10.XXX.XXX.XXX
[user1@server1 /users/user1]
However, /users/user1/tempfile.txt
never gets written and I do not get any further output.
Do you see what I'm doing wrong?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…