How to create a windows service with credentials in Docker container? - docker

I need to start a service in Windows container which has username and password.
In Windows it looks like this:
In Docker container I tried this:
$serviceName = "MyService"
$binaryPath = "c:\MyService.exe"
$secpasswd = ConvertTo-SecureString "MYPASS" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("mydomain\account1", $secpasswd)
New-Service -name $serviceName -binaryPathName $binaryPath -displayName $serviceName -startupType Automatic -credential $mycreds
But I get this error:
New-Service : Service 'MyService(MyService)' cannot be created due to the following eerror: The account name is invalid or does not exist, or the password is invalid for the account name specified At line:1 char:1
+ New-Service -name $serviceName -binaryPathName $binaryPath -displayNa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (MyService:String) [New-Service], ServiceCommandExceptio n
+ FullyQualifiedErrorId : CouldNotNewService,Microsoft.PowerShell.Commands.NewServiceCommand
I think my domain account credentials aren't somehow reachable in docker container.
Does anyone know how to fix this?

You have to use group managed service accounts.
https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/manage-serviceaccounts

Related

Getting error .\config.cmd : VS30063: You are not authorized to access https://

Running on premise Azure DevOps server. Trying to setup agent for pipeline.
Error in log file: [2021-12-02 17:21:20Z ERR Terminal] WRITE ERROR: VS30063: You are not authorized to access https://
Have a Basic authentication setup. Have users granted access to site.
Here is the command line in powershell.
\config.cmd --unattended --url https://FQDN_Server/Bill_Test/ --auth negotiate --userName Domain\User --password PASSWORD --token h6mgqztjnx5zbam7rmmdo5gnb4gz3xndvwyqotofxuycx4x74uha --pool SQLServer --agent devAgent --acceptTeeEula
Can you try below steps:
Download the release agent zip file and place it inside the downloads folder of release machine
Then execute below 2 PS scripts to extract in c drive
PS C:> mkdir agent ; cd agent
Add-Type -AssemblyName System.IO.Compression.FileSystem ; [System.IO.Compression.ZipFile]::ExtractToDirectory("$HOME\Downloads\vsts-agent-win-x64-2.153.1.zip", "$PWD")
Point to c drive agent folder and execute below command.
.\config.cmd --deploymentpool --deploymentpoolname "YOUR_DEP_POOL_NAME" --agent $env:COMPUTERNAME --runasservice --work '_work' --url 'https://YOUR_TFS_SERVER/';
While installing when it prompts for authentication type, enter as Negotiate. Then provide username and password

Docker Windows Error Reporting Crash dump for StackOverflowExceptions not wokring

I am trying to configure a docker image so that we get a memory dump when a container crashes.
I have configured the registry settings for "Windows Error Reporting" so that it should write a dump file to a mapped directory on the host machine.
$key = "HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\{0}" -f CrashTest.exe
New-Item $key -Force
Push-Location $key
New-ItemProperty . -Name DumpType -Value 2 -PropertyType DWord
New-ItemProperty . -Name DumpFolder -Value "C:\Dumps" -PropertyType String
Pop-Location
This works fine for an unhandled user exception but not for a stack overflow exception or an out of memory exception.
I have created a github repository with a minimal example of the issue here - https://github.com/spreadex/win-docker-crash-dump
If anyone has any idea how to get this working it would be most appricated.
Cheers.

Windows Container does not resolve container by service name if using user-defined network

I have a simple Dockerfile
FROM mcr.microsoft.com/windows/servercore:1803
CMD powershell "Start-Sleep -s 100000"
and docker-compose defining 2 services a and b:
version: "3.5"
services:
a:
build: .
b:
build: .
networks:
default:
external: true
name: app
```
After docker-compose up --build --force-recreate and connecting to one of containers I cannot resolve containers by their service names:
PS C:\> ping a
Ping request could not find host a. Please check the name and try again.
PS C:\> ping b
Ping request could not find host b. Please check the name and try again.
PS C:\> Resolve-DnsName a
Resolve-DnsName : a : The filename, directory name, or volume label syntax is incorrect
At line:1 char:1
+ Resolve-DnsName a
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (a:String) [Resolve-DnsName], Win32Exception
+ FullyQualifiedErrorId : ERROR_INVALID_NAME,Microsoft.DnsClient.Commands.ResolveDnsName
PS C:\> Resolve-DnsName b
Resolve-DnsName : b : The filename, directory name, or volume label syntax is incorrect
At line:1 char:1
+ Resolve-DnsName b
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (b:String) [Resolve-DnsName], Win32Exception
+ FullyQualifiedErrorId : ERROR_INVALID_NAME,Microsoft.DnsClient.Commands.ResolveDnsName
PS C:\>
But if I remove networks section from docker-compose service name resolution works fine. If I create and use bridged network on Linux everything also works fine.
Is this behavior by design or am I doing something wrong?

Attaching a SQL Server database to a Docker container throws error- Docker for Windows

I am using the below command in Powershell and Docker for Windows (Windows 10 Pro)
docker run -d -p 1433:1433 -e sa_password=Infra_2017 -e ACCEPT_EULA=Y -v
c:/infra_mvc_projects/SampleDb:c:/infra_mvc_projects/SampleDb -e
attach_dbs="[{'dbName':'AdventureWorksDW2008R2_Data','dbFiles':
['c:\infra_mvc_projects\SampleDb\AdventureWorksDW2008R2_Data.mdf','c:\infra
mvc_projects\SampleDb\AdventureWorksDW2008R2_Log.ldf']}]"
microsoft/mssql-server-windows
Below is the error
VERBOSE: Starting SQL Server
docker : Sqlcmd: 'AdventureWorksDW2008R2_Data";CREATE DATABASE
"AdventureWorksDW2008R2_Data" ON (FILENAME =
N'c:\infra_mvc_projects\SampleDb\AdventureWorksDW2008R2_Data.mdf'),
(FILENAME =
N'c:\infra_mvc_projects\SampleDb\AdventureWorksDW2008R2_Log.ldf') FOR
ATTACH ;"': Unexpected
argument. Enter '-?' for help.
At line:1 char:1
+ docker logs 673
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Sqlcmd: 'Advent... '-?' for
help.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
VERBOSE: Changing SA login credentials
VERBOSE: Attaching 1 database(s)
VERBOSE: Invoke-Sqlcmd -Query sp_detach_db
"AdventureWorksDW2008R2_Data";CREATE
DATABASE "AdventureWorksDW2008R2_Data" ON (FILENAME =
N'c:\infra_mvc_projects\SampleDb\AdventureWorksDW2008R2_Data.mdf'),
(FILENAME =
N'c:\infra_mvc_projects\SampleDb\AdventureWorksDW2008R2_Log.ldf') FOR
ATTACH ;
VERBOSE: Started SQL Server.
The container gets created and able to open in Sql server management studio. But unable to attach the database with the above error.
Per the solution posted over in GitHub, the latest developer and express sqlserver images with setting the ATTACH_DBs environmental var works fine.

Start And Stop Windows Service remotely using PSEXEC

How to start and and stop a Windows service remotely using PSEXEC? Preferably the syntax to write I tried the cmdlet given below
psexec \\Server -u Administrator -p Somepassword ServiceName
PSService on SysInternals is specifically for remotely controlling services::`
psservice [\\computer [-u username] [-p password]] <command> <options>
where:
query Displays the status of a service.
config Displays the configuration of a service.
setconfig Sets the start type (disabled, auto, demand) of a service.
start Starts a service.
stop Stops a service.
restart Stops and then restarts a service.
pause Pauses a service
cont Resumes a paused service.
depend Lists the services dependent on the one specified.
security Dumps the service's security descriptor.
find Searches the network for the specified service.
\\computer Targets the NT/Win2K system specified.
Include the -u switch with a username and password to login to the remote system if your security credentials do not permit you to obtain performance counter information from the remote system. If you specify the -u option, but not a password with the -p option, PsService will prompt you to enter the password and will not echo it to the screen.
Another alternative to psexec is sc. You can use sc to start or stop services remotely:
sc \\server start ServiceName
sc \\server stop ServiceName
There is no "login" information, so maybe you need to execute
net use \\server password /USER:user
before executing sc command.
One advantage over psexec is that no console window shows in the remote machine.
I can't test this right now, but it ought to be:
psexec \\server -u username -p password net start ArgusCommunityWorkerService
and
psexec \\server -u username -p password net stop ArgusCommunityWorkerService
Using PSEXEC
The below batch file will let you stop and start services on multiple remote machines. Create Computers.txt file in the same directory where the batch file runs from and list PC hostnames one per line.
#echo off
TITLE Manage Services v1.0
SET suffix=%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%%time:~6,2%
SET /P username=Enter your admin username:
set "psCommand=powershell -Command "$pword = read-host 'Enter Password' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p
:service
SET /P servicename=Enter service name:
:begin
echo ========================================
echo 1) Start
echo 2) Stop
echo 3) Choose another service
echo ========================================
ECHO.
set /p op=Select an option:
if "%op%"=="1" SET action=start
if "%op%"=="2" SET action=stop
if "%op%"=="3" goto service
psexec "\\#%~dp0Computers.txt" -u %username% -p %password% -h net %action% %servicename% >>%suffix%.log 2>&1
pause
cls
goto begin
Using PowerShell
# Point the script to the text file with remote computers
$RemoteComputers = Get-Content "$PSScriptRoot\Computers.txt"
# sets service name
$Service = "uvnc_service"
# Counter for progress bar
$counter = 0
ForEach ($Computer in $RemoteComputers) {
$counter++
Try
{
Write-Progress -Activity 'Processing computers' -CurrentOperation $Computer -PercentComplete (($counter / $RemoteComputers.count) * 100)
Start-Sleep -Milliseconds 200
Get-Service -Name $Service -ComputerName $Computer | Restart-Service -Force -ErrorAction Stop
Write-Output "$(Get-Date -format "yyyy-MM-dd hh:mm:ss"),$computer" | out-file -append -filepath "$PSScriptRoot\success.log"
}
Catch
{
Write-Output "$(Get-Date -format "yyyy-MM-dd hh:mm:ss"),$computer" | out-file -append -filepath "$PSScriptRoot\failed.log"
}
}
Refering to Microsoft, an alternative is using psservice, which is part of pstools downloadable under following link:
Download PsTools (2.7 MB)
If someone needs to
Start, stop, restart, etc... a Windows Service remotely
as mentioned in the official reference from Microsoft, the appropriate command using the provided executable
PsService.exe
could be something similar to following (Case 1 and case 2), if you are using Windows PowerShell
Case 1: User, who will perform the wished command (e.g. restart) after signed in, is remote computer user with appropriate rights
.\PsService.exe \\Remote-ComputerName-OR-ServerName -u
'RemoteComputerName-OR-ServerName\Remote-ComputerUser' -p
'Remote-ComputerUser-Password' restart ServiceName
Case 2: User, who will perform the wished command (e.g. restart) after signed in, is domain superuser (e.g. DomainAdministrator)
.\PsService.exe \\Remote-ComputerName-OR-ServerName -u
'DomainShortName\DomainAdministrator' -p
'DomainAdministrator-Password' restart ServiceName
PS: Notice in this case the single quoted parameter values for
username
-u
and password
-p
for complex password and/or username
That's it, your command should get executed smoothly, just be patient!

Resources