Powershell: managing ubuntu with sudo and Posh-ssh
Using Powershell module Posh-ssh is a soft-way to handle a Linux system with ssh service enabled. But not all linux system had the same security policies for ssh user/role/session: thinking about ubuntu, during installation, the first user could gain the administrator privileges only using sudo command.
But during server deployment, is quite boring (and sometimes is denied) enable direct root access to send ssh commands with ubuntu OS. In this case Powershell and Posh-SSH are great solutions to manage a linux server via ssh. Let’s see how to implement a sudo dialogue.
The code!
The first step using Posh-SSH is establishing the connection with the server
1 2 |
$oCredential = New-Object System.Management.Automation.PSCredential ($sUser, $sPassword) $oSessionSSH = New-SSHSession -ComputerName $sHost -Credential $oCredential |
SSH Stream is the key element to starting a ssh dialogue with sudo and further commands
1 |
$stream = $oSessionSSH.Session.CreateShellStream("PS-SSH", 0, 0, 0, 0, 1000) |
Finally the real stream could starts with secure action, which is waiting sudo su answers “[sudo] password for…”. Note: sudo su answer is language legacy command. For this reason you should modify the –ExpectString with the answer in Italian or other languages.
1 2 3 4 |
$result = Invoke-SSHStreamExpectSecureAction -ShellStream $stream -Command "sudo su -" -ExpectString "[sudo] password for $($sUser):" -SecureAction $sClearPassword if ($result -eq "False"){ $result = Invoke-SSHStreamExpectSecureAction -ShellStream $stream -Command "sudo su -" -ExpectString "[sudo] password di $($sUser):" -SecureAction $sClearPassword } |
Time to read the stream (this flush the stream buffer) and go ahead to other commands. Note: there is a key value that is not depending on the regoular code flow: every issued commands are not synchronized with the code flow due to the nature of the stream. For this reason, if you would read the steam after command, you must introduce a sleep (depending on the connection from 1 to 5 seconds)
1 2 3 4 |
$sReturn = $stream.Read() $stream.WriteLine("whoami") sleep -s 2 $sReturn = $stream.Read() |
The $stream variable brings all you need for next commands:
1 2 3 |
$stream.WriteLine("whoami") sleep -s 1 $sReturn = $stream.Read() |
Note
At the moment I don’t find a way to improve stream dialogue, for this reason if the connection fails and/or network latecy is to could get Nopredictable results.