Jenkins on Windows fails to deploy with WinRM? - windows

I have an old established codebase that I'm trying to bring up to modern era standards. Most of it is written on Windows using Visual Studio, so I need to have a Windows based build server to use the MSBuild pipeline. I have a mostly working Jenkins CI pipeline that ingests from Github webhooks, and should deploy to a Windows PC on my local network. I've tested that this works from any other user, on my workstation and on the build server. I know Jenkins runs jobs as the "NT AUTHORITY\System" user, and I've used SysInternals PSExec to pop in and setup my ssh keys, and so forth in the past. The problem is during the deploy step; I'm compressing and copying the build output using a PowerShell script, and using New-PSSession, and Copy-Item -ToSession.
I'm using a cred I'm constructing with Get-Credential, user/pass pair, that I've verified as working. All concerned systems are in a simple workgroup, no domain involved.
The New-PSSession command in my deploy.ps1 script fails with the following error:
PS C:\Program Files (x86)\Jenkins\workspace\xxx> .\deploy.ps1
Compressing to C:\Windows\TEMP\tmpEBB2.tmp.zip
New-PSSession: C:\Program Files (x86)\Jenkins\workspace\xxx\deploy.ps1:95
Line |
95 | … $sess = New-PSSession -ComputerName $TargetHost -Credential $cred …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| [205.208.87.185] Connecting to remote server 205.208.87.185 failed with the following error message :
| WinRM cannot process the request. The following error with errorcode 0x8009030d occurred while using
| Negotiate authentication: A specified logon session does not exist. It may already have been
| terminated. Possible causes are: -The user name or password specified are invalid. -Kerberos is
| used when no authentication method and no user name are specified. -Kerberos accepts domain user
| names, but not local user names. -The Service Principal Name (SPN) for the remote computer name and
| port does not exist. -The client and remote computers are in different domains and there is no trust
| between the two domains. After checking for the above issues, try the following: -Check the Event
| Viewer for events related to authentication. -Change the authentication method; add the destination
| computer to the WinRM TrustedHosts configuration setting or use HTTPS transport. Note that computers
| in the TrustedHosts list might not be authenticated. -For more information about WinRM
| configuration, run the following command: winrm help config. For more information, see the
| about_Remote_Troubleshooting Help topic. Other Possible Cause: -The domain or computer name was not
| included with the specified credential, for example: DOMAIN\UserName or COMPUTER\UserName.
Write-Error: C:\Program Files (x86)\Jenkins\workspace\xxx\deploy.ps1:129
Line |
129 | Deploy-ToTargetHost
| ~~~~~~~~~~~~~~~~~~~
| Could not establish session.
I generated that second error when the $sess var fails to populate. This is line 95:
$sess = New-PSSession -ComputerName $TargetHost -Credential $cred
I believe I've heard something about the System user has some restrictions on network access? Is there any way to work around this?
I mean, I can just scp it over if there's no other way to do this, but I really wanted to just have all my shell scripting in pwsh if I could get away with it. Thanks.
[Edit: TL;DR, I suppose I can modify Jenkins to run as a different user, but why isn't it already running like that? This just seems trivially weird to me to install by default on a user with no network access, I guess?]

I ended up running Jenkins as a different user in Windows Services, specifically a "regular" login user. This made it do the deployment successfully.

Related

PS script to copy data to external file share location

Scenario:
Site to Site VPN is configured with my network and with a remote Data centre and there is no AD Trust
On a daily basis, I need to copy the data from my server folder to remote file share location
For example:
Platform: Windows 2008
Server folder : D:\Data
Remote file share location: \1.2.3.4\Data
For remote file share location, they have different domain (for example username: xyz\user1)
How can I have a script where the data generated in our server folder (D:\Data) can be replicated to remote file share location using their credentials on a daily basis?
I'm confused with the step where how I can pass the 3rd party credentials to copy the data to their location as AD Trust is not configured.
Thanks in Advance.
You can use something like $cred = Get-Credential to create a variable that will store the credential in a PSCredential object.
Then when you call on it later you can just use $cred instead of signing in.
This will cause the script to prompt for domain credentials each time the script is run, and then use those when moving the files. I have used a simple cmdlet below and separated out the credential variable for readability.
Get-CimInstance Win32_DiskDrive -ComputerName Server01 -Credential $cred

PowerShell | Get Storage from Servers with "Get-ADComputer"

i have an problem with my script, plz help :3
This script is supposed to get all Server Hostnames from our Server OU. And than get the Used and Free Space of the Servers But when i try to get the server list with the "Get-AdComputer" cmdlet i get errors.
$servers = Get-ADComputer -Filter * -SearchBase "OU=SomeOU, DC=SomeDomain, DC=SomeDomain, DC=SomeDomain" | Select-Object Name
$allDisks = foreach ($server in $servers)
{
Get-WmiObject Win32_LogicalDisk -ComputerName $server -Filter DriveType=3 |
Select-Object #{'Name'='ComputerName'; 'Expression'={$server}},
DeviceID,
#{'Name'='Size'; 'Expression'={[math]::truncate($_.size / 1GB)}},
#{'Name'='Freespace'; 'Expression'={[math]::truncate($_.freespace / 1GB)}}
}
$allDisks |Export-Csv C:\Servers.csv -NoTypeInformation
when i run this i get:
Get-WmiObject : Der RPC-Server ist nicht verfügbar.
In Zeile:5 Zeichen:5
+ Get-WmiObject Win32_LogicalDisk -ComputerName $server -Filter Dri ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
i also should add, that if i only run the thing from the first line i get an clean list of all of our servers.
As the error states that RPC server is not available for the one of the servers that you are trying to query. There can be multiple reasons as per the PS Blog:
The remote computer is blocked by the firewall.
Solution: Open the Group Policy Object Editor snap-in (gpedit.msc) to edit the Group Policy object (GPO) that is used to manage Windows Firewall settings in your organization. OpenComputer Configuration, open Administrative Templates, open Network, open Network Connections, open Windows Firewall, and then open either Domain Profile or Standard Profile, depending on which profile you want to configure. Enable the following exception: “Allow Remote Administration Exception” and “Allow File and Printer Sharing Exception“.
Hostname or IP address is wrong or the remote computer is shut down.
Solution: Verify correct hostname or IP address.
The “TCP/IP NetBIOS Helper” service isn’t running.
Solution: Verify that “TCP/IP NetBIOS Helper” is running and set to auto start after restart.
The “Remote Procedure Call (RPC)” service is not running on the remote computer.
Solution: Verify that “Remote Procedure Call (RPC)” is running and set to auto start after restart.
The “Windows Management Instrumentation” service is not running on the remote computer.
Solution: Verify that “Windows Management Instrumentation” is running and set to auto start after restart
So, I dont think there is any code issue there. Kindly check the network firwwall and server side. Also apply a try/catch block and capture the exact server name in the loop to see which server is that causing the issue.

Where is github authentication token stored on Windows?

If I run a command similar to the following on a private repository:
git ls-remote https://github.com/org/repo.git
I'm getting this following prompt.
I'm using https://gitforwindows.org and looking at the Process Explorer, it appears that the executable that produces this window is \mingw64\libexec\git-core\git-credential-manager.exe relative to Git for Windows installation folder.
When I put in my credentials, I'm getting an email from Github, saying that a new authentication token is created.
Where is this token stored on my PC? When I repeat the command above I'm no longer getting the prompt - as long as I do not revoke the token on the github web site.
By default, Git will use the Windows Credential Manager for storing and retrieving Git credentials via Github for Windows desktop.
Credential Manager lets you view and delete your saved credentials for signing in to websites, connected applications, and networks.
To open Credential Manager, type credential manager in the search box on the taskbar and select Credential Manager Control panel.
Select Web Credentials or Windows Credentials to access the credentials you want to manage.
You will find the GitHub - https://api.github.com/{username} entry on the Windows Credentials tab.
Mike Mackintosh is right. Here is how you can access the token.
Install-Module CredentialManager -Scope AllUsers -Force
Change flags on the above command to your liking. Then:
Get-StoredCredential -AsCredentialObject | %{$_} `
| ?{ $_.targetName -like "*github.com*"} `
| sort LastWritten `
| select LastWritten,Targetname,Password
This will get you the list of tokens you may have created. Use Get-Command -Module CredentialManager to list all avialble commands on the module, you can use to manipulate the credentials store.

How to include domain user in Jenkins Job execution

I am automating a build process. The process requires deployment of application to a server, after deployment a few scripts have to be executed to share and provide permissions on the server. The scripts run when I login via domain user through powershell.I am using Jenkins for the CI/CD process. I want to include my domain credentials to run the scripts on the server. I have also used the active directory plugin, and can login with my domain credentials but still I am not able to establish a remote connection with the server.
My script is
Enter-PSSession -ComputerName ATKT-WS-20
Invoke-Expression -Command .\FolderSharingScript.ps1
Enter-PSSession : Connecting to remote server ATKT-WS-20 failed with the following error message : WinRM cannot
process the request. The following error with errorcode 0x8009030e occurred while using Kerberos authentication: A
specified logon session does not exist. It may already have been terminated.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or
use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.<
I have also added the machine name in the trustedhosts. How can I include the domain credential in Jenkins jobs?
The solution turned out to be not to use PowerShell's remoting at all, but instead rely on the remoting built into Jenkins:
Connect the remote machine as a Jenkins agent to the Jenkins server, running the agent executable as the desired domain user.
On the Jenkins server, ensure that your job is configured to run on the remote machine, using a label expression.
Assuming the PowerShell plugin is installed, you can then send PowerShell code as-is to the remote machine - no need for PowerShell sessions, credentials, ...

Security of running PowerShell command remotely?

I'm new to PowerShell. I'm looking to run PowerShell command on a remote PC running Windows 7.
On the remote PC, I ran the following PowerShell commands:
Enable-PSRemoting -Force
Set-Item WSMAN:\localhost\client\trustedhosts <host_ip>
Restart-Service WinRM
I performed the last two commands on the host PC (but using <remote_ip>).
I confirmed this worked OK with:
Invoke-Command -ComputerName <name> -Credential <username> -ScriptBlock { Get-ChildItem C:\ }
My question: Is this secure on a public network? Should I be doing something else? Or should I be using SSL? If so, how do I go about this?
If you use the default authentication when using Invoke-Command the user is authenticated on the remote host using either NTLM or Kerberos. So I don't think you need to worry too much about the password being sniffed out on the network. Also, by default, remoting endpoints can only be used by administrators on that machine. Finally, if you need to allow non-admins access, you can configure a remoting endpoint that is restricted. It can be restricted in the cmdlets available and it can be restricted in language capability. This tutorial on remoting covers setting up a restricted session.

Resources