Running process under another user in Windows - windows

I am trying to launch a process in Windows under specific user account.
While launching process with ProcessStartInfo works locally and when you have the active interactive session. It's not working in remote scenario where the active session is not present.
On Remote machine, Service ABC is running under admin account (domain\adminuser), which is launching the powershell.exe under same admin account to launch the script and drive the flow.
In the script, I am tried to launch process [non-interactive], but failed to launch the same.
$Processinfo = New-Object System.Diagnostics.ProcessStartInfo
$Processinfo.UseShellExecute = $false
$Processinfo.LoadUserProfile = $false
$Processinfo.CreateNoWindow = $true
$Processinfo.Username = "domain\user"
$Processinfo.PasswordInClearText = "testpass"
$Processinfo.FileName = "abc.exe"
I don't see a reason why I am not allowed to launch non-interactive process from Session 0

To run locally, you can simply use Start-Process
$Credentials = Get-Credentials
Start-Process -Credential $Credentials -FilePath 'C:\Windows\notepad.exe'
For Remote Machine you can use WMI Create using the -List Parameter:
(Get-WmiObject win32_process -ComputerName $computer -Credential $Credentials -List).Create("notepad")

Related

"Activate" Local user just after creating it with powershell

Hello when I create a user in powershell with New-LocalUser, I was wondering if there was a way to "activate" that user without connecting to it.
by "activate" I mean being able to make Windows create the users directories,registry keys, and all without manually disconnecting the current user and connecting to the newly created user.
Thank you.
Just run any process as that new user.
Here is something that will start a powershell prompt as the new user and close it.
This will create the user profile folder without disconnecting you from the current session.
# Name credentials
$username = 'NewUsername'
$password = 'NewProfilePassword' | ConvertTo-SecureString -AsPlainText -Force
$credential = [PSCredential]::New($username,$password)
Start-Process powershell.exe -Credential $Credential -ArgumentList "-Command","Write-host 'Hello Profile'"

Retrieving Windows Defender Status remotely

I am using the following script to retrieve Windows Defender status remotely.
$password = ConvertTo-SecureString “myPassword” -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential (“myUserNamer”, $password)
$sessionOption = New-CimSessionOption -Protocol WsMan
$session = New-CIMSession -ComputerName myMachineName -Credential $credentials -SessionOption
Get-MpPreference -CimSession $session
However, I am quite new to PowerShell scripting and related protocols. Is this the best way of retrieving this information when I may have to run it over hundreds of computers?
Does it need to be for all the machines or selected ones?
For example:
You could run a remote session on the machine you need and then run the command.
Enter-PSSession [VMname]
Get-MpComputerStatus
Replace [VMname] with the name of the VM/Computer you're looking for.
Enter-PSSession Computer-01
Get-MpComputerStatus
If that's what you're looking for.

PSExec on Windows Server Startup Script

I'm programatically launching a Google Cloud Compute Instance running Windows Server 2016 with a start up script.
The executable in the start up script requires to be launched as a specific user, so I'm trying to launch it with psexec to simulate said user:
C:/psexec.exe \\\\WIN-SERVER-2016 -u WIN-SERVER-2016\\customuser -p custompassword -accepteula -w "c:/app" cmd /c node index.js
c:/app/index.js contains a simple hello world, which should write to a file.
If I log in as any user and launch this exact command from cmd, the file is written. Launching from the startup script (supplied as windows-startup-script-cmd in the Google Cloud Compute Engine Instance) results in no file written.
What could be the solution? Is there a more efficient way to execute a start-up script as a specific user?
Looking at the concern , I would not recommend you to use PSEXEC .
NOrmally, we use PSExec in order to invoke a GUI in the remote system which PS doesn't support by native.
In your case, I would suggest you to run using the Invoke-Command
Something like this:
$username = 'WIN-SERVER-2016\customuser'
$password = "custompassword"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$Script_block = {cmd /c node index.js}
Invoke-Command -ComputerName WIN-SERVER-2016 -Credential $cred -ScriptBlock $Script_block
This should also take it from the Metadata key if you are using windows-startup-script-cmd
Note: I have not considered the accepteula -w "c:/app" part. Please incorporate the placeholders accordingly.
Hope it helps...!!!

Runas in another Windows terminal session

For simplicity, let's say the user Administrator is logged in in terminal session 2. Another user Boda is logged in terminal session 3.
Is it possible to runas a program in session 3 from session 2?
For simplicity, let's say I want to start calc.exe in session 3 (in Boda's session). How do I do that? Can it be done with runas?
Like Harry Johnston suggested in a comment you can do this using the psexec tool available on TechNet. I've tried it using a Windows 2008 Server running Terminal Services and managed to start various applications in another users session (although not calc.exe - it started but minimized and the window refused to restore), among them cmd.exe.
The command I used was psexec.exe -i 3 cmd.exe where 3 is the session number (that you can get from qwinsta.exe).
Example: Remote session, logged on as Administrator; using qwinsta to enumerate sessions and psexec to start cmd.exe on another session.
Another session: logged on as Patrick, with the cmd.exe window on the desktop opened by Administrator (which the window title reveals too).
There is a commandline tool and it’s called RunInSession. You need to specify at least the SessionId in which you want to launch the process and which process you want to launch. Optional is servername if you want to launch on a remote server. If you run it without parameters a dialog with possible parameters is shown:
Currently supported OS versions are Windows XP, 2003, Vista and 2008.
The program needs to run in the context of the Localsystem user, therefore it temporarily installs itself as service and start itself. With the WTSQueryUserToken it obtains the Primary User token of the requested Terminal Session. Finally the process is launched with CreateProcessAsUser and the service deletes itself.
More details:
How to launch a process in a Terminal Session
Launching an interactive process from Windows Service in Windows Vista and later
Its kind of an hack, but its very useful to me. Way more faster than psexec.exe in my environment.
Just create a temporary task in a remote computer, for a specific user or group, run it, than delete the task.
I created a powershell script for it:
param (
[string]$Computer = ($env:computername),
[string]$User = "",
[string]$Command,
[string]$Args
)
$script_task =
{
param (
[string]$User = "",
[string]$Command,
[string]$Args
)
#Action
$Action = New-ScheduledTaskAction –Execute $Command
if($Args.Length > 0) { $Action = New-ScheduledTaskAction –Execute $Command -Argument $Args}
#Principal
$P = New-ScheduledTaskPrincipal -UserId $User -LogonType Interactive -ErrorAction Ignore
#Settings
$S = New-ScheduledTaskSettingsSet -MultipleInstances Parallel -Hidden
#Create TEMPTASK
$TASK = New-ScheduledTask -Action $Action -Settings $S -Principal $P
#Unregister old TEMPTASK
Unregister-ScheduledTask -TaskName 'TEMPTASK' -ErrorAction Ignore -Confirm:$false
#Register TEMPTASK
Register-ScheduledTask -InputObject $TASK -TaskPath '\KD\' -TaskName 'TEMPTASK'
#Execute TEMPTASK
Get-ScheduledTask -TaskName 'TEMPTASK' -TaskPath '\KD\' | Start-ScheduledTask
#Unregister TEMPTASK
Unregister-ScheduledTask -TaskName 'TEMPTASK' -ErrorAction Ignore -Confirm:$false
}
#The scriptblock get the same parameters of the .ps1
Invoke-Command -ComputerName $Computer -ScriptBlock $script_task -ArgumentList $User, $Command, $Args
Usage example:
file.ps1 -User USER_NAME -Command notepad.exe -Computer REMOTE_COMPUTER
I don't know of any way you can control another open cmd session. However, you should be able to use runas to run it as another user.
This can be archived using Sysinternals tools from Microsoft. Beside running lists of commands and scripts remotely, they are useful for lot of things. As admin they had been my savior on multiple occasions.
#To run a command on single computer remotly
psexec \\RemoteComputerName Path_Of_Executable_On_Remote_Computer Argument_list
#To run a command on list of computers remotely.
psexec #Remote_Computer_list Path_Of_Executable_On_Remote_Computer Argument_list /AcceptEULA
#To run list of commands on list of remote computer. make sure you copy batch file before you run command below.
psexec #Remote_Computer_List Path_Of_Batch_On_Remote_Computer Argument_list

How to start a program in another Windows Terminal session? (as an Administrator) [duplicate]

For simplicity, let's say the user Administrator is logged in in terminal session 2. Another user Boda is logged in terminal session 3.
Is it possible to runas a program in session 3 from session 2?
For simplicity, let's say I want to start calc.exe in session 3 (in Boda's session). How do I do that? Can it be done with runas?
Like Harry Johnston suggested in a comment you can do this using the psexec tool available on TechNet. I've tried it using a Windows 2008 Server running Terminal Services and managed to start various applications in another users session (although not calc.exe - it started but minimized and the window refused to restore), among them cmd.exe.
The command I used was psexec.exe -i 3 cmd.exe where 3 is the session number (that you can get from qwinsta.exe).
Example: Remote session, logged on as Administrator; using qwinsta to enumerate sessions and psexec to start cmd.exe on another session.
Another session: logged on as Patrick, with the cmd.exe window on the desktop opened by Administrator (which the window title reveals too).
There is a commandline tool and it’s called RunInSession. You need to specify at least the SessionId in which you want to launch the process and which process you want to launch. Optional is servername if you want to launch on a remote server. If you run it without parameters a dialog with possible parameters is shown:
Currently supported OS versions are Windows XP, 2003, Vista and 2008.
The program needs to run in the context of the Localsystem user, therefore it temporarily installs itself as service and start itself. With the WTSQueryUserToken it obtains the Primary User token of the requested Terminal Session. Finally the process is launched with CreateProcessAsUser and the service deletes itself.
More details:
How to launch a process in a Terminal Session
Launching an interactive process from Windows Service in Windows Vista and later
Its kind of an hack, but its very useful to me. Way more faster than psexec.exe in my environment.
Just create a temporary task in a remote computer, for a specific user or group, run it, than delete the task.
I created a powershell script for it:
param (
[string]$Computer = ($env:computername),
[string]$User = "",
[string]$Command,
[string]$Args
)
$script_task =
{
param (
[string]$User = "",
[string]$Command,
[string]$Args
)
#Action
$Action = New-ScheduledTaskAction –Execute $Command
if($Args.Length > 0) { $Action = New-ScheduledTaskAction –Execute $Command -Argument $Args}
#Principal
$P = New-ScheduledTaskPrincipal -UserId $User -LogonType Interactive -ErrorAction Ignore
#Settings
$S = New-ScheduledTaskSettingsSet -MultipleInstances Parallel -Hidden
#Create TEMPTASK
$TASK = New-ScheduledTask -Action $Action -Settings $S -Principal $P
#Unregister old TEMPTASK
Unregister-ScheduledTask -TaskName 'TEMPTASK' -ErrorAction Ignore -Confirm:$false
#Register TEMPTASK
Register-ScheduledTask -InputObject $TASK -TaskPath '\KD\' -TaskName 'TEMPTASK'
#Execute TEMPTASK
Get-ScheduledTask -TaskName 'TEMPTASK' -TaskPath '\KD\' | Start-ScheduledTask
#Unregister TEMPTASK
Unregister-ScheduledTask -TaskName 'TEMPTASK' -ErrorAction Ignore -Confirm:$false
}
#The scriptblock get the same parameters of the .ps1
Invoke-Command -ComputerName $Computer -ScriptBlock $script_task -ArgumentList $User, $Command, $Args
Usage example:
file.ps1 -User USER_NAME -Command notepad.exe -Computer REMOTE_COMPUTER
I don't know of any way you can control another open cmd session. However, you should be able to use runas to run it as another user.
This can be archived using Sysinternals tools from Microsoft. Beside running lists of commands and scripts remotely, they are useful for lot of things. As admin they had been my savior on multiple occasions.
#To run a command on single computer remotly
psexec \\RemoteComputerName Path_Of_Executable_On_Remote_Computer Argument_list
#To run a command on list of computers remotely.
psexec #Remote_Computer_list Path_Of_Executable_On_Remote_Computer Argument_list /AcceptEULA
#To run list of commands on list of remote computer. make sure you copy batch file before you run command below.
psexec #Remote_Computer_List Path_Of_Batch_On_Remote_Computer Argument_list

Resources