How to execute a powershell command as user XYZ? - powershell

I am trying to execute a PowerShell script on a salt-minion windows server from a salt master Linux server.
I am sending the command like this:
salt My-server cmd.run "C:\Users\XYZ\Desktop\my_script.ps1" shell=powershell
This works but I need to execute this script as a specific user.
I have tried all of the following:
salt My-server cmd.run "start powershell -credential "XYZ" C:\Users\XYZ\Desktop\my_script.ps1"
salt My-server cmd.run "runas/user:XYZ "powershell.exe C:\Users\XYZ\Desktop\my_script.ps1"
salt My-server cmd.run "runas/user:XYZ C:\Users\XYZ\Desktop\my_script.ps1" shell=powershell
But all of them either fail to run the script or don't have the desired effect.
I don't know much about PowerShell but I know how to do the same in Linux bash:
su -c "C:\Users\XYZ\Desktop\my_script.ps1" XYZ
I am aware that's not a valid Linux path but you see the point.

Have you tried using the runas option for cmd.run? Such as:
salt My-server cmd.run "C:\Users\XYZ\Desktop\my_script.ps1" runas=XYZ shell=powershell
The documentation seems to imply that password= argument may be required, too:
runas (str) -- Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running on
a Windows minion you must also use the password argument, and the target
user account must be in the Administrators group.
Documentation references:
https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.cmdmod.html#salt.modules.cmdmod.powershell (for cmd.run with the runas option via execution module, with shell=powershell, which also includes the added information around needing password= against Windows minions)
https://docs.saltstack.com/en/latest/ref/states/all/salt.states.cmd.html#salt.states.cmd.run (for cmd.run with the runas option in states)

Related

The system cannot find the file specified- Task Scheduler

I have batch script file, which should encrypt a file with pgp. I have defined a task in task scheduler to do this, but I am keep receiving the error"The system cannot find the file specified".
Interestingly, when I run the same line of script in my powershell , the encrypted file is successfully generated.
I was wondering if anyone knows what can possibly be wrong here?
I tried to give the full path in my batch script , and also added the pass in start in part, when defining the action.
the batch scrip code is here::
rem #echo off
#set path=c:\test;%path%
#set d=%date:~-4,4%%date:~4,2%%date:~-7,2%
#set d=%d: =_%
#set t=%time:~0,2%%time:~3,2%%time:~6,2% #set t=%t: =0%
Rem Generate PGP encrypted file
#echo Starting PGP... >> c:\apps\ftpLogs\test.log
gpg2 --batch --yes -r testkey --output c:\test\foo\test_20150505.pgp --encrypt c:\test\foo\test_20150505.txt >> c:\apps\ftpLogs\test.log
and the script that I ran in my powershell, which works fine, is this line:
gpg2 --batch --yes -r testkey --output c:\test\foo\test_20150505.pgp --encrypt c:\test\foo\test_20150505.txt >> c:\apps\ftpLogs\test.log
Finally I was able to resolve the issue. The problem was with the user authority. The batch script was suppose to encrypt a file and then ftp the encrypted file to the vendor's ftp server.
Apparently in Windows Server 2012 , the ADMINISTRATORS have the permission to create a file (here the encrypted file) while this user does not have the permission to send it. and SYSTEM user has the permission to send but not to create. (Both of them had this authority back in Win Server 2012).
So what did I do at the end, was to make two different batch script tasks and schedule them with 10 mins time distance. The first one was running the above code with ADMINISTRATOR privileges and the second one was sending it out with SYSTEMS.
If your batch file doesn't work, but the PowerShell script does, just run the PowerShell script from your scheduled task instead.
From the Scheduled Task, instead of entering the path to your batch file specify PowerShell.exe (or more likely C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe). Then in the Arguments box specify your parameters. You probably want to hide the window, so we'll include that in the arguments, and for this you can probably skip loading a profile, so we'll add that too. Then just use the -Command parameter to specify your code that you have in the question.
So your Program to run box should show:
C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe
Then the box that says "Add Arguments (optional)" should have:
-NoProfile -WindowStyle Hidden -command "gpg2 --batch --yes -r testkey --output c:\test\foo\test_$((get-date).ToString(yyyyMMdd)).pgp --encrypt c:\test\foo\test_$((get-date).ToString(yyyyMMdd)).txt >> c:\apps\ftpLogs\test.log"
On a side note, should that be gpg2 or pgp2? I just copied your command, but it seemed odd to me that they would name it like that.

Noninteractive Remote Commands with Powershell

I am developing a script which uses ssh to connect to a windows host, run a powershell command, and parse the output. While I can connect to the host and run the command, powershell will not exit and return control back to the local script until I press the enter key.
At the moment, the specific command being run is ssh HOSTNAME 'echo $(hostname)' and the ssh server is configured to pass remote execution requests to powershell -noninteractive -command CMD, where HOSTNAME is the name of the windows host and CMD is the remote command to be run (in this case echo $(hostname)).
The end goal is to have the script which is calling remote powershell commands to run completely noninteractively, but this is currently impossible as the powershell command will not run noninteractively.
How do I get powershell to run remote commands noninteractively?
I've resolved the issue. While I haven't determined what was causing the issue, I can at least overcome the issue at hand by redirecting stdin to /dev/null on the side that initiates the ssh connection.
$ ssh HOSTNAME "CMD" </dev/null
This solution doesn't involve powershell at all, but rather treats the symptoms from the other side of the connection.

Command line : make a program run as admin when double click

In Windows 7, I have an executable A.exe. I want that when the user launches it (by double click), it prompts for administrator privileges. I know it can be done graphically by selecting "Run this program as an administrator" then pressing "Change settings for all users" in the properties dialog, like this :
But I need a command line that does exactly the same thing. How to achieve that ?
EDIT : I don't want to run A.exe as admin from the command line. For now A.exe doesn't prompt for admin privileges during launch. I want a batch program B.bat such that when I launch B.bat, it will change this behavior of A.exe. So after successful execution of B.bat, when any user launches A.exe by double click (not from command line), it prompts for admin privileges. B.bat doesn't execute A.exe, it only changes this "setting" of A.exe. I now it's not so easy to understand ...
You can use from runas.exe in CMD
>runas.exe
RUNAS USAGE:
RUNAS [ [/noprofile | /profile] [/env] [/savecred | /netonly] ]
/user:<UserName> program
RUNAS [ [/noprofile | /profile] [/env] [/savecred] ]
/smartcard [/user:<UserName>] program
RUNAS /trustlevel:<TrustLevel> program
/noprofile specifies that the user's profile should not be loaded.
This causes the application to load more quickly, but
can cause some applications to malfunction.
/profile specifies that the user's profile should be loaded.
This is the default.
/env to use current environment instead of user's.
/netonly use if the credentials specified are for remote
access only.
/savecred to use credentials previously saved by the user.
/smartcard use if the credentials are to be supplied from a
smartcard.
/user <UserName> should be in form USER#DOMAIN or DOMAIN\USER
/showtrustlevels displays the trust levels that can be used as arguments
to /trustlevel.
/trustlevel <Level> should be one of levels enumerated
in /showtrustlevels.
program command line for EXE. See below for examples
Examples:
> runas /noprofile /user:mymachine\administrator cmd
> runas /profile /env /user:mydomain\admin "mmc %windir%\system32\dsa.msc"
> runas /env /user:user#domain.microsoft.com "notepad \"my file.txt\""
NOTE: Enter user's password only when prompted.
NOTE: /profile is not compatible with /netonly.
NOTE: /savecred is not compatible with /smartcard.
Found a solution ! The key is to embed a manifest file to the exe.

net use with /savecred is not working in PowerShell remote

I am trying to permanently map a drive on XP computer (has instaled PS V2) over a PowerShell Remote session with a admin privileges.
I tried this advice: Net.exe use 'Error: A command was used with conflicting switches.' while using /savecred
[zikaz-7]: PS C:\Users\administrator\Documents> net use V: \\CNBS-Test\Storage
/savecred /P:yes
and I get this error instead of being asked for username and pass:
The password is invalid for \CNBS-Test\Storage.Enter the user name for
'CNBS-Test': net.exe....The operation was canceled by the user.
and when I try like this:
[zikaz-7]: PS C:\Users\administrator\Documents> net use V: \\CNBS-Test\storage
/persistent:yes /savecred /user:domain2003\admistrator admin123
I get "A command was used with conflicting switches" error becouse of /user and /savecred.
I can map whitout /savecred but it only last until reboot.
I tried bouth of them without /persisten but get the same resoult, and I looked on every forum I could fined and everywhere they said one of those two examples.
How do I solve this problem, am I writeing something wrong in the first example or that can not work over PS remote session? Or do I have to import -credential and then /savecred on that, or something like that?
It sounds like a variation on the double-hop problem - From computer A, you remotely execute something on computer B, which tries to access computer C.
You can get around this by using Cred-SSP; special steps may be required on the XP machine.

PSEXEC, access denied errors

While I'm using PSEXEC.exe getting 'Access denied' error for remote systems.
Any idea about how to solve this?
Hi i am placing here a summary from many sources online for various solutions to "access is denied" :
most information can be found here (including requirements needed) - sysinternal help
as someone mentioned add this reg key, and then restart the computer :
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system
/v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
Read this knowledge base article to learn what this does and why it is
needed
Disable firewall (note - this will leave you with out any firewall
protection)
netsh advfirewall set allprofiles state off
if target user has a blank PW and you dont want to add one, run on target:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
"LimitBlankPasswordUse"=dword:00000000
This didnt work for me, but i have read it did for others in a few places,
on target execute:
Start -> Run -> secpol.msc -> Local Policies -> Security Options -> Network Access: Sharing > and security model for local accounts > Classic – local users authenticate as themselves
if already in 'Classic':
move to "Guest only - .." run from elevated command prompt gpupdate \force
move back to 'Classic - .." again run from elevated command prompt gpupdate \force
This one solved my issue:
run on target from elevated command prompt "net use" look at ouput chart and for shares listed in remote column there (i only deleted the disconnected ones - you can try them all) run "net use [remote path from before list] /delete" then run 'net use \target\Admin$ /user:[user name]' enter prompt password request (if empty PW just press enter), viola should work.
I just solved an identical symptom, by creating the registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system\LocalAccountTokenFilterPolicy and setting it to 1. More details are available here.
This helped in my case:
cmdkey.exe /add:<targetname> /user:<username> /pass:<password>
psexec.exe \\<targetname> <remote_command>
PsExec has whatever access rights its launcher has. It runs under regular Windows access control. This means whoever launched PsExec (be it either you, the scheduler, a service etc.) does not have sufficient rights on the target machine, or the target machine is not configured correctly. The first things to do are:
Make sure the launcher of PsExec is familiar to the target machine, either via the domain or by having the same user and password defined locally on both machines.
Use command line arguments to specify a user that is known to the target machine (-u user -p password)
If this did not solve your problem, make sure the target machine meets the minimum requirements, specified here.
You can try the command
net use \\computername\ipc$ /user:adminname password
to get admin permissions on remote PC before use psexec.
I had the same problem. And after a hard work, I found a easy and full solution:
I use runas to run the script in a admin account
I use the -s parameter in psExec to run in a system account
Inside the PsExec, I login again with a admin account
You can use & to run multiples commands
Remember to replace [USERNAME], [PASSWORD], [COMPUTERNAME], [COMMAND1] and [COMMAND2] with the real values
The code looks like this:
runas /user:[USERNAME] "psexec -e -h -s -u [USERNAME] -p [PASSWORD] \\[COMPUTERNAME] cmd /C [COMMAND1] & [COMMAND2]"
If you whant to debug your script in the another machine, run the following template:
runas /user:[USERNAME] "psexec -i -e -h -s -u [USERNAME] -p [PASSWORD] \\[COMPUTERNAME] cmd /C [COMMAND1] & [COMMAND2] & pause"
Try setting this key on the target (remote) machine, and restart the machine:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]
"LocalAccountTokenFilterPolicy"=dword:00000001
See: http://forum.sysinternals.com/topic10924.html and http://www.brandonmartinez.com/2013/04/24/resolve-access-is-denied-using-psexec-with-a-local-admin-account/
I just added "-с" parameter. It makes Psexec copy executable to remote machine. So it works without access errors.
I found Sophos kept placing psexec.exe into the Quarantine section. Once I authorized it, it ran fine.
I still use psexec, even on win 10. Replace the psexec.exe in the Windows 10's win32 folder with the older version to work -> I use version 2.11.0.0. The Windows 10 version I was using would only run .bat files as background/hidden process on the remote computer. Took a whole day to figure this out.
Adding the registry key from above to the remote computer helps as well:
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
I found another reason PSEXEC (and other PS tools) fail - If something (...say, a virus or trojan) hides the Windows folder and/or its files, then PSEXEC will fail with an "Access is Denied" error, PSLIST will give the error "Processor performance object not found on " and you'll be left in the dark as to the reason.
You can RDP in; You can access the admin$ share; You can view the drive contents remotely, etc. etc., but there's no indication that file(s) or folder(s) being hidden is the reason.
I'll be posting this information on several pages that i was perusing yesterday while trying to determine the cause of this odd problem, so you might see this elsewhere verbatim - just thought I'd put the word out before anyone else pulled their hair out by the roots trying to understand why the performance counter has anything to do with PSEXEC running.
I had a case where AV was quarantining Psexec - had to disable On-access scanning
For anybody who may stumble upon this. There is a recent (Dec 2013) Security Update from Microsoft Windows on Windows 7 that is preventing remote execution.
See http://support.microsoft.com/kb/2893294/en-us
I uninstalled the Security Update by going to Control Panel\Programs\Programs and Features\Installed Updates
It worked right after that.
The following worked, but only after I upgraded PSEXEC to 2.1 from Microsoft.
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]
"LocalAccountTokenFilterPolicy"=dword:00000001 See:
http://forum.sysinternals.com/topic10924.html
I had a slightly older version that didn't work. I used it to do some USMT work via Dell kace, worked a treat :)
On Windows Server 2012 R2 I had trouble to run from user account
psexec -u administrator -p password \\machinename -h -s -d -accepteula cmd.exe
But it works fine if you run without parameters -h -s. That's why I use this to solve my trouble:
psexec -accepteula -u administrator -p password \\machinename %PathToLocalUtils%\psexec.exe -h -s -d cmd.exe
I couldn't get access to remote machines unless I had UAC disabled.
That has to be done locally, either from control panel or running the following through cmd:
reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
While UAC is enabled, make sure you run cmd as administrator.
For a different command I decided to change the network from public to work.
After trying to use the psexec command again it worked again.
So to get psexec to work try to change your network type from public to work or home.
I tried a lot of way but I could not use psexec. It gives "Access denied". After I change the target user account type from Standard to Admin, I connected the machine via psexec.
I researched the reason why admin type account is required then I found this answer.
You can change target machine user account this way: Control Panel -> User Accounts -> Change Account Type. You must enter an admin account and password to change that account if you logged in standard account.
After that I logged in with this command: psexec \\remotepcname -u remoteusername -p remotepassword cmd
Tried all suggestions above, but still was unable to resolve the error. Finally once I made the below change, I could successfully run the PSexec command.
Turns out that when you have UAC enabled psexec does not work as supposed. We need to set HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA to 0 then psexec starts working as expected.