# Import the Posh-SSH module Import-Module Posh-SSH # Define the connection details $server = "your_server_ip_or_hostname" $port = 22 $username = "your_username" $password = "your_password" # Define the command to run as root $command = "your_command_here" # Create a new SSH session $securePassword = ConvertTo-SecureString $password -AsPlainText -Force $credential = New-Object -TypeName PSCredential -ArgumentList $username, $securePassword $session = New-SSHSession -ComputerName $server -Port $port -Credential $credential if ($session) { try { Write-Host "Connected to $server" # Create a shell stream $stream = $session.Session.CreateShellStream("PS-SSH", 0, 0, 0, 0, 100) # Get the current user's name $user = Invoke-SSHCommand -SessionId $session.SessionId -Command "whoami" $SSHusersName = $user.Output | Out-String $SSHusersName = $SSHusersName.Trim() # Define the secure password action $secpas = { param ($stream) $stream.WriteLine($using:password) } # Execute sudo su - and provide the password $results = Invoke-SSHStreamExpectSecureAction -ShellStream $stream -Command "sudo su -" -ExpectString "[sudo] password for $($SSHusersName):" -SecureAction $secpas $stream.Read() # Execute the command as root $stream.WriteLine($command) Start-Sleep -Seconds 1 # Give it a moment to execute $output = $stream.Read() # Output the result Write-Host "Command executed as root. Output:" Write-Host $output } catch { Write-Host "Error: $_" } finally { # Disconnect the session Remove-SSHSession -SessionId $session.SessionId } } else { Write-Host "Failed to connect to $server" }