Running an installer from a windows share using ansible - windows

I want to log into a Windows server using a local user, then map a network drive using an Active Directory user and run an installer from it automated with Ansible.
I followed the suggestion from this question to create a PowerShell script and do the mount and the install. I used that script as follows:
Inventory:
[winserver]
windows
[winserver:vars]
ansible_user="local_user"
ansible_password="P#ssw0rd"
ansible_connection="winrm"
ansible_winrm_cert_validation=ignore
win_user="domain\aduser"
win_pass="P#55w0rd"
task yaml:
---
- name: Mount and run a script
script: 'files/maprun.ps1 -map_user {{ win_user }} -map_password {{ win_pass }} -script z:\ascript.ps1'
And the maprun.ps1 script contains the following:
param(
$map_user,
$map_password,
$script
)
$PWord="$map_password"|ConvertTo-SecureString -AsPlainText -Force
$myCreds=New-Object System.Management.Automation.PsCredential($map_user,$PWord)
New-PSDrive -Name "Z" -PSProvider "FileSystem" -Root "\\domain\share" -Credential $myCreds
echo Invoke-Command -ScriptBlock $script
And I get the error:
New-PSDrive: A specified logon session does not exist. It may already have
been terminated
Most hits talk about a double-hop problem, but I am trying to specify different credentials in the remote script, so this isn't a double hop problem. The other answer suggests this ought to be possible. The script works in interactive mode, so it is something to do with being in batch mode. Any ideas how I can get this to work?
I am using Ansible 2.3.1.0 on Red Hat Enterprise Linux. Windows is Windows Server 2012 R2. Scripts were manually typed, sorry for any typos.

I can make a few suggestions.
As you've written it, the script "maprun.ps1" must be saved in the "files" directory of your Linux controller machine. If it is, the "maprun.ps1" script will be copied by Ansible to the remote host, executed and deleted. If "maprun.ps1" is going to call "ascript.ps1" you need to copy "ascript.ps1" over to the remote host before calling "maprun.ps1" and have it's location defined in the context of "maprun.ps1".
You don't need parameter names before the args in your playbook "script:" command.
Args internal to your Ansible playbook need double curly brackets and quotes around them.
As an alternative to connecting to the network drive with the New-PSDrive command you could try the "net use" command as shown below.
So instead of
script: 'files/maprun.ps1 -map_user {{ win_user }} -map_password {{ win_pass }} -script z:\ascript.ps1'
Try
script: files/maprun.ps1 "Z:" "{{ win_user }}" "{{ win_pass }}" "z:\ascript.ps1"
Where maprun.ps1 contains the following...
# connect to a shared resource and run script
param(
[string]$map_server,
[string]$map_user,
[string]$map_password,
[string]$script
)
# connect to the network drive
net use $map_server $map_password /USER:$map_user
Invoke-Item (start powershell ((Split-Path $MyInvocation.InvocationName) + $script))
net use $uncServer /delete

Related

Access Windows FileShare for all users in EC2 instance setup using userdata

We have an EC2 instance with a Files Share. Until now we could access it via UNC like so \\files.server.com.
Now we've started using packer and Ansible to setup our servers in deployment. After sysprep all the credentials get deleted and we need to create the access once again using the UserData script.
One more thing we need to give this access to all of our users because we have special user for our Windows service.
I have tried many things and still no luck, from New-PSDrive, NET USE,MapNetworkDrive, CredentialsManager and so on.
I would appreciate some assistance with this.
I do something similar, but I use the commands: section of a configSet within CloudFormation:
commands:
10-Create-Local-Fileshare-Directory:
command: >-
powershell.exe -Command New-Item "D:\Shared" -type directory
waitAfterCompletion: '0'
11-Create-Fileshare:
command: >-
powershell.exe -Command New-SmbShare -Name my-fileshare -Path "D:\Shared"
waitAfterCompletion: '0'
12-Grant-Fileshare-Permissions:
command: >-
powershell.exe -Command Grant-SmbShareAccess -Name my-fileshare -AccountName Everyone -AccessRight Change -Force
waitAfterCompletion: '0'
You could do the same if you're using CloudFormation or just pull out the Powershell commands you need.

Trigger powershell script remotely in an admin prompt mode

I'm trying to update the JVM Heap Size from Powershell by running this PS Script. It works on the local machine and persists as an env variable:
test.ps1
& cmd /c 'SETX _JAVA_OPTIONS "-Xms256m -Xmx256m"' | Write-Host
But when triggering this same test.ps1 script from a Remote Machine (through Nagios NRPE), the value of this env variable does not update though a success message is returned to the remote machine.
If running the Powershell command for setting the env variable (in a non-admin console), like below:
[Environment]::SetEnvironmentVariable("Test3", "test string", "Machine")
I'm getting this error:
Exception calling "SetEnvironmentVariable" with "3" argument(s): "Requested registry access is not allowed."
So how to trigger this PowerShell script remotely in an admin prompt mode?
You likely need to start the service that is running NRPE (NSClient++?) with an elevated account.

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

Accessing SMB share from Windows when using Powershell

I'm trying to build a custom VeeamZip backup script using PowerShell from a Windows 7 box. The box doesn't have the space requirements to hold the actual data itself, it's just the catalyst to manage the VeeamZip files.
I've been hunting around and found a solution here on SO to work around the fact that the PS-Drive command doesn't function using the -Credentials flag in PowerShell 2.0 using this snippet:
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\share\point", $false, "user", "pass")
I can verify this is properly mounting the share and is searchable using Powershell, but when using the VeeamZip Powershell commands, the path U:\ isn't available.
I tried then using the net use command in Powershell which also mounted the volume, but even with /persistent:yes it won't show in Explorer and the backups fail.
What can I do? There has to be option to get this to work. I'm a Linux guy so I'm not powershell wiz.
EDIT: I've now updated to Powershell 3.0 and I still can't get it work...
I'm trying the following snippet, but only Powershell has access the new drive:
$credential = Get-Credential
New-PSDrive -Name V -PSProvider FileSystem -Root \\server\share -Credential $credential -Persist
EDIT: The New-PSDrive function now works to mount the volume in Explorer and can be browsed as expected as long as I don't launch PowerShell as administrator. The dilemma is now that I can't use the VeeamZip tool because it requires Admin to function. Ideas welcome.

Access is denied to localhost despite being administrator - PowerShell

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

Resources