sourcecode

암호를 입력하라는 메시지를 표시하지 않고 PowerShell 인증 정보 사용

codebag 2023. 4. 23. 10:19
반응형

암호를 입력하라는 메시지를 표시하지 않고 PowerShell 인증 정보 사용

도메인에 속한 원격 컴퓨터를 다시 시작하고 싶습니다.관리자 계정이 있는데 powershell에서 어떻게 사용하는지 모르겠어요.

는 there알 i i가 있다는 것을 있습니다.Restart-Computer 및 할 수 도메인이 instance mydomain은 " " " 입니다myuser 비밀번호는 '비밀번호'입니다.mypassword떤떤구 문용 ?용 ?? ????

암호를 입력할 필요가 없도록 재부팅 일정을 잡아야 합니다.

Get-Credential항상 패스워드를 입력하도록 요구됩니다.그러나 이 문제를 해결하는 방법은 있지만 암호를 파일 시스템에 보안 문자열로 저장하는 것입니다.

다음 문서에서는 이 동작에 대해 설명합니다.

프롬프트 없이 PSCredential 사용

요약하면 비밀번호를 저장하는 파일을 만듭니다(암호화 문자열).는 에 됩니다.c:\mysecurestring.txt이치노 딱한 번만 요.

read-host -assecurestring | convertfrom-securestring | out-file C:\mysecurestring.txt

-Credential하면 PowerShell을 할 수 .PSCredential다음 중 하나:

$username = "domain01\admin01"
$password = Get-Content 'C:\mysecurestring.txt' | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist $username, $password

$serverNameOrIp = "192.168.1.1"
Restart-Computer -ComputerName $serverNameOrIp `
                 -Authentication default `
                 -Credential $cred
                 <any other parameters relevant to you>

것이 요.-Authentication사용 환경을 모르기 때문에 값을 바꿉니다.

다른 방법이 있긴 하지만...

비밀번호를 스크립트 파일에 저장하지 않으면 이 작업을 수행하지 마십시오(비밀번호를 스크립트에 저장하는 것은 좋지 않지만 방법을 알고 싶은 사람도 있습니다).

좋아, 그게 경고야. 암호는 이렇다.

$username = "John Doe"
$password = "ABCDEF"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr

$cred는 비밀번호가 "ABCDEF"인 있습니다.

다른 방법으로 패스워드를 사용할 수 있도록 준비합니다.

$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force

credential 저장에 관해서는 다음 두 가지 기능(일반적으로 프로파일에서 로드되는 모듈에 있음)을 사용합니다.

#=====================================================================
# Get-MyCredential
#=====================================================================
function Get-MyCredential
{
param(
$CredPath,
[switch]$Help
)
$HelpText = @"

    Get-MyCredential
    Usage:
    Get-MyCredential -CredPath `$CredPath

    If a credential is stored in $CredPath, it will be used.
    If no credential is found, Export-Credential will start and offer to
    Store a credential at the location specified.

"@
    if($Help -or (!($CredPath))){write-host $Helptext; Break}
    if (!(Test-Path -Path $CredPath -PathType Leaf)) {
        Export-Credential (Get-Credential) $CredPath
    }
    $cred = Import-Clixml $CredPath
    $cred.Password = $cred.Password | ConvertTo-SecureString
    $Credential = New-Object System.Management.Automation.PsCredential($cred.UserName, $cred.Password)
    Return $Credential
}

그리고 이건...

#=====================================================================
# Export-Credential
# Usage: Export-Credential $CredentialObject $FileToSaveTo
#=====================================================================
function Export-Credential($cred, $path) {
      $cred = $cred | Select-Object *
      $cred.password = $cred.Password | ConvertFrom-SecureString
      $cred | Export-Clixml $path
}

다음과 같이 사용합니다.

$Credentials = Get-MyCredential (join-path ($PsScriptRoot) Syncred.xml)

credential 파일이 존재하지 않으면 처음에 프롬프트가 표시되며, 이 시점에서 XML 파일 내의 암호화된 문자열에 credential이 저장됩니다.이 라인을 두 번째로 실행하면 xmlfile이 표시되고 자동으로 열립니다.

다른 credential이 필요한 리모트서버에서 SCOM 2012 기능을 실행해야 합니다.패스워드 복호화 함수의 출력을 ConvertTo-SecureString에 입력으로 전달함으로써 클리어 텍스트의 패스워드를 회피합니다.알기 쉽게 하기 위해서, 이것은 여기에서는 나타내고 있지 않습니다.

나는 선언문을 강하게 타이핑하는 것을 좋아한다.$strPass 유형 선언은 올바르게 작동합니다.

[object] $objCred = $null
[string] $strUser = 'domain\userID'
[System.Security.SecureString] $strPass = '' 

$strPass = ConvertTo-SecureString -String "password" -AsPlainText -Force
$objCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($strUser, $strPass)

재기동을 스케줄 하고 있는 경우는, 다음의 2개의 방법이 있습니다.

먼저 다른 시스템을 연결하고 재부팅하는 데 필요한 권한이 있는 자격 증명을 사용하여 한 시스템에 태스크를 생성할 수 있습니다.따라서 스케줄러는 credential을 안전하게 저장할 책임이 있습니다.reboot 명령어(나는 Powershell 사용자이지만 이 명령어가 더 깨끗합니다)는 다음과 같습니다.

SHUTDOWN /r /f /m \\ComputerName

로컬 머신에 스케줄된 작업을 생성하여 다른 작업을 원격으로 재부팅하는 명령줄은 다음과 같습니다.

SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f /m \\ComputerName" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU "domain\username" /RP "password"

두 번째 방법은 현재 자격 증명을 사용하여 원격 시스템에서 시스템 계정으로 실행되는 스케줄링된 작업을 생성하는 것입니다.

SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU SYSTEM /S ComputerName

이 조작은 GUI에서도 동작합니다.패스워드 필드는 공백인 채로 SYSTEM을 사용자명으로 입력합니다.

Import/Export-CLIXML을 사용하는 예를 하나 보았습니다.

해결하려는 문제에 대해 제가 가장 좋아하는 명령어입니다.그리고 그것들을 사용하는 가장 간단한 방법은요.

$passwordPath = './password.txt'
if (-not (test-path $passwordPath)) {
    $cred = Get-Credential -Username domain\username -message 'Please login.'
    Export-CliXML -InputObject $cred -Path $passwordPath
}
$cred = Import-CliXML -path $passwordPath

따라서 파일이 로컬에 존재하지 않으면 자격 증명을 입력하라는 메시지가 표시되고 저장됩니다. 작업은 이이가 합니다.[pscredential]자격 증명

마지막으로 평소처럼 자격증을 사용합니다.

Restart-Computer -ComputerName ... -Credentail $cred

유가증권에 관한 주의사항:

자격 증명을 디스크에 안전하게 저장

솔루션을 읽을 때 처음에는 디스크에 암호를 저장하는 데 주의를 기울일 수 있습니다.하드 드라이브에 기밀 정보를 흘리는 것은 당연하지만 Export-CliXml cmdlet은 Windows 표준 Data Protection API를 사용하여 자격 증명 개체를 암호화합니다.이렇게 하면 사용자 계정만 내용을 올바르게 해독할 수 있습니다.마찬가지로 ConvertFrom-SecureString cmdlet은 사용자가 제공한 비밀번호도 암호화합니다.

편집: 원래 질문을 다시 읽어 보십시오.'만.[pscredential]하드 디스크로 이동합니다., 한 후 가 자동으로

read-host -assecurestring | convertfrom-securestring | out-file C:\securestring.txt
$pass = cat C:\securestring.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "test",$pass
$mycred.GetNetworkCredential().Password

이 방법으로 패스워드를 보존할 때는, 매우 주의해 주세요.그것은 ...만큼 안전하지 않다.

솔루션

$userName = 'test-domain\test-login'
$password = 'test-password'

$pwdSecureString = ConvertTo-SecureString -Force -AsPlainText $password
$credential = New-Object -TypeName System.Management.Automation.PSCredential `
    -ArgumentList $userName, $pwdSecureString

빌드 머신의 경우
이전 코드에서는 사용자 이름과 비밀번호 값을 빌드 머신의 비밀("로그에서 숨김") 환경변수로 대체했습니다.

테스트 결과:

'# Results'
$credential.GetNetworkCredential().Domain
$credential.GetNetworkCredential().UserName
$credential.GetNetworkCredential().Password

그러면 알게 될 것이다

# Results
test-domain
test-login
test-password

이것은 내가 사용하고 나를 위해 일하는 것이다.

$User="Domain\Username"
$Password=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('VABlAHMAdABQAGEAcwBzAHcAbwByAGQA'))

$SecurePassword = New-Object -TypeName System.Security.SecureString
$Password.ToCharArray() | ForEach-Object {$SecurePassword.AppendChar($_)}

$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $SecurePassword

VABl을 취득하려면AHMAdABQAGEAcwBzAHcAbwByAGQA:

$EString 인코딩은 암호화된 문자열을 의미하고 $DString은 복호화된 문자열을 의미합니다.

$EString = Read-Host "Type Text to Encode" -AsSecureString
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($EString)
$DString=[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$Encoded=[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($DString))

$Encoded # VABlAHMAdABQAGEAcwBzAHcAbwByAGQA
$DString # TestPassword

그렇게 하면 스크립트에 내가 원하는 패스워드를 쉽게 넣을 수 있다.

아래 코드가 도움이 될 수 있는 경우.

function Get-RemoteConnection()
{
    //$serverIp can be passed as a parameter of the function.
    //I just make it static for testing. 
    $serverIp = '192.168.100.137'
    Enable-PSRemoting -Force
    Set-Item wsman:\localhost\client\trustedhosts $serverIp
    Restart-Service WinRM
    #Set credentials needed for remote installation
    $userName = "administrator"
    $password = ConvertTo-SecureString "2020core0515" -AsPlainText -Force
    $cred = New-Object System.Management.Automation.PSCredential -ArgumentList ($userName, $password)
    $session = New-PSSession -ComputerName $serverIp -Credential $cred

    $a = Invoke-Command -Session $session -ScriptBlock {  Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3" | Select-Object DeviceID, @{label='UsedPercent'; expression={[Math]::Round((($_.size - $_.freespace) / $_.size) * 100, 2)}} }

    Write-Host $a

    return $session
}

function Delete-RemoteConnection($session)
{
    Disconnect-PSSession $session | Out-Null
    Disable-WSManCredSSP -Role Client
}

암호화된 암호를 텍스트 파일에 저장하는 대신 인증 정보 볼트에 저장할 수 있습니다.다음 예제에서는 사용자에게 패스워드를 입력하라는 메시지가 처음 표시된 후 자격 증명 볼트에서 패스워드를 가져옵니다.

# Load the Windows Runtime Class
[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$Vault = New-Object Windows.Security.Credentials.PasswordVault

$RESOURCE = "myresource"
$USERNAME = "myuser"

try {
    $credentials = $Vault.Retrieve($RESOURCE,$USERNAME)
    $pwd = $credentials.Password | ConvertTo-SecureString -Key (1..16)
    }
catch {
    $pwd = Read-Host "please enter your password:" -AsSecureString
    $Encrypted = ConvertFrom-SecureString -SecureString $pwd -Key (1..16)
    $credentials = new-object -Type Windows.Security.Credentials.PasswordCredential -ArgumentList $RESOURCE,$USERNAME,$Encrypted
    $Vault.Add($credentials)
    }

$cred = New-Object System.Management.Automation.PsCredential($USERNAME,$pwd)

아주 간단한 것을 시도해 보는 게 어때?

명령어 'shutdown /r /f /t 0' 및 CMD의 PC 목록과 함께 psexec을 사용합니다.

언급URL : https://stackoverflow.com/questions/6239647/using-powershell-credentials-without-being-prompted-for-a-password

반응형