Powershell and Jenkins - Execute Powershell Script as another user - powershell

I have an environment formed by a Jenkins Server, a couple of Jenkins Slaves (windows) and several remote windows computers all part of the same domain.
I need to run a jenkins job, which executes a powershell snippet consisted of several functions (part of a custom modules loaded on the Jenkins Slave) against other windows remote computers in the same domain (which do not have the modules installed).
These modules needs to run under a specific domain account with permissions to access the remote computers.
If I logon with on any of the jenkins slave (with that specific domain account) everything works fine.
By default, Jenkins executes the job on the slave using the NT authority\system account which, of course, returns me denied access errors.
Question: is there a way to tell Jenkins to execute the Job on the windows slave with another specific Domain Account and not the NT Authority\System one?
Tried already:
Invoke-command using credentials: this is not an option since the remote computers do not have the modules
Impersonation: tried a couple of functions found on the PS gallery but do not work

You can run powershell as a process in a script and call that from Jenkins. In the script also you can use like:
$username = 'username'
$password = 'password'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username,$securePassword
Start-Process Powershell.exe -Credential $credential
Hope it helps.

Related

Looking to map an Azure Fileshare as a mapped network drive on an Azure Windows VM via another machine/Custom Script Execution

I'm attempting to provision a Windows VM and I need to map some Azure fileshares to drives for the VM user that will be interacting with the VM.
I've been trying to make "az vm extension set"/Custom Script Execution work for me by calling some PowerShell scripts to setup the mapping to the fileshare, but since the process runs as NT AUTHORITY\SYSTEM, the mappings aren't working, obviously. I've tried to switch user contexts in my scripts via having an intermediate script that changes context to my VM user and then calling another script that does the work, but that doesn't seem to be working.
$scriptFile = $args[0]
$username = $args[1]
$password = $args[2]
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username,
$securePassword
Start-Process Powershell.exe -Credential $credential $scriptFile
Unfortunately it seems nothing gets run in the $scriptFile that I call, and I can't get any errors out of standard out/err, so I'm at a loss as to how this can be done.
Certainly someone out there has had to run scripts as another user via the Custom Script Execution method before, I'm hoping they happen to read this post.
Is there a way to set what user the Custom Script Execution runs as?
No, there is no way of setting a user under which script extension runs.
You also should use -PassThru and -Wait and\or -RedirectStandardError\-RedirectStandardInput to your command invocation. Also, add -ErrorAction Stop to your commands to propagate errors.

How do I execute a powershell script under a specified credential without a prompt?

I'm writing an 'Action Script' in VMWare AppDirector 'AppD' which installs MS Dynamics. (My action script is actually a powershell script). The way this works is that AppD will execute a powershell script on a newly deployed server, using a builtin administrator account. This script is one of the last steps in a highly orchestrated deployment. At this stage my SQL server has been deployed, the databases loaded, and I'm performing the final deployment.
When I run my script logged in as myself, everything works great. But of course that's executing under 'mydomain\myusername' which has access to the SQL server etc. However, when AppD executes this script under a local builtin account, it doesn't have the credentials needed by setup to authenticate against SQL, and make proper connections for install to succeed.
My first attempt was to just call a script, that invokes my actual deployment script, so I can pass credentials;
$user = "mydomain\myusername"
$pword = ConvertTo-SecureString -String "mypassword" -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $pword
Invoke-Command -FilePath "C:\Scripts\DeployAOS.ps1" -Credential $credential -Computer localhost
This looked like it might have worked, but when reviewing the install log I see the following error;
2015-03-09 13:15:19Z Property DbSqlServer set to: 'SQLSERVER001'
2015-03-09 13:15:23Z Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
My original DeployAOS.ps1 script contains this line, which kicks off the install;
# Perform AOS Installation
Start-Process -FilePath $exeAOSSetup -ArgumentList $cfgAOS -Wait
I have also tried just modifying my DeployAOS.ps1 to set the 'System.Management.Automation.PSCredential' object w\ Username\Password, and doing something like this;
# Perform AOS Installation
Start-Process -FilePath $exeAOSSetup -ArgumentList $cfgAOS -Credential $credentials -Wait
And it really didn't like that. It feels like the AOS setup needs to be executed under a domain user, that has access to the SQL server, and maybe even have a user profile loaded while setup runs (So it can create a desktop shortcut, etc.)
Any ideas how I might go about solving this problem? I'm fairly new to scripting in powershell, so any help would be appreciated.

Execute PowerShell remotely from TeamCity build using current agent credentials

TeamCity executes builds using the build agents. The build agent I have is an agent on Windows that is running as a service under domain credentials.
I need to Invoke-Command on a remote web server in one of my build steps.
When I do this (lot's of stuff removed for simplicities sake):
$password = ConvertTo-SecureString "actualpasswordhere" -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PsCredential("domain\teamcityagent1",$password)
...
Invoke-Command -computername $IISComputerName -Credential $credentials -ScriptBlock ${function:BackupSite} -ArgumentList $IISSiteName, $IISBackupDirectory
It works. But when I provide credentials for currently executing user like this:
$credentials = [System.Net.NetworkCredential]::DefaultCredentials
(surrounding code is the same)
I get the internal waiting and not execution at the point of Invoke-Command. I haven't waited too long, but nothing happens even in 5 minutes.
I would like not to have to provide login and password explicitly in the script, since the credentials are basically for the same user that the build agent is running under. How can I work around the need to provide the login and password in script code?
I did two things and it worked:
Unchecked -NoProfile argument in PowerShell runner parameters. (Didn't help alone)
Removed -Credentail parameter from Invoke-Command.
This executed my code as current user - service user.

Linux executes a command on a remote Windows server without SSH/Telnet

I am building a Jenkins server. One of the deployment steps is to execute a command on the production server to download the UAT-tested artifacts to the required folders. Jenkins is running on CentOS Linux while the production server is running Windows 2008 R2.
However, my client does not want to install any software into the production server, therefore executing commands via SSH is not possible. The client had an unpleasant experience with using Telnet before. It is an insecure service which has already been disabled on the server.
Other than using SSH and Telnet, are there other ways to execute a command on a remote machine? I was thinking of creating a task that is triggered by a specific event, but how to raise the event on the server remotely seems not an easy job.
I can think of four different solutions:
Have a network share on the production machine that your Jenkins server can put a trigger file into. Have a scheduled task that checks for that file and triggers the download.
Have a scheduled task on the production machine poll the Jenkins server for new files. Powershell can be used to query the Jenkins REST api.
If the production machine has IIS, get Jenkins to trigger an asp.net script, do a form POST to a cgi script, or upload a trigger file. curl and wget on CentOS will help there.
As a last resort, add another windows machine into the mix. Install SSH onto it. Use SSH from Jenkins to the new machine, then powershell from the new machine to the production machine.
If you decide on step 4, I use Power Shell to run commands on a remote machine.
PS2.0 is installed on Windows 2008 R2 by default.
Here is an example of how I do it.
$username = 'user'
$password = 'password'
$appHost = 'hostname'
$dest = 'C:\Unpack\'
$archive = "C:\Releases\new release.7z"
$securePass = ConvertTo-SecureString -AsPlainText $password -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$securePass
"Create PowerShell Session"
$appSession = New-PSSession -ComputerName $appHost -Credential $cred -Authentication CredSSP
invoke-command -session $appSession -scriptblock { param($dest,$archive) & 'C:\Program Files (x86)\7-Zip\7z.exe' x -bd -aoa """-oc:\$dest""" """c:\$dest\$archive"""} -args $dest,$archive
$remotelastexitcode = invoke-command -session $appSession -ScriptBlock { $lastexitcode }
if ( $remotelastexitcode -ne 0 )
{
"Archive Extraction Failed. Is a file locked or open?"
exit -1
}

Executing a remote SSIS package via Powershell

I'm a Powershell newbie and am trying to use this article to create a way for another user to kick off an SSIS package on a remote server.
The Powershell code I'm using is:
$pass = convertto-securestring "myPassword" -asplaintext -force
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "myUsername",$pass
invoke-command -computername myServer -scriptblock { dtexec.exe /File "d:\myPath.dtsx" } -credential $mycred
Even though I've tried passing my credentials in Powershell, the SSIS package doesn't seem to be executing with them and is executing as an Anonymous user. The package is failing validation for a number of reasons -
The package can not connect to a remote file that requires permission to access (I have permission but the Anonymous User does not). The user that I would like to have run this script does have permission to the folder.
The SQL Server login is failing. I tried forcing a SQL user in the connection details of the package but that doesn't seem to have worked.
Can I use change the Powershell code to use Windows Authentication? How do I execute the SSIS package using those permissions?
you need to enable CredSSP first (see this), and use invoke-command -Authentication Credssp