Access is denied to localhost despite being administrator - PowerShell - windows

Okay, so this has been bugging me for a while and I have tried too many things now.
I'm trying to run a PowerShell script - my user account is a regular one on the domain, it is however local administrator on my computer. Therefore I've created a PowerShell script prompting me for credentials (where I type the credentials of my domain administrator account) to be used to invoke another script which needs this domain administrator elevation.
This script looks like this:
Invoke-Command -FilePath "C:\Temp\script.ps1" -ComputerName localhost -Credential Get-Credential
Here the script.ps1 is the script which needs domain administrator elevation.
Executing the shown script results in a prompt for credential and then the following error:
[localhost] Connecting to remote server localhost failed with the following error message : Access is denied.
I've tried messing around with a .bat file looking like this:
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%script.ps1 PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";
aswell, but I can't make it work - it is not elevating the script to domain administrator level.
Lastly however, I need to mention that the script I want to run with domain elevation works if I open PowerShell with the domain administrator elevation, navigates to C:\Temp\script.ps1 and executes it by .\script.ps1.
Any suggestions?

One topic that helped me (I had a similar case) was the section "HOW TO ENABLE REMOTING FOR NON-ADMINISTRATIVE USERS" in About Remote Troubleshooting. Basically, it tells you to execute a PS Command: Set-PSSessionConfiguration Microsoft.PowerShell -ShowSecurityDescriptorUI and grant execution permission to the user that you are trying to use it.

If you have local administrative rights, run powershell as administrator and run Invoke-Command without the -Credential flag.
If you're only running the script locally, you don't need Invoke-Command. You're better off just running the script and passing arguments to it.

Enable PSRemoting Service to Start Automatic
on both host and remote machines
Set-Service winrm -StartupType Automatic
Start-Service winrm
Enable PSREmoting
On both host and remote machines
EnablePSRemoting -Force
Add computers to Trusted Hosts
On Remote machine
Set-Item wsman:\localhost\Client\TrustedHosts -Value "$(hostname),*$((Get-WmiObject Win32_ComputerSystem).Domain)"
Enable Multi Hopping in Powershell Remoting
Identify which hosts to allow passing of Creds
Enable-WSManCredSSP –Role Client –DelegateComputer "$(hostname),*$((Get-WmiObject Win32_ComputerSystem).Domain)"
On the source machine.
Enable-WSManCredSSP –Role Server
You must specify Authentication and a Credential
on Host Machine
$Cred = [System.Management.Automation.PSCredential]::new("<username>",$("<Password>" | ConvertTo-SecureString -AsPlainText -Force))
invoke-command -ComputerName localhost -ScriptBlock {Write-Host $args[0]} -ArgumentList "Hello!, It Works" -Authentication Credssp -Credential $cred
REFERENCE
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting?view=powershell-6

Well, you are doing it wrong if I understand it correctly.
Credential you provided is used to access localhost (which you don't need BTW). Script is still executed unelevated. There are two solutions:
You need to elevate the powershell itself and execute the script.
You need to change the script so that it itself accepts Credential parameter and use it to access things. There isn't much more I can say about it until you show the script.
You can elevate shell with:
start powershell -verb Runas
The problem here is that unless you disable UAC, it will prompt you. Unfortunately there is no easy way around this that I know. One sure way is to add the script to task scheduler and set the task to run elevated, then run it and delete the task. All of this can be automated ofc. This is a consequence of unfortunate design of UAC system (sudo on Linux that serves the same purpose will cache the response for some time so that subsequent commands do not prompt). This would go something like:
schtasks /Create /TN runner ... /TR powershell -File script.ps1 /RU username /RP password /RL HIGHEST
schtasks /run runner
schtasks /delete runner

Related

Using a remote Powershell Session to change a service username/password

I have a list of servers, and then another list of services on each of those servers. I am trying to remove it, change a few values in the .bat and then install the services again. Right now I have started a remote Powershell Session using
$PSsession = New-PSSession -ComputerName $server -Credential $Credential
Enter-PSSession -Session $PSsession
I have been mainly using the Invoke-Command -ScriptBlock {//somecodehere} -Session $PSsession in order to run each of the commands that I have used so far. My initial approach was to use sc.exe config $serviceName obj=$username password=$passwd, but each time I make the change on the remote server, it tells me that there is a NativeCommandError and that there is a logon issue with the service.
Is there a way that I can use the credentials provided by the user in order to change the username/password of a service in a secure way? Or does anyone have any recommendations on a better approach I could research?
So my solution to my own problem was to create a script and copy it over to the server. Then it ran the sc.exe command inside of the machine itself. Since it is another machine, you can't send the credentials through as variables if they are a SecureString. So my solution is just to create those variables normally and then make sure to delete them afterwards.
If you are working with confidential data, don't forget that you usually need to overwrite the variable 3 times before deleting it.

Ansible error - credssp: The server did not respond with pubKeyAuth info

When running an Ansible script against a Windows server, I get the following error message.
credssp: The server did not respond with pubKeyAuth info auth was rejected
What is the cause of this.
I'm answering this question for myself because the solution was trivial to implement, but took some time to work out.
I was creating new EC2 instances with the following userdata which prepared the system as per the docs at http://docs.ansible.com/ansible/latest/intro_windows.html, and set the Administrator password.
<powershell>
Enable-WSManCredSSP -Role Server -Force
Set-Item -Path "WSMan:\localhost\Service\Auth\CredSSP" -Value $true
Invoke-Expression ((New-Object System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1'))
$user=[adsi]"WinNT://localhost/Administrator,user"
$user.SetPassword("{{win_initial_password}}")
$user.SetInfo()
</powershell>
My Ansible script was waiting for a response on port 5986 (WinRM) before continuing, under the assumption that once this port responds the instance would be accessible.
What I believe was happening was that the Administrator password was not being set by the time port 5986 was responding.
To fix this I set the Administrator credentials as the first step in the userdata script, and added a pause for good measure.
<powershell>
$user=[adsi]"WinNT://localhost/Administrator,user"
$user.SetPassword("{{win_initial_password}}")
$user.SetInfo()
Enable-WSManCredSSP -Role Server -Force
Set-Item -Path "WSMan:\localhost\Service\Auth\CredSSP" -Value $true
Invoke-Expression ((New-Object System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1'))
</powershell>
After these two changes, my script worked as expected. So if you get that error message, check the username and password are valid.

Multiple logins to windows server in jmeter

I just want to know whether there is a way to login windows server (OS Process Sampler) in the same test plan as we can do for Unix servers (SSH command).
In SSH command it is asking for username and password to login the UNIX box, but it is not there in OS Process sampler.
I just want to check logs in different Windows Server but I need to have only one .jmx file. This will be a central one and it should not be installed in any of the Windows Server where I check logs.
Thanks in advance.
Microsoft Powershell has ability of executing remote commands, you just need to enable this mode, see Enable and Use Remote Commands in Windows PowerShell for details.
Once done you should be able to execute commands on remote Windows machines like:
powershell.exe $password = ConvertTo-SecureString -String YOUR_PASSWORD -AsPlainText -Force; $credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "YOUR_USERNAME",$password; Invoke-Command -Computer REMOTE_MACHINE -cred $credentials -scriptBlock {YOUR_COMMAND}
Replace:
YOUR_USERNAME with Windows username
YOUR_PASSWORD with Windows password
REMOTE_MACHINE with hostname or IP address of the remote machine
YOUR_COMMAND with Powershell script you want to execute
More information: How to Run External Commands and Programs Locally and Remotely from JMeter

Add user access to a shared folder in remote computer

My objective is to add users to a shared folder in the remote server. I know that netshare command can be used to add users to local folder.
net share PathName=D:/Projects /GRANT:XXXX,FULL
When i run the above command in the local machine, it works fine.
Since the shared folder is present in remote server, i tried wmic and the psExec options. But both did not work. Not sure what i am missing here
wmic /node:ComputerName process call create "cmd.exe net share PathName=D:/Projects /GRANT:XXXX,FULL"
and
psExec \\ComputerName cmd.exe "net share PathName=D:/Projects /GRANT:XXXX,FULL"
Assuming you're running Windows 8 (Server 2012) or newer, use the Grant-SmbShareAccess cmdlet and a remote CIM session:
$RemoteSession = New-CimSession -ComputerName RemoteComputerName
Grant-SmbShareAccess -Name ShareName -AccountName XXXX -AccessRights Full -CimSession $RemoteSession
On Windows 7, you can use Invoke-Command to run the net share command on the remote machine:
$RemoteSession = New-PSSession -ComputerName RemoteComputerName
Invoke-Command -Session $RemoteSession -ScriptBlock { net share PathName=D:/Projects /GRANT:XXXX,FULL }

How can I copy a file between two remote computers and run an install, then repeat for 50 LAN

I'm new to programming and am trying to write a powershell script.
I'm in a windows domain environment with over 50 remote offices. Each office has 4 computers. One computer, "Computer A," has dropbox installed that we use for backups, and now software updates. I want to execute a script from my local machine that copies a folder (~1 GB) to the other computers in that LAN, and runs the setup.exe file in the directory to update software on these computers.
As far as I can tell in order to use the Enter-pssession cmdlet & run a copy-item and start process, I have to:
On remote machine enable winrm by: enable-psremoting -force
On remote machine enable CredSSP authentication by: enable-smancredssp -role server -force
On local machine enable CredSSP authentication by: enable-SmanCredSSP -role
client -force
From here I can enter the Power shell session and begin the copy and install. Here is the code I'm running:
#Allow my computer to send credentials to remote computers
Enable-WSManCredSSP -Role Client -DelegateComputer * -Force
$credential = Get-Credential -Credential domain\user
#Getting Content
$path = "C:\computernames.csv"
Import-Csv -path $path |
foreach-object {
$computername = $_.Name
if (Test-Connection -cn $_.Name -quiet) {
#copy the batch file that allows remote powershell access
$source = "c:\"
$destination = "\\$computername\c$\install files\remoteaccess"
robocopy $source $destination
#open file to allow remote PS access
& psexec \\$computername -a runas -u domain\user -p password -c -f -h "\\$computername\c$\install files\remoteaccess\remoteaccess.bat"
#Initiates Power Shell session with remote computer
Enter-PSSession -cn $_.Name -Credential $credential -Authentication Credssp
#begin copy
#be sure to refine destination
copy-item -path $_.Source -Destination $_.Destination -force -verbose -recurse | out-file c:\copylog.txt
#begin silent install
#code here
#stop wsmancredssp accep
disable-wsmancredssp -role server
#close pssession
exit-pssession
} else {
"$computername is not online"
}
}
Disable-wsmancredssp -role client
The computernames.csv has the headers: Name, Source, Destination with UNC directories for each LAN's computer with dropbox and where to copy the file.
The "remoteaccess.bat" file contains the following two lines of code:
powershell.exe enable-psremoting -force >>c:\remotelog.txt
powershell.exe Enable-WSManCredSSP -role Server -force >>c:\remotelog.txt
The powershell window freezes after initiating the psexec session with the remote computer and sends the first powershell command to enable remoting. No error is generated, or input requested. The output of this command is saved in the remotelog text file:
"WinRM has been updated to receive requests.
WinRM service started.
WinRM already is set up for remote management on this machine."
It appears the powershell command to enable wsmancredssp is never received. When I run the batch file on the remote computer from remote access software, both commands execute and are logged successfully. Where is my psexec command going wrong, or how can I setup these computers to allow remote sessions with a remote command without using GPO?

Resources