Access is denied prompted while windows sc command calling from jenkins groovy - jenkins

I am trying to create CI/CD pipeline using jenkins and my environment devops/deployment is windows servers 2016.
Pipeline script written in apache groovy. Which call batch file for deploy the code, that batch script is doing 2 tasks.
deploy code on another host machine (using robocopy command)
start w3svc service (using sc command).
Both command are mentioned in batch file which is call through groovy script with simple 'bat batchfilelocation /name.bat'. here is batch script:
#echo [off]
net use "\\<servername>\<shareddirectory>" <password> /user:<domain\user> /persistent:no
robocopy "C:\jenkins\AngularPipeline\dist\<project>" \\$<Dir>eddistinationServer>\<shar /E /PURGE
sc \\$servername start w3svc
echo on
echo close batch script!
For sc command execuation it is giving below error:
C:\jenkins\AngularPipeline>sc \ start w3svc [SC]
StartService: OpenService FAILED 5:
Access is denied.
This script is working well while I directly called it through command prompt(non administrator). access denied only comes while this script run under the jenkins groovy.
I have checked below possibilities :
WMI permission on source and target machine
//Confirm that WinRM is properly configured. c:>Winrm quickconfig
//Make sure that the remote server allows commands from any machine. PS c:>Set-item wsman:localhost\client\trustedhosts -value *
Restart Windows Remote management service restarted on both machines
C:\Windows\system32>sc \ sdshow w3svc
D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)
Please suggest how to resolve the same.

Recommended Approach:
If you are not running this Jenkins job on an another agent then you could re-configure your Jenkins service to use local administrator account. To do so follow below steps
Open Start Menu
Search 'Services'
Find "Jenkins" service
Right click on Jenkins service
Open Properties
Click on "Log on" tab
Select "This Account"
Browse for local system admin account and select it
Add Password and confirm password for same id
click OK
Restart/Start Jenkins Service
Second Approach:
Create a bat file on the server/workstation where Jenkins is installed
Create a shortcut of the file
Right click on Shortcut and go to 'properties'
Click on 'Comp'
check the check box next to "Run as administrator"
Click OK and Then
Click Apply Now, Go to Control Panel -> System and Security ->
Action Center -> Change User Account Control Settings
Set the level to "never notify" Run that bat shortcut using Jenkins job
In this case the job will marked as failed but the script will get executed.

Related

Jenkins user gets "Permission denied" at deploying

Deploying a PDF documentation Jenkins executes a simple batch file:
#echo off
REM
REM Adapt the filepath as needed
REM
set PDF_OUTPUT_DIR="F:\svnWorkingCopy\kostra\trunk\DITA\__out_pdf"
set PDF_DEPLOY_DIR="\\FILE-SRV01\Austausch\Setup_Masterbuild\KOSTRA_AKVS\Deutsch\KostraAKVS"
del %PDF_DEPLOY_DIR%\KostraUserManual.pdf /F /Q
copy %PDF_OUTPUT_DIR%\kostra.pdf %PDF_DEPLOY_DIR%\KostraUserManual.pdf /Y
It quits with permission denied. End of console output (in German) is:
[kostra] $ cmd /c call C:\Windows\TEMP\jenkins1093559218605334188.bat
F:\svnWorkingCopy\kostra>F:\svnWorkingCopy\kostra\trunk\DITA\kostra-pdf-deploy.bat
Zugriff verweigert
0 Datei(en) kopiert.
Build step 'Windows Batch-Datei ausführen' marked build as failure
Archiviere Artefakte
Discard old builds...
#111 is removed because old than numToKeep
Sending e-mails to: fjk#akgsoftware.de
Finished: FAILURE
The Jenkins user is the user logged on that machine (Win Server 2012 r2) and has all Jenkins rights.
If I open CMD and execute the batch file manually, everything goes OK. Any idea why Jenkins refuses to copy the file? Is there a way to get a more detailed error msg. from Jenkins?
I see you are running Jenkins on windows. First check that if the user that started Jenkins is allowed to write on your directory. If that is not the case restart Jenkins with a user allowed to write in that directory.
Found the solution for my environment (Jenkins as Windows Service):
The default system user assigned to the Jenkins service must be changed to the logged on windows user.
Even after doing so Jenkins as a service doesn't know about mapped network drives, so you must change these to UNC paths if you have to deploy to a local network share.

How to run a VSTS build or release Task under another user and not the Build service account?

I'm setting up a build and release pipeline and part of the requirement is for some Powershell and Batch commands to be run on the target server(s).
In most cases, all build and release definitions are run by our dedicated Build service account which usually is sufficient, however in this particular case, the Batch command should be run on the target server(s) by another service account or user with the required privileges on the server(s).
Unfortunately, our dedicated Build service account does not have the required privileges for the target server(s), as they are restricted environments and there are no plans for those restrictions to be removed.
Likewise, only a limited number of service accounts have the privileges to perform the desired tasks on the target server(s), but neither of these has the privileges to run build tasks and there are no plans to change this.
My challenge therefore is to run the build/release definitions under the build service account as usual, however for the specific Batch command operations, those tasks should be run by the target server(s) designated service accounts. How can I achieve this?
We can not change the build service account during the build or release process.
However you can try below ways to run the Batch commands with other account on target server(s):
If you can convert the Batch commands to a PowerShell script, then
you can use the task Deploy: PowerShell on Target Machines
directly to run the PowerShell script on the target machines with the
specific credential.
You can also try creating a PowerShell script (See below sample) to call the cmd.exe to run the batch script with the specific credential. Then Add a Utility: PowerShell task to run the script.
Param(
[string]$computerName = "v-tinmo-12r2",
)
$Username = "username"
$Password = ConvertTo-SecureString "pasword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($Username,$password)
Invoke-Command -ComputerName $computerName -Credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'C:\Scripts\Test.bat'"}
Please note that for both of them you have to copy the batch script or PowerShell script which you want to be ran to the target server(s) first.

How to start Owasp zap server(exe or jar) from jenkins

Actually, the main issue is if I start the server then my next commond will never trigger as it always running as zap server in listening mode.
Can I run two command line in Jenkins. I have added 2 "Execute Windows batch command" still nothing works. I have added the image in same thread
I have tried by creating a batch file
cd /
cd C:\Program Files\OWASP\Zed Attack Proxy
start java -jar zap-2.6.0.jar
I am getting error as below after using above batch file
Process leaked file descriptors. See https://jenkins.io/redirect/troubleshooting/process-leaked-file-descriptors for more information
https://wiki.jenkins.io/display/JENKINS/Spawning+processes+from+build
I have also use command line arugument directly in "Execute window batch command" like:-
java -jar zap-2.6.0.jar
But the UI of zap is not starting
I have also tried "Windows Exe Runner Plugin"
https://wiki.jenkins.io/display/JENKINS/Windows+Exe+Runner+Plugin
But jenkins not allowing me to put an exe name in configuration. Looks like a bug of jenkins.
I have also tried by adding zap in environmental variable but that also not working.
Now I am out of idea.
The issue is if I am triggering zap.bat it will do not allow another command to run forward as below which is in my batch:-
Additionally, UI of zap is not open as it is open after direct clicking on zap.bat file
I have added 2 "Execute Windows batch command" still nothing works
Any suggestions will be welcome
Simple - dont start it from the jar!
Start it using the zap.sh or zap.bat scripts we provide as part of the installation :) You'll also probably want to use the -daemon flag.
Or you can use the official ZAP jenkins plugin: https://wiki.jenkins.io/display/JENKINS/zap+plugin
I have resolve this issue by creating two jobs in jenkins.
The main job trigger the first job.
Follow the steps :-
Go to the configure section of main job
Now add "Trigger/call builds on other projects" from Build option
Add the project name of zombie job
Note :- uncheck the checkbox of "Block until the triggered projects finish their builds".

Jenkins: ansible host not reachable

I am trying Jenkins to execute an ansible playbook.
But I am getting the unreachable host error which I don't get otherwise.
fatal: [vogo-alpha.cloudapp.net]: UNREACHABLE! => {"changed": false, "msg": "Authentication failure.", "unreachable": true}
I have given this variable in ansible hosts file,
ansible_ssh_private_key_file=/home/luvpreet/.ssh/id_rsa
I think it is because the user jenkins is playing those playbooks and it cannot read this private key file. I tried to make jenkins' user home folder but it was not successful.
It can be done if I switch to the user luvpreet and then run these playbooks.
How do I switch to another user via jenkins shell ?
OR
Is there any other way this problem can be solved ?
There are a couple of possibilities why your solution is working. Most likely because Ansible is trying to ssh to your target machine as the jenkins user which isn't on said machine. I'd approach the problem from a different angle.
First, I'd install the Ansible plugin for Jenkins. This allows you to use the built in credentials located at "Manage Jenkins > Manage Credentials". There you can copy and paste your key in (or point to a key file located on the jenkins server) and set the username that will ssh to the target machine. In your job configuration choose "Invoke Ansible Playbook" for your build step rather than shell. There will be a "Credentials" parameter where you can specify the ssh key you added earlier. The rest should be pretty self explanatory.

Configuring a TFS2015 build agent fails because agent pool not found. Why?

When configuring a build agent with the use of a PowerShell script, provided by an on-site TFS2015, the script errors out because it cannot find the agent pool on the server.
However, the agent pool 'default' definitely exists. On another server the same script works as expected, and builds run. See the script output below.
I have tried to following:
Create a new agent pool on the server, and reference that in the script. Same problem "Agent pool not found".
Installed Visual Studio 2015 with minimal features.
The user running the script is member of 'Build Administrators' and 'Build Service Accounts' security groups.
What is causing the script to fail on agent pool verification?
PS C:\Windows\system32> E:\Build\agentConfigureAgent.ps1
Enter the name for this agent (default is Agent-SRV001): BUILD002
Enter the URL for the Team Foundation Server (default is: http://[ip-address]:8080/tfs
Configure this agent against which agent pool? (default pool name is 'default'):
Enter the path of work folder for this agent (default is 'E:\Build\agent_work'): E:\Build\Work
Would you like to install the agent as a Windows Service (Y/N) (default is Y): n
Would you like to unconfigure any existing agent (Y/N) (default is N; the agent will be updated):
Configuring agent
Unblocking files Calling agent configure without /RunningAsService
Calling agent configure without /Force
Unable to find a agent pool with the name: default
WARNING: Configure agent failed, but you might fix this problem by configure with /Force.
Would you like to try agent configure again with parameter -Force (Y/N): y
Calling agent configure without /RunningAsService
Calling agent configure with /Force
Unable to find a agent pool with the name: default
E:\Build\agent\ConfigureAgent.ps1 : Configure agent failed. At line:1 char:1
+ E:\Build\agent\ConfigureAgent.ps1 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,ConfigureAgent.ps1
The user account running the build process script, needs to be part of the Agent Pool Administrator Accounts.
The error message from the script is misleading.
To resolve this error, I had to add the Windows user which is running the TFS build agent to the "Advanced" access level. This can be done under the root TFS Administer Server (top right gear) > Access levels UI. (http://your-tfs-server-here:8080/tfs/_admin/_licenses) My default access level for the server is set to Stakeholder.
The answer from #RoeIF worked for me, but I had a bit of trouble finding the page needed to add the account. Here's a screen grab to help:

Resources