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

SSH Stream is the key element to starting a ssh dialogue with sudo and further commands

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.

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)

The $stream variable brings all you need for next commands:


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.