도메인의 시스템에 예약 된 작업을 추가하는 Powershell 스크립트를 사용하고 있습니다. 이 스크립트를 실행하면 비밀번호를 묻는 메시지가 나타납니다. 비밀번호를 뚱뚱하게 손가락으로 가리고 프로세스가 시작되어 계정이 잠 깁니다. 입력 한 내용이 도메인에서 유효한지 확인하기 위해 자격 증명을 확인하는 방법이 있습니까?
도메인 컨트롤러를 쿼리하는 방법을 찾고 싶습니다. 일부 Google 검색을 수행했으며 WMI 쿼리를 수행하고 오류를 잡을 수 있어야합니다. 가능한 경우 해당 스타일의 유효성 검사를 피하고 싶습니다.
어떤 아이디어? 미리 감사드립니다.
답변
나는 이것을 내 도서관에 가지고있다 :
$cred = Get-Credential #Read credentials
$username = $cred.username
$password = $cred.GetNetworkCredential().password
# Get current domain using logged-on user's credentials
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$UserName,$Password)
if ($domain.name -eq $null)
{
write-host "Authentication failed - please verify your username and password."
exit #terminate the script.
}
else
{
write-host "Successfully authenticated with domain $domain.name"
}
답변
이것이 내가 과거에 사용한 것입니다. 로컬 컴퓨터 계정과 ‘응용 프로그램 디렉토리’에서 작동해야하지만 지금까지는 AD 자격 증명으로 만 성공적으로 사용했습니다.
function Test-Credential {
<#
.SYNOPSIS
Takes a PSCredential object and validates it against the domain (or local machine, or ADAM instance).
.PARAMETER cred
A PScredential object with the username/password you wish to test. Typically this is generated using the Get-Credential cmdlet. Accepts pipeline input.
.PARAMETER context
An optional parameter specifying what type of credential this is. Possible values are 'Domain','Machine',and 'ApplicationDirectory.' The default is 'Domain.'
.OUTPUTS
A boolean, indicating whether the credentials were successfully validated.
#>
param(
[parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.Management.Automation.PSCredential]$credential,
[parameter()][validateset('Domain','Machine','ApplicationDirectory')]
[string]$context = 'Domain'
)
begin {
Add-Type -assemblyname system.DirectoryServices.accountmanagement
$DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::$context)
}
process {
$DS.ValidateCredentials($credential.UserName, $credential.GetNetworkCredential().password)
}
}
답변
이 게시물이 유용하다는 것을 알았지 만 로컬 관리자 계정이 로그온 한 스크립트에서 실행하려고 시도했을 때 문제가 해결되지 않았습니다. 로컬 관리자로 작동하지 않는 것 같습니다 (도메인 사용자로 로그온 한 경우에만).
그러나 마침내 작동하는 솔루션을 얻었으므로 문제가 너무 많아서이 문제를 가진 다른 사람이 여기에 답을 줄 수 있도록 여기에서 공유한다고 생각했습니다. 필요에 따라 두 페이지 모두 한 페이지에 답변됩니다.
scipt (이것은 get-credentials 섹션 일 뿐이므로 여기에 포함되지 않음)에 powergui가 설치되어 있으며 아래 코드 ( “Add-PSSnapin Quest.ActiveRoles.ADManagement”줄뿐만 아니라)에 대한 요구 사항입니다. powergui의 기능이 다른지 확실하지 않지만 아무도 나에게 말할 수 없으며 작동합니다.
“domain_name”섹션에서 자신의 도메인 이름을 대체하십시오.
#Get credentials
$credential_ok = 0
while ($credential_ok -ne 1)
{
$credential = get-credential
$result = connect-qadservice -service *domain_name* -credential $credential
[string]$result_string = $result.domain
if ($result_string -eq "*domain_name*")
{
$credential_ok = 1
#authenticated
}
else
{
#failed
}
}
$username = $credential.username
$password = $credential.GetNetworkCredential().password
$date = get-date
Add-Content "c:\lbin\Install_log.txt" "Successfully authenticated XP script as $username $date"
답변
(아직) 다른 버전 :
param([string]$preloadServiceAccountUserName = "")
function HarvestCredentials()
{
[System.Management.Automation.PSCredential]$credentialsOfCurrentUser = Get-Credential -Message "Please enter your username & password" -UserName $preloadServiceAccountUserName
if ( $credentialsOfCurrentUser )
{
$credentialsOfCurrentUser = $credentialsOfCurrentUser
}
else
{
throw [System.ArgumentOutOfRangeException] "Gui credentials not entered correctly"
}
Try
{
# see https://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.path(v=vs.110).aspx
# validate the credentials are legitimate
$validateCredentialsTest = (new-object System.DirectoryServices.DirectoryEntry ("WinNT://"+$credentialsOfCurrentUser.GetNetworkCredential().Domain), $credentialsOfCurrentUser.GetNetworkCredential().UserName, $credentialsOfCurrentUser.GetNetworkCredential().Password).psbase.name
if ( $null -eq $validateCredentialsTest)
{
throw [System.ArgumentOutOfRangeException] "Credentials are not valid. ('" + $credentialsOfCurrentUser.GetNetworkCredential().Domain + '\' + $credentialsOfCurrentUser.GetNetworkCredential().UserName + "')"
}
else
{
$t = $host.ui.RawUI.ForegroundColor
$host.ui.RawUI.ForegroundColor = "Magenta"
Write-Output "GOOD CREDENTIALS"
$host.ui.RawUI.ForegroundColor = $t
}
}
Catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
$StackTrace = $_.Exception.StackTrace
$t = $host.ui.RawUI.ForegroundColor
$host.ui.RawUI.ForegroundColor = "Red"
Write-Output "Exception - $ErrorMessage"
Write-Output "Exception - $FailedItem"
Write-Output "Exception - $StackTrace"
$host.ui.RawUI.ForegroundColor = $t
throw [System.ArgumentOutOfRangeException] "Attempt to create System.DirectoryServices.DirectoryEntry failed. Most likely reason is that credentials are not valid."
}
}
Try
{
HarvestCredentials
}
Catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
$StackTrace = $_.Exception.StackTrace
$t = $host.ui.RawUI.ForegroundColor
$host.ui.RawUI.ForegroundColor = "Red"
Write-Output "Exception - " + $ErrorMessage
Write-Output "Exception - " + $FailedItem
Write-Output "Exception - " + $StackTrace
$host.ui.RawUI.ForegroundColor = $t
Break
}
Finally
{
$Time=Get-Date
Write-Output "Done - " + $Time
}
과
.\TestCredentials.ps1 -preloadServiceAccountUserName "mydomain\myusername"