source

"네트워크 서비스" 계정을 위해 파워셸에서 윈도우 서비스를 만드는 방법은?

nicesource 2023. 10. 1. 19:31
반응형

"네트워크 서비스" 계정을 위해 파워셸에서 윈도우 서비스를 만드는 방법은?

파워셸을 이용해 윈도우 서비스를 만들고 싶습니다.주어진 사용자를 위해 그것을 만드는 것은 식은 죽 먹기입니다.여기서 개조한 이 기능을 사용했습니다.

function ReinstallService1 ($serviceName, $binaryPath, $login, $pass)
{  
    Write-Host "installing service"
    # creating credentials which can be used to run my windows service
    $secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
    $mycreds = New-Object System.Management.Automation.PSCredential ($login, $secpasswd)

    # creating widnows service using all provided parameters
    New-Service -name $serviceName -binaryPathName $binaryPath -displayName $serviceName -startupType Automatic -credential $mycreds
    Write-Host "installation completed"
}

제 질문은 다음과 같습니다."네트워크 서비스" 계정을 만들려면 어떻게 해야 합니까?

서비스 줄을 수정하고 자격 증명 매개 변수를 제거하면 "로컬 시스템" 계정에 대한 서비스가 생성됩니다.거의 놓칠 뻔했네요.

New-Service -name $serviceName -binaryPathName $binaryPath -displayName $serviceName -startupType Automatic 

구글 검색을 많이 했는데 서비스 계정을 표시할 방법이 없었습니다.사용자 "NETWORK SERVICE"에 대해 자격 증명 매개 변수를 사용하려고 하면 어떤 암호를 입력해야 할지 모르겠고 (cmdlet이 무시할 경우를 대비하여) 하나를 발명하면 작동하지 않습니다.오류는 다음과 같습니다.

새 서비스 : 다음 오류로 인해 'XXXX(XXXX)' 서비스를 만들 수 없습니다.계정 이름이 잘못되었거나 존재하지 않거나 지정한 계정 이름에 대한 암호가 잘못되었습니다.

계정의 정확한 이름은NT AUTHORITY\NETWORK SERVICE.

이것은 애니켓을 위한 모든 사람들을 위한 재설치 서비스의 최종 버전입니다.

function ReinstallService ($serviceName, $binaryPath, $description, $login, $password, $startUpType)
{
        Write-Host "Trying to create service: $serviceName"

        #Check Parameters
        if ((Test-Path $binaryPath)-eq $false)
        {
            Write-Host "BinaryPath to service not found: $binaryPath"
            Write-Host "Service was NOT installed."
            return
        }

        if (("Automatic", "Manual", "Disabled") -notcontains $startUpType)
        {
            Write-Host "Value for startUpType parameter should be (Automatic or Manual or Disabled) and it was $startUpType"
            Write-Host "Service was NOT installed."
            return
        }

        # Verify if the service already exists, and if yes remove it first
        if (Get-Service $serviceName -ErrorAction SilentlyContinue)
        {
            # using WMI to remove Windows service because PowerShell does not have CmdLet for this
            $serviceToRemove = Get-WmiObject -Class Win32_Service -Filter "name='$serviceName'"

            $serviceToRemove.delete()
            Write-Host "Service removed: $serviceName"
        }

        # if password is empty, create a dummy one to allow have credentias for system accounts: 
        #NT AUTHORITY\LOCAL SERVICE
        #NT AUTHORITY\NETWORK SERVICE
        if ($password -eq "") 
        {
            #$secpassword = (new-object System.Security.SecureString)
            # Bug detected by @GaTechThomas
            $secpasswd = (new-object System.Security.SecureString)
        }
        else
        {
            $secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
        }
        $mycreds = New-Object System.Management.Automation.PSCredential ($login, $secpasswd)

        # Creating Windows Service using all provided parameters
        Write-Host "Installing service: $serviceName"
        New-Service -name $serviceName -binaryPathName $binaryPath -Description $description -displayName $serviceName -startupType $startUpType -credential $mycreds

        Write-Host "Installation completed: $serviceName"

        # Trying to start new service
        Write-Host "Trying to start new service: $serviceName"
        $serviceToStart = Get-WmiObject -Class Win32_Service -Filter "name='$serviceName'"
        $serviceToStart.startservice()
        Write-Host "Service started: $serviceName"

        #SmokeTest
        Write-Host "Waiting 5 seconds to give time service to start..."
        Start-Sleep -s 5
        $SmokeTestService = Get-Service -Name $serviceName
        if ($SmokeTestService.Status -ne "Running")
        {
            Write-Host "Smoke test: FAILED. (SERVICE FAILED TO START)"
            Throw "Smoke test: FAILED. (SERVICE FAILED TO START)"
        }
        else
        {
            Write-Host "Smoke test: OK."
        }

}

다음과 같이 간단하게 네트워크 서비스에 대한 자격증을 얻을 수 있습니다.

$login = "NT AUTHORITY\NETWORK SERVICE"
#### #just set a dummy psw since it's just used to get credentials

$psw = "dummy"

$scuritypsw = ConvertTo-SecureString $psw -AsPlainText -Force

$mycreds = New-Object System.Management.Automation.PSCredential($login, $scuritypsw)
#### #then you can use the cred to new a windows service

$serviceName = "Test"
$binaryPath = "C:\Test\Test.exe"

New-Service -name $serviceName -binaryPathName $binaryPath -displayName $serviceName -startupType Automatic -credential $mycreds

Get-WmiObject는 지금 더 이상 사용되지 않습니다.그러나 PowerShell은 이제 서비스와 함께 작동할 수 있도록 cmdlet을 내장했습니다.다음은 의 업데이트된 버전입니다.ReinstallService서비스를 시작하고 중지하기 위한 편리한 기본값 및 포장지와 함께 오스카 폴리의 답변에 따라 수정되었습니다.

# https://stackoverflow.com/questions/35064964/powershell-script-to-check-if-service-is-started-if-not-then-start-it
function TryStopService([string] $serviceName)
{
    Write-Host "Attempting to stop service: $serviceName..."
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue

    if($service)
    {
        if ($service.Status -ne 'Running')
        {
            Write-Host "    Service: $serviceName is not running."
        }
        else
        {
            Stop-Service -name $serviceName
            Write-Host "    Stopped service: $serviceName."
        }
    }
    else
    {
        Write-Host "    Service: $serviceName is not found."
    }
}

function UninstallService([string] $serviceName)
{
    Write-Host "Attempting to uninstall service: $serviceName..."
    if (Get-Service $serviceName -ErrorAction SilentlyContinue)
    {
        Remove-Service -Name $serviceName
        Write-Host "    Uninstalled service: $serviceName."
    }
    else
    {
        Write-Host "    Service: $serviceName is not found."
    }
}

function StartSertice([string] $serviceName)
{
    Write-Host "Attempting to start service: $serviceName..."
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue

    if($service)
    {
        if ($service.Status -eq 'Running')
        {
            Write-Host "    Service: $serviceName is already running."
            return
        }
    }

    # Trying to start new service.
    Write-Host "    Trying to start new service: $serviceName."
    Start-Service -Name $serviceName

    #Check that service has started.
    Write-Host "    Waiting 5 seconds to give service time to start..."
    Start-Sleep -s 5
    $testService = Get-Service -Name $serviceName

    if ($testService.Status -ne "Running")
    {
        [string] $errMessage = "    Failed to start service: $serviceName"
        Write-Host $errMessage
        Throw $errMessage
    }
    else
    {
        Write-Host "    Started service: $serviceName."
    }
}

function ReinstallService ([string] $serviceName, [string] $binaryPath, [string] $description = "", [string] $login = "NT AUTHORITY\NETWORK SERVICE", [string] $password = "", [string] $startUpType = "Automatic")
{
    Write-Host "Attempting to reinstall service: $serviceName..."

    #Check Parameters
    if ((Test-Path $binaryPath)-eq $false)
    {
        Write-Host "    BinaryPath to service was not found: $binaryPath."
        Write-Host "    Service was NOT installed."
        return
    }

    if (("Automatic", "Manual", "Disabled") -notcontains $startUpType)
    {
        Write-Host "    Value for startUpType parameter should be (Automatic or Manual or Disabled) and it was $startUpType"
        Write-Host "    Service was NOT installed."
        return
    }

    TryStopService -serviceName $serviceName
    UninstallService -serviceName $serviceName

    # if password is empty, create a dummy one to allow having credentias for system accounts:
    #     NT AUTHORITY\LOCAL SERVICE
    #     NT AUTHORITY\NETWORK SERVICE
    if ($password -eq "")
    {
        $secpassword = (new-object System.Security.SecureString)
    }
    else
    {
        $secpassword = ConvertTo-SecureString $password -AsPlainText -Force
    }

    $mycreds = New-Object System.Management.Automation.PSCredential ($login, $secpassword)

    # Creating Windows Service using all provided parameters.
    Write-Host "Installing service: $serviceName with user name: '$login'..."
    New-Service -name $serviceName -binaryPathName $binaryPath -Description $description -displayName $serviceName -startupType $startUpType -credential $mycreds
    Write-Host "    Installed service: $serviceName."

    # Trying to start new service.
    StartSertice -serviceName $serviceName
}

언급URL : https://stackoverflow.com/questions/14708825/how-to-create-a-windows-service-in-powershell-for-network-service-account

반응형