Executing CMD command remotely - powershell

I need to execute some commands remotely on computers and receive back input, to prevent calling every user and remote desktop to use CMD.
What I need to do:
Run CMD as admin, and run the two lines below and review the results. (On 30+ computers)
cd "c:\Program Files\Tenable\Nessus Agent"
nessuscli agent status --local
I tried:
wmic /node:COMPUTERNAME process call create "cmd.exe /c start"
It worked on my computer, but I think it opened the command prompt on the other persons computer when I tried this.
winrs -r:COMPUTERNAME CMD
WINRM apparently isn't enabled and I don't want to enable it if it's not already enabled.
$PC = (Read-Host "Enter Computer Name").ToUpper()
$PC cmd.exe --% /k cd "c:\Program Files\Tenable\Nessus Agent" & nessuscli agent status --local
write-host -f WHITE "Operation Complete."
I couldn't figure out how to make it work with a Powershell script in ISE.
I was able to run the below one from Powershell x86 as admin on my computer, but not sure how I would replicate to run it on an external computer.
cmd.exe --% /k cd "c:\Program Files\Tenable\Nessus Agent"
nessuscli agent status
EDIT
I created a .bat file and was able to launch it as admin, but it still requires input from the user to accept the cmd runas admin. Then I cannot see the results of the CMD on my end.
$PC = (Read-Host "Enter Computer Name").ToUpper()
#Change $xWare to your folder
[string]$RemoteStagingPath = '\\' + $PC + '\C$\Intel'
$xWare = "C:\Users\NAME\Desktop\"
$password= convertto-securestring $passwordTextBox.Text -asplaintext –force
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $userTextBox.Text,$password
$script = "C:\intel\cmd.bat"
#Runs Nessus
CP $xWare\cmd.bat $RemoteStagingPath
Start-Process powershell -Credential $credential -ArgumentList "-noprofile -command &{Start-Process $script -verb runas}"
write-host -f WHITE "Operation Complete."

Related

Invoke-AzVMRunCommand and Start-Process under specific user on remote VM using Azure Runbook

I need to run Start-Process on a remote VM with specific user account using Azure Powershell Runbook
function Install-Postgres {
$username = "aact-import-vm1\aact-importer"
$password = "ChangeMe!"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList `
#($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
write-output $cred
# run pg installer
Start-Process "C:\Program Files\WindowsPowerShell\Modules\Install-Postgres\postgresql.exe" -ArgumentList `
"--mode unattended", "--unattendedmodeui none",`
"--prefix `"C:\Program Files\PostgreSQL\10`"", "--datadir `"C:\Program Files\PostgreSQL\10\data`"",
"--superpassword `"ChangeMe!`"",`
"--servicename `"postgres`"", "--serviceaccount `"postgres`"", "--servicepassword `"ChangeMe!`""`
-Wait -Credential $cred;
}
$script = Get-Content Function:\Install-Postgres
Out-File -FilePath Install.ps1 -InputObject $script
#Note that the -ScriptPath should not point to the remote path(in remote vm), it should point to the local path where you execute the command Invoke-AzureRmVMRunCommand
$output = Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -Name $vmName -CommandId 'RunPowerShellScript' -ScriptPath Install.ps1
write-output $output.Value
#after execution, you can remove the file
Remove-Item -Path Install.ps1
The script above produces the following error:
Start-Process : This command cannot be run due to the error: Access is denied.
If I run the script above without specific credentials the postgres installer produces this error in the log:
Executing icacls "C:\Windows\Temp/postgresql_installer_1ef9b3f2c6" /T /Q /grant "WORKGROUP\aact-import-vm1$:(OI)(CI)F"
Script exit code: 1332
Script output:
Successfully processed 0 files; Failed processing 1 files
Script stderr:
WORKGROUP\aact-import-vm1**$**: No mapping between account names and security IDs was done.
Please notice that there is symbol $ instead of user name.
However, if I run it on the VM it works fine and produces this line in the log:
Executing icacls "C:\Users\aact-importer\AppData\Local\Temp\2/postgresql_installer_2662c862ff" /T /Q /grant "aact-import-vm1\aact-importer:(OI)(CI)F"
Script exit code: 0
As far as I can see, If I run runbook script remotely without credentials it runs under NTAUTHORITY\SYSTEM that's why there is symbol $ instead of user name in the postgres installer log. If I run it locally it uses proper user and everything works fine.
The question is: how can I specify a user account to run Start-Process on the remote VM?
Same question on msdn https://social.msdn.microsoft.com/Forums/en-US/a7fa0ca8-5cba-42bb-8076-9a8d4a654beb/invokeazvmruncommand-and-startprocess-under-specific-user-on-remote-vm-using-azure-runbook?forum=azureautomation#a7fa0ca8-5cba-42bb-8076-9a8d4a654beb
For those who are interested:
After investigation with MS support they confirmed that runbook (not hybrid) always runs under NTAUTHORITY\SYSTEM

Unable to install program in self extracting cabinet using Invoke-Command

I'm writing a script to set up a test SharePoint server for trusted (AD FS) authentication on a stamped test environment that consists of a SharePoint server (server 2016) and a domain controller (server 2008R2). I'm writing the script to run on the SharePoint server and use a remote session to configure the DC because the DC only has PowerShell 2.0 which is missing some convenient functionality.
I have a specific segment of the script that runs a script block on the DC which downloads the AD FS 2.0 installer, a self extracting cabinet, and tries to install it. Every line of the block executes except for the actual installation. If I log onto the machine and run those same lines it works perfectly.
Invoke-Command -Session $domainControllerSession -ScriptBlock {
$installerUrl = "https://download.microsoft.com/download/F/3/D/F3D66A7E-C974-4A60-B7A5-382A61EB7BC6/RTW/W2K8R2/amd64/AdfsSetup.exe"
$filename = "$($PWD.Path)\AdfsSetup.exe"
$wc = New-Object System.Net.WebClient
$wc.DownloadFile($installerUrl, $filename)
Start-Process -FilePath $filename -ArgumentList "/quiet" -Wait
}
I tried manually extracting the contents (using /x:) and then executing the setup file but there was no change in result (Note: The files are extracted but the extractor process never exits, this doesn't seem pertinent to the problem). I also moved to the DC and created a session to localhost and got the same exact behavior.
PS C:\Users\Administrator> $session = New-PSSession -ComputerName Localhost
PS C:\Users\Administrator> Invoke-Command -Session $session -ScriptBlock {
>> $filename = "$($PWD.Path)\AdfsSetup.exe"
>> write-host $filename
>> Test-Path -Path $filename
>> Start-Process -FilePath $filename -ArgumentList "/quiet" -Wait
>> Test-Path -Path 'C:\Program Files\Active Directory Federation Services 2.0'
>> }
>>
C:\Users\Administrator\Documents\AdfsSetup.exe
True
False
PS C:\Users\Administrator>
Update 1
I ran the process with the /Logfile parameter and confirmed that the installation is failing due to an access denied error. I've also confirmed that, as expected, the remote session is running under the same administrator account that I am using to initiate the session. I am assuming that the missing ingredient here is that the remote session is not running in an elevated shell. However, I can't seem to get that working either.
Invoke-Command -Session $session -ScriptBlock {
Start-Process PowerShell -Verb RunAs -ArgumentList "& C:\Users\Administrator\Documents\AdfsSetup.exe /quiet /Logfile C:\Users\Administrator\Documents\AdfsSetup.log" -Wait -PassThru
}
The error is the same.

Elevated PS script in Jenkins

I have been trying to run a script from a Windows Jenkins (slave) server. The script is written in PowerShell and requires elevated privileges (such as if one right-clicked on PS and selected run-as-administrator).
Jenkins launches its scripts the following way:
powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\JOHAN.DER\AppData\Local\Temp\2\hudson9084956499652818911.ps1'"
My script fails because it requires elevated privileges. How can I spawn a new elevated-privileged PS process (that does not require clicking because Jenkins can't do that) that could run my script?
Cheers!
The snippet below checks if current process is elevated and if not, it spawns a new, privileged process. It is little tricky to get output of the child powershell process, so I'm using transcript command to capture it. Below you can find my pipeline definition step:
powershell """
cd "${env.WORKSPACE}"
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
echo "* Respawning PowerShell child process with elevated privileges"
\$pinfo = New-Object System.Diagnostics.ProcessStartInfo
\$pinfo.FileName = "powershell"
\$pinfo.Arguments = "& '" + \$myinvocation.mycommand.definition + "'"
\$pinfo.Verb = "RunAs"
\$pinfo.RedirectStandardError = \$false
\$pinfo.RedirectStandardOutput = \$false
\$pinfo.UseShellExecute = \$true
\$p = New-Object System.Diagnostics.Process
\$p.StartInfo = \$pinfo
\$p.Start() | Out-Null
\$p.WaitForExit()
echo "* Child process finished"
type "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
Remove-Item "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
Exit \$p.ExitCode
} Else {
echo "Child process starting with admin privileges"
Start-Transcript -Path "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
}
# put rest of your script here, it will get executed
# with elevated privileges.
"""
Even though this is an old thread, I still provide my methods here since I had the same problem, hoping to help anyone who is finding the answer.
First of all, This problem is not relevant to Jenkins, it's Windows's issue, you have to enable build-in Administrator to get an elevated privilege, here is the reference:
Administrator user
It is an unelevated administrator account
that is created by default during the installation of Windows. If an
administrator user tries to do something that requires elevated rights
(ex: run as administrator), Windows will display a UAC prompt for the
administrator user to approve before allowing the action.
Built-in "Administrator"
The hidden built-in elevated
"Administrator account" is a local account that has full
unrestricted access rights to the PC. By default, this "Administrator"
account will not be prompted by UAC.
After enabling build-in Administrator, you have two ways to elevate PS script which is triggered by Jenkins:
1.Login Windows with build-in Administrator:
This is the easiest way to achieve your goal, just log in with build-in Administrator, and everything are elevated, including the PS script triggered by Jenkins. (I am using this method.)
2.Pass credential and run as Administrator:
Add some codes in your PS script
$user = "Administrator"
$passwd = "password"
$securePasswd = ConvertTo-SecureString $passwd -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $user, $securePasswd
#Use Credential to prevent from being prompted for password
#Use argument -Verb RunAs to get script elevated
Start-Process powershell.exe -Credential $credential -ArgumentList "Start-Process powershell.exe -Verb RunAs -ArgumentList '-File hudson.ps1' -Wait"
Try this :
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"

How to prompt to run EXE as different user in powershell

How would I go about running an EXE as a different user? How could I prompt for credentials or atleast ask for the password for a local admin to launch an exe through powershell. I'm having a hard time getting the runas command to work.
This was the latest thing I tried:
runas -credential .\me c:\windows\system32\notepad.exe
This works in the powershell terminal:
runas /user:asdf c:\windows\system32\notepad.exe but doesn't ask for credentials in a standalone powershell script.
This is a simple operation.
Start-Process "c:\windows\system32\notepad.exe" -Credential $(Get-Credential)
Using Get-Credential will prompt the user for credentials, You can also store it in a variable.
$Creds = Get-Credential
Start-Process "c:\windows\system32\notepad.exe" -Credential $Creds
Try following
Start-Process notepad.exe -Verb RunAsUser
change directory to .exe directory and run below command
runas /netonly /user:<domain\username> .\<app name>

psexec powershell output

I try remote execute powershell script like this:
psexec -i \\host -u user -p pass PowerShell C:\tst\tst.ps1
Source code for tst.ps1:
$TempLogFilePath = "$(Get-Date -u "%Y-%m-%d")-LogFileEventLog.log"
Start-Transcript -Path "$TempLogFilePath" -Append
echo (Get-Date –f o)
Stop-Transcript
Exit 0
When a run command to remote execute this script, script locate on remote machine, in local machine in output nothing. Command running in cmd.exe. How i can get output to local console?
PsExec.exe \\host -u domain\user -p pass cmd /c "echo . | %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe C:\WINDOWS\system32\Hello.ps1"
This construction help you to run remote powershell script, but script should be locate on remote computer.
and second construction
Param(
[alias("sp")]
[string]$script_path,
[alias("u")]
[string]$user_name,
[alias("p")]
[string]$password,
[alias("h")]
[string]$host_name
)
$pass = convertto-securestring $password -asplaintext -force
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user_name,$pass
invoke-command -credential $mycred -computername $host_name -filepath $script_path
but i don't know how i can pass args string for execute remote script with param