how to "sudo root" with posh-ssh (powershell) - powershell

i am using posh-ssh to connect to my ssh server do some commands start with su root,but i can not switch user to root sucessfully.
PS C:\> $rootpwdSec = ConvertTo-SecureString $rootpwd -AsPlainText -Force
PS C:\> Invoke-SSHStreamExpectSecureAction -Command 'su ' -ExpectString 'Password:' -SecureAction $rootpwdSec -ShellStream $stream
True
PS C:\> $stream.read();
[root#aaaaaa-test admin]#
PS C:\> Invoke-SSHCommandStream -SessionId $SessionId -Command 'id'
uid=500(admin) gid=500(admin) groups=500(admin) context=user_u:system_r:unconfined_t
PS C:\>
how can run my command as root?

What I noticed when working with posh-ssh and ubuntu was I was failing to sudo up to root using "sudo su -" due to the ExpectString. It was expecting "[sudo] password for (username):" and I was merely providing "password:"
$stream = $session.Session.CreateShellStream("PS-SSH", 0, 0, 0, 0, 100)
$user = Invoke-SSHCommand $session -Command "whoami"
$SSHusersName = $user.Output | Out-String
$SSHusersName = $SSHusersName.Trim()
$results = Invoke-SSHStreamExpectSecureAction -ShellStream $stream -Command "sudo su -" -ExpectString "[sudo] password for $($SSHusersName):" -SecureAction $secpas
$stream.Read()
This was how I was able to sudo to root. Again it may be different for you depending on what *nix variant you are connecting to.

Related

PSExec registry file remotly

I am trying to execute a PowerShell to execute a reg file remotly
This is what I have at the moment:
$computer = 'IP';
$username = 'user';
$password = 'password';
$reg = 'regedit /s //ip/teste.reg';
$reg_command = "psExec -i -d -c -f -s \\$computer -u $computer\$username -p $password `"$reg`"";
Write-Output "Inserting regestry file...";
Invoke-Expression $reg_command;
I have psExec in my computer, but I don't know how I would add the path executable for PSExec in the code.

Powershell command-line with Autologon.exe

Has anyone made the 'Autologon.exe for Windows v3.10' work with PowerShell v5.1?
Execution 1:
As administrator the following is run:
.\Autologon.exe -n guest10 -d test.com -p Password1 -accepteula yes
Error 1:
Execution 2:
As administrator in powershell the following is run:
.\Autologon.exe guest10 test.com Password1
Error2: Nothing happens
Execution 3:
As administrator in powershell the following is run:
$obj=.\Autologon.exe
$name ="guest10"
$domain="test"
$pass="Password1"
& $obj $name $domain $pass
Error3:
The expression after '&' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object.
I generally use Start-Process with the ArgumentList parameter to run programs with arguments:
$autologon = "C:\folder\Autologon.exe"
$username = "guest10"
$domain = "domain"
$password = "Password1"
Start-Process $autologon -ArgumentList $username,$domain,$password
Or you can put them directly into the command:
Start-Process "C:\folder\Autologon.exe" -ArgumentList "guest10","domain","Password1"
This worked for me:
Start-Process -FilePath $exePath -ArgumentList "/accepteula", $user, $domain, $password -Wait
It's very picky about quote placement.

Starting Powershell elevated from PSExec (enable-psremoting)

I'm trying to enable-psremoting with PSexec on my servers with the following command:
psexec.exe \\server cmd /c "echo . | powershell (-verb runas -argumentlist (enable-psremoting -force))"
but it doesn't work. I'm guessing I'm messing up my double quotes. Any help?
Sune:)
Thanks for commenting all! I found out how to do it, and this is the completed code:
$user = "youruser"
$p = Read-Host "Enter domain password for $adminuser"
cls
$expression1 = "enable-psremoting -force"
$commandBytes1 = [System.Text.Encoding]::Unicode.GetBytes($expression1)
$encodedCommand1 = [Convert]::ToBase64String($commandBytes1)
$expression2 = "Set-ExecutionPolicy remotesigned -Force”
$commandBytes2 = [System.Text.Encoding]::Unicode.GetBytes($expression2)
$encodedCommand2 = [Convert]::ToBase64String($commandBytes2)
$expression3 = "Restart-Service winrm”
$commandBytes3 = [System.Text.Encoding]::Unicode.GetBytes($expression3)
$encodedCommand3 = [Convert]::ToBase64String($commandBytes3)
foreach ($server in (get-content c:\temp\enablepsremotinglist.txt))
{
echo " "
echo "Running on $server"
echo "--------------------------------------- "
echo " "
psexec.exe \\$server -h -u no\$user -p $p cmd /c "echo . | powershell -EncodedCommand $encodedCommand1"
psexec.exe \\$server -h -u no\$user -p $p cmd /c "echo . | powershell -EncodedCommand $encodedCommand2"
psexec.exe \\$server -h -u no\$user -p $p cmd /c "echo . | powershell -EncodedCommand $encodedCommand3"
}
I hope this can be of help to someone else one day:)
PS: Please keep in mind that this send your adminpassword as clear text..
It looks like you are trying to invoke PowerShell to run elevated. This might not be possible to do remotely... I was able to get this to work against a machine without UAC enabled (2003 server):
$c = Get-Credential
$u = $c.UserName
$p = $c.GetNetworkCredential().Password
$path = "C:\SysinternalsSuite"
& "$path\psexec.exe" \\server -u $u -p $p powershell.exe -Command "Enable-PSRemoting -Force"
For some reason though I had to press enter a couple times on the shell for it to keep spitting out output and eventually return me to a prompt. Not sure what's up with that...
You don't need PSExec for that. Check this script by PowerShell developer Lee.
http://poshcode.org/2141

Output ssh command to text file in powershell

I am trying to output the following command to a text file in powershell, but I cannot seem to get it working:
ssh -v git#git.assembla.com | Out-File C:\output.txt
As stated in the post below with using native apps, you could try using Start-Process, e.g.
Start-Process ssh "-v git#git.assembla.com" -NoNewWindow -RedirectStandardOutput stdOut.log -RedirectStandardError stdErr.log; gc *.log; rm *.log
Working on the same problem I made a detail post on my blog How to SSH from Powershell Using Putty\Plink but the short version is this bit of code. But sure you try it after installing putty.
Function Invoke-SSHCommands {
Param($Hostname,$Username,$Password, $CommandArray, $PlinkAndPath, $ConnectOnceToAcceptHostKey = $true)
$Target = $Username + '#' + $Hostname
$plinkoptions = "-ssh $Target -pw $Password"
#Build ssh Commands
$remoteCommand = ""
$CommandArray | % {$remoteCommand += [string]::Format('{0}; ', $_) }
#plist prompts to accept client host key. This section will login and accept the host key then logout.
if($ConnectOnceToAcceptHostKey)
{
$PlinkCommand = [string]::Format('echo y | & "{0}" {1} exit', $PlinkAndPath, $plinkoptions )
#Write-Host $PlinkCommand
$msg = Invoke-Expression $PlinkCommand
}
#format plist command
$PlinkCommand = [string]::Format('& "{0}" {1} "{2}"', $PlinkAndPath, $plinkoptions , $remoteCommand)
#ready to run the following command
#Write-Host $PlinkCommand
$msg = Invoke-Expression $PlinkCommand
$msg
}
$PlinkAndPath = "C:\Program Files (x86)\PuTTY\plink.exe"
$Username = "remoteshell"
$Password = "pa$$w0rd"
$Hostname = "Linuxhost"
$Commands = #()
$Commands += "ls"
$Commands += "whoami"
Invoke-SSHCommands -User $Username -Hostname $Hostname -Password $Password -PlinkAndPath $PlinkAndPath -CommandArray $Commands

PSExec never completes when run inside start-job

I'm trying to execute a cmd file on a list of 48 computers. I don't want to execute and wait for completion sequentially because each cmd takes about 10 minutes to complete. WinRM isn't an option. Neither is WMI. PSExec is an option....but I can't seem to make it work inside of Start-Job.
I'm doing something like:
$sb = {
param
(
$computer = "serverw01",
$userid = "domain2\serviceid",
$password = 'servicepw',
$command = "cd /d d:\ && updateAll.cmd"
)
d:\eps\pstools\PsExec.exe -u $userid -p $password "\\$($computer)" cmd /c $command
}
foreach ($computer in Get-Content "D:\Data\serverlist.txt") {
Start-Job $sb -ArgumentList $computer
}
This creates a bunch of jobs....but the never complete and if I Receive-Job on any of them i get back
PS> get-job | receive-job -Keep
+ CategoryInfo : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
PsExec v1.98 - Execute processes remotely
Copyright (C) 2001-2010 Mark Russinovich
Sysinternals - www.sysinternals.com
it executes just fine if I run the function like:
& $sb -computer "serverw01"
Initiating script is run in Powershell v2.0 on Server 2008r2 box
I've tried it on a box in domain2 while logged in with a domain admin userid (same result).
Try this for the psexec command, ensuring you include "-d" to not wait for response, and put the computer variable right after psexec:
d:\eps\pstools\psexec "\\$($computer)" /accepteula -u $userid -p $password -d cmd /c $command
This hanging issue occurs on Win2003 and Win2008 servers.
Most people solve this issue with a workaround like echoing and piping so that powershell gets some input from STDIN.
But there exists a solution within powershell. Just start powershell with the option -inputformat none like:
powershell -inputformat none -command ...
please try the -accepteula parameter to psexec
like
d:\eps\pstools\PsExec.exe -accepteula -u $userid -p $password
from
$computerList = Get-Content "D:\Data\serverlist.txt"
$sb =
{
param($name)
}
$computer = $name
$userid = "domain2\serviceid"
$password = 'servicepw'
$command = "cd /d d:\ && updateAll.cmd"
d:\eps\pstools\PsExec.exe -u $userid -p $password \\$computer cmd /c $command
{
}
foreach ($computer in $computerLinst) {
Start-Job $sb -ArgumentList $computer
}