Verify domain credentials at command line - windows

Is there a windows command that will allow me to verify a domain account/password?

You could use the command RUNAS, it is not technically a commandline to validate credentials, but it CAN be used for that.
runas /noprofile /user:mycomputer\administrator "notepad"
If it fails it returns:
RUNAS ERROR: Unable to run - notepad
1326: Logon failure: unknown user name or bad password.

RUNAS works great on a local system.
To verify credentials on a remote computer, I use the PSExec tool from SysInternals. I specify the username, then it prompts me for the password. Here is an example of what my command looks like:
psexec \\RemoteComputer -u DOMAIN\USER cmd.exe
If I enter the correct password, I'll be greeted with a command prompt. If I enter the wrong password, I get this:
PsExec could not start cmd.exe on RemoteComputer:
The user name or password is incorrect.

You can use this powershell script which does some extra testing (domain reachable, user name exists, account enabled, account unlocked).
Got this script from this post. Put this in a notepad, save as .ps1 and execute. It will prompt for credentials and provide feedback. Worked perfectly for my needs.
<#
.SYNOPSIS
Test domain username/password combination are correct
.DESCRIPTION
This script will check if the password for a given username is correct. If the authentication failed using the provided Domain\Username and Password.
The script will do some checks and provide some clues why the authentication failed.
The checks are:
* Domain is reachable.
* User Name exists in the domain.
* The account is Enabled.
* The account is Unlocked.
.EXAMPLE
.\Test-UserCredentials.ps1
or
Right click the script and select "Run with PowerShell"
.Notes
Created by: Ibrahim Soliman
Version: 1.6 (Enhanced error handling, and authentication failure root cause analysis.)
#>
#Import Active Directory Module
Import-Module Activedirectory
#Clear User Info Function
Function ClearUserInfo
{
$Cred = $Null
$DomainNetBIOS = $Null
$UserName = $Null
$Password = $Null
}
#Rerun The Script Function
Function Rerun
{
$Title = "Test Another Credentials?"
$Message = "Do you want to Test Another Credentials?"
$Yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Test Another Credentials."
$No = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "End Script."
$Options = [System.Management.Automation.Host.ChoiceDescription[]]($Yes, $No)
$Result = $host.ui.PromptForChoice($Title, $Message, $Options, 0)
Switch ($Result)
{
0 {TestUserCredentials}
1 {"End Script."}
}
}
#Test User Credentials Function
Function TestUserCredentials
{
ClearUserInfo
#Get user credentials
$Cred = Get-Credential -Message "Enter Your Credentials (Domain\Username)"
if ($Cred -eq $Null)
{
Write-Host "Please enter your username in the form of Domain\UserName and try again" -BackgroundColor Black -ForegroundColor Yellow
Rerun
Break
}
#Parse provided user credentials
$DomainNetBIOS = $Cred.username.Split("{\}")[0]
$UserName = $Cred.username.Split("{\}")[1]
$Password = $Cred.GetNetworkCredential().password
Write-Host "`n"
Write-Host "Checking Credentials for $DomainNetBIOS\$UserName" -BackgroundColor Black -ForegroundColor White
Write-Host "***************************************"
If ($DomainNetBIOS -eq $Null -or $UserName -eq $Null)
{
Write-Host "Please enter your username in the form of Domain\UserName and try again" -BackgroundColor Black -ForegroundColor Yellow
Rerun
Break
}
# Checks if the domain in question is reachable, and get the domain FQDN.
Try
{
$DomainFQDN = (Get-ADDomain $DomainNetBIOS).DNSRoot
}
Catch
{
Write-Host "Error: Domain was not found: " $_.Exception.Message -BackgroundColor Black -ForegroundColor Red
Write-Host "Please make sure the domain NetBios name is correct, and is reachable from this computer" -BackgroundColor Black -ForegroundColor Red
Rerun
Break
}
#Checks user credentials against the domain
$DomainObj = "LDAP://" + $DomainFQDN
$DomainBind = New-Object System.DirectoryServices.DirectoryEntry($DomainObj,$UserName,$Password)
$DomainName = $DomainBind.distinguishedName
If ($DomainName -eq $Null)
{
Write-Host "Domain $DomainFQDN was found: True" -BackgroundColor Black -ForegroundColor Green
$UserExist = Get-ADUser -Server $DomainFQDN -Properties LockedOut -Filter {sAMAccountName -eq $UserName}
If ($UserExist -eq $Null)
{
Write-Host "Error: Username $Username does not exist in $DomainFQDN Domain." -BackgroundColor Black -ForegroundColor Red
Rerun
Break
}
Else
{
Write-Host "User exists in the domain: True" -BackgroundColor Black -ForegroundColor Green
If ($UserExist.Enabled -eq "True")
{
Write-Host "User Enabled: "$UserExist.Enabled -BackgroundColor Black -ForegroundColor Green
}
Else
{
Write-Host "User Enabled: "$UserExist.Enabled -BackgroundColor Black -ForegroundColor RED
Write-Host "Enable the user account in Active Directory, Then check again" -BackgroundColor Black -ForegroundColor RED
Rerun
Break
}
If ($UserExist.LockedOut -eq "True")
{
Write-Host "User Locked: " $UserExist.LockedOut -BackgroundColor Black -ForegroundColor Red
Write-Host "Unlock the User Account in Active Directory, Then check again..." -BackgroundColor Black -ForegroundColor RED
Rerun
Break
}
Else
{
Write-Host "User Locked: " $UserExist.LockedOut -BackgroundColor Black -ForegroundColor Green
}
}
Write-Host "Authentication failed for $DomainNetBIOS\$UserName with the provided password." -BackgroundColor Black -ForegroundColor Red
Write-Host "Please confirm the password, and try again..." -BackgroundColor Black -ForegroundColor Red
Rerun
Break
}
Else
{
Write-Host "SUCCESS: The account $Username successfully authenticated against the domain: $DomainFQDN" -BackgroundColor Black -ForegroundColor Green
Rerun
Break
}
}
TestUserCredentials
ClearUserInfo

Related

Test-path to local user profile folder path is returning true even after user profile is deleted. And there is no user folder present

Deleting User profile
$UserFolderPath1 = "\$Server\C$\Users\$UserName"
Try {
(Get-WmiObject -ComputerName $Server Win32_UserProfile | Where-Object {$_.LocalPath -eq "C:\Users\$UserName"}).Delete()
Write-Host -ForegroundColor Green "$UserName has been deleted from $Server"
} Catch [System.Management.Automation.MethodInvocationException]{
Write-Host -ForegroundColor Red "ERROR: Profile is currently locked on $Server "
} Catch [System.Management.Automation.RuntimeException] {
Write-Host -ForegroundColor Yellow -BackgroundColor Blue "INFO: $UserName Profile does not exist on $host"
} Catch {
Write-Host -ForegroundColor Red "ERROR: an unknown error occoured. The error response was $($error[0])"
}
User folder is deleted but test-path c:\users\userprofilefolder is still showing as true
if(test-path "$UserFolderPath1"){
Write-host "user folder found"
Get-ChildItem $UserFolderPath1 -Recurse | Remove-Item -recurse -Force
Remove-Item $UserFolderPath1 -Force
}

Is there a way to check if a PFX cert is currently imported without getting the password

I have the following script to install a PFX file:
$cert = Get-ChildItem -Path .\secrets\certificates\ssl\certificate.pfx
while($true){
write-host "Enter Password" -foregroundcolor yellow
try{
$pass = read-host -AsSecureString
$cert | Import-PfxCertificate -CertStoreLocation Cert:\CurrentUser\My `
-Exportable `
-Password $pass
break
}catch{
write-host "Incorrect password" -foregroundcolor red
continue
}
}
write-host "Certificate installed" -foregroundcolor green
However I would like to be able to run the install script again and if the cert is already installed then I don't want to ask the user once again to look up the password. It is tedious.
Is there a way to check if a PFX file has already been imported without asking for the password? Then I could change my code to
function Is-PfxInstalled($cert) {
// ???????
}
$cert = Get-ChildItem -Path .\secrets\certificates\ssl\certificate.pfx
if(!($cert | Is-Pfx-Installed)
{
while($true){
write-host "Enter Password" -foregroundcolor yellow
try{
$pass = read-host -AsSecureString
$cert | Import-PfxCertificate -CertStoreLocation Cert:\CurrentUser\My `
-Exportable `
-Password $pass
break
}catch{
write-host "Incorrect password" -foregroundcolor red
continue
}
}
write-host "Certificate installed" -foregroundcolor green
}
If you know the thumbprint of the certificate, you can use the Test-Path cmdlet to check whether the certificate is installed.
Note: I renamed your function to Test-CertificateIsInstalled since Test is an approved verb:
function Test-CertificateIsInstalled
{
Param
(
[string]$Thumbprint,
[string]$Location = 'Cert:\CurrentUser\My\'
)
Test-Path (Join-Path $Location $Thumbprint)
}
The function uses Cert:\CurrentUser\My as the default location, but you can specify a different one. Usage example:
Test-CertificateIsInstalled 007790F6561DAD89B0BCD85585762495E358F8A2

Check server before starting service

I need to edit a script. There is a service that is on two Windows Server 2008 R2. They are load balanced. I need it so when I run the script that starts the service on the primary server and the secondary, so before it even start the service on both servers, the goes out and checks to ensure the primary server is up and running, then continues on as normal to start the services on both servers.
# Start Appian
function StartAppian {
$APNSVC = Get-Service -Name $AppianService
if (!$APNSVC) {
Write-Host "Appian Service does not exist"
return
}
# Check to see if Appian's service is already started
if ($APNSVC.Status -eq "Running") {
if ($LB) {
if ($MULEAPNSVC.Status -eq "Running") {
Write-Host "Appian Service on the Load Balanced Server already is started!" -ForegroundColor Yellow
return
}
}
Write-Host "Appian Service already is started!" -ForegroundColor Yellow
Read-Host "Press any key to return"
return
}
# Check if DEV's Process Design has a writing_*.kdb file and delete it
if ($Server -eq "DEV") {
#gw1
if (Test-Path $APPIAN_HOME\server\process\design\gw1\writing_*.kdb) {
Write-Host "Removing writing_*.kdb from GW1" -ForegroundColor Yellow
Remove-Item $APPIAN_HOME\server\process\design\gw1\writing_*.kdb
}
#gw2
if (Test-Path $APPIAN_HOME\server\process\design\gw2\writing_*.kdb) {
Write-Host "Removing writing_*.kdb from GW2" -ForegroundColor Yellow
Remove-Item $APPIAN_HOME\server\process\design\gw2\writing_*.kdb
}
}
Write-Host "Starting Appian"
# Place the name of the service here to start for Appian
Start-Service $AppianService
Notify("StartAppian")
if ($LB) {
(Get-Service $MULEAPNSVC.Name -ComputerName $MULE).Start()
Write-Host "Starting Mule's Appian" -ForegroundColor Magenta
}
cmd.exe "/C $APPIAN_HOME\server\_scripts\diagnostic\checkengine.bat -s > $logdir\Startup.log"
# These lines check the Startup log for fatals and errors at the beginning
$fatals = Select-String FATAL $logdir\Startup.log
$errs = Select-String ERROR $logdir\Startup.log
# Check for errors and fatals again
$fatals = Select-String FATAL $logdir\Startup.log
$errs = Select-String ERROR $logdir\Startup.log
Write-Host "Still warnings or Errors in CE" -ForegroundColor Yellow
# Increment times
$times = $times + 1
# If times > threshold, email out error message
if ($times -gt $threshold) {
SendAlert("There is a problem with Appian - It won't start")
Write-Host "There was a problem with Appian..it took too long to start - emailing alert" -ForegroundColor Red
Read-Host "Press any key to exit"
}
}
Write-Host "Appian Started" -ForegroundColor Green
Read-Host "Press any key to return"
}
You can do that with a simple Test-Connection at the start of the script.
if ($ping = Test-Connection -ComputerName PrimaryServerName -Quiet) {
Write-Host "Host avalible"
}
else {
Write-Host "Host unavalible"
Exit
}
any other suggestions?
if (Test-Connection ServerName -Count 1 -Quiet) {
Write-Host "Host avalible"
}
else {
Write-Host "Host unavalible"
Exit
}
this doesnt work. I want it to test the if the server is up or not, if its not, exit the script, if it is, continue on with the script. When testing this on ISE it work, but when i launch the script it doesn't

How to prevent words from being removed [duplicate]

This question already has answers here:
What is the difference between combining paths in those 2 ways?
(2 answers)
Closed 6 years ago.
I'm running into a small problem where I have to require the user to NOT put a backslash "\" in the folder name because it removes the server name when I combine $Server and $Parent... How do I prevent that from happening? I'd rather not restrict my user from adding that backslash...
Also, I've been trying to prevent c:, d:, e:, etc. drives from being used in $Parent, but even if I use -in or -contains it still allows the c:\xxxx or d:\xxxx to be entered. How do I prevent that?
# File share server name
$Server = Read-Host -prompt "Verify Server Server Name (ie ECCOFS01)"
If ([string]::IsNullOrWhiteSpace($Server)) {
Write-Host "You entered $Server which is an incorrect value: This Script is now Exiting." -Foreground "White" -Background "Red"
Exit
}
else {
Write-Host "You Entered $Server" -Foreground "Black" -Background "Yellow"
}
# Parent folder setup
$Parent = Read-Host -prompt "Enter full parent path that will contain the new folder(ie. Groups\ECCO IT) - Do NOT start with \. Please use correct spelling and capitalization (ie. Parent Folder Name). "
If ([string]::IsNullOrWhiteSpace($Parent) -or ($Parent -eq "c:") -or ($Parent -eq "d:")) {
Write-Host "You entered $Parent which is an incorrect value: This Script is now Exiting." -Foreground "White" -Background "Red"
Exit
}
else {
Write-Host "You Entered $Parent" -Foreground "Black" -Background "Yellow"
}
$ServerParentShare = "\\"+[IO.Path]::Combine($Server,$Parent)
# New Folder Name
$Name = Read-Host -prompt "Enter New Folder Name. Please use correct spelling and capitalization (ie. New Test Folder)"
If ([string]::IsNullOrWhiteSpace($Name)) {
Write-Host "You entered $Name which is an incorrect value: This Script is now Exiting." -Foreground "White" -Background "Red"
Exit
}
else {
Write-Host "You Entered $Name." -Foreground "Black" -Background "Yellow"
}
$Path = [IO.Path]::Combine($ServerParentShare,$Name)
Write-Host = "New Folder Path = $Path" -Foreground "Black" -Background "Yellow"
# Choose parent OU
$Country = Read-Host -prompt "Enter the Country OU that the Security Group will reside in (i.e. Global, Americas, Europe, Asia Pacific)"
If ([string]::IsNullOrWhiteSpace($Country)) {
Write-Host "You entered $Country which is an incorrect value: This Script is now Exiting." -Foreground "White" -Background "Red"
Exit
}
else {
Write-Host "---------------------VERIFY ENTRY---------------------" -Foreground "Black" -Background "Yellow"
Write-Host "OU = $Country, New share location = $Path" -Foreground "Black" -Background "Yellow"
}
# Option to continue or cancel the script
$Continue = Read-Host -prompt "Does this look correct? Y or N?"
If (($Continue -eq "N") -or ($Continue -eq "No")) {
Write-Host "Please Start over. This Script is now Exiting." -Foreground "White" -Background "Red"
Exit
}
else {
Write-Host "Make sure to verify all folders and and AD Groups once complete." -Foreground "Yellow" -Background "Black"
}
I have to require the user to NOT put a backslash "\" in the folder name
insert this line after line 12:
$parent = $parent -replace '^\\',''
if $parent contains a backslash at position 0, it will replace it with an empty string. if not, it has no effect.
PS C:\> '\a\b' -replace '^\\',''
a\b
PS C:\> 'a\b' -replace '^\\',''
a\b
PS C:\>
technically this doesn't prevent the user from putting a backslash in the folder name, but if he/she does, it will remove it, which has a similar effect.
I've been trying to prevent c:, d:, e:, etc. drives from being used in
$Parent, but even if I use -in or -contains it still allows
-in and -contains operate on collections, not a single object (like $parent). for $parent, you probably want to use -like or -match. you can check for a drive letter-formatted path like this:
($parent -like '?:*')
or you can just look for a colon in the path
($parent -like '*:*')
you can use either of those conditionals in a while loop, forcing the user to keep inputting until he/she inputs the format you want. or you can just exit if the input is invalid. put it all together, for example:
do{
$parent = read-host -prompt 'Enter full parent path'
$parent = $parent -replace '^\\',''
}while($parent -like '*:*')

sc.exe config "Service Name" obj= "DOMAIN\User" password= "password" not working

I want to set password for a service from the cmd. I got the option
sc.exe config "Service Name" obj= "DOMAIN\User" password= "password"
When I execute, its showing "[SC] ChangeServiceConfig SUCCESS"
and if I start the service
I am getting
"Windows could not start the service1 service on Local Computer.
Error 1069: The service did not start due to a logon failure."
I searched and got the below link
Using SC.exe to set service credentials password fails
My password doesn't consist of special character.
What's the option to do that?
The first thing to check is if that user has permission to Log On As A Service in that machine. If he does (and you can do the following procedure to check this), just go to the service (Start Menu - type "services", without the quotes). Find your service on the list, and right-click on it. Select "Properties", and go to the "Log On" tab. Retype the "Password" and "Confirm password". Click OK. If your user DOES have permission to Log On as a Service, a message "The account YourDomain\YourUser has been granted the Log On As a Service right". Just try to start the service again, and it will work.
If your user does not have this kind of permission, you can use one of these two approaches:
1) Start menu - type "local security policy" without the quotes. Open the "Local Policies", then left-click on "User Rights Assignment". On the right panel, right-click on "Log on as a service", and select "Properties". Click on "Add User or Group" and add your user. Click OK. You might have to reboot your machine.
2) Download and install the "Windows Server 2003 Resource Kit Tools" (http://www.microsoft.com/en-us/download/confirmation.aspx?id=17657). Open a command prompt and type:
ntrights +r SeServiceLogonRight -u MyDomain\MyUser -m \\%COMPUTERNAME%
Reboot your computer and try to start the service again.
After your user has been granted the Log On As A Service right, you can create and start services through the command line.
If you face The account YourDomain\YourUser has been granted the Log On As a Service right, you should execute powershell script link
AddLogonasaService and this is nothing to do with your password. It's a right/permission for an user to run the service.
Am embedding the code for your reference. You can refer that URL as well.
param($accountToAdd)
#written by Ingo Karstein, http://blog.karstein-consulting.com
# v1.0, 01/03/2014
## <--- Configure here
if( [string]::IsNullOrEmpty($accountToAdd) ) {
Write-Host "no account specified"
exit
}
## ---> End of Config
$sidstr = $null
try {
$ntprincipal = new-object System.Security.Principal.NTAccount "$accountToAdd"
$sid = $ntprincipal.Translate([System.Security.Principal.SecurityIdentifier])
$sidstr = $sid.Value.ToString()
} catch {
$sidstr = $null
}
Write-Host "Account: $($accountToAdd)" -ForegroundColor DarkCyan
if( [string]::IsNullOrEmpty($sidstr) ) {
Write-Host "Account not found!" -ForegroundColor Red
exit -1
}
Write-Host "Account SID: $($sidstr)" -ForegroundColor DarkCyan
$tmp = [System.IO.Path]::GetTempFileName()
Write-Host "Export current Local Security Policy" -ForegroundColor DarkCyan
secedit.exe /export /cfg "$($tmp)"
$c = Get-Content -Path $tmp
$currentSetting = ""
foreach($s in $c) {
if( $s -like "SeServiceLogonRight*") {
$x = $s.split("=",[System.StringSplitOptions]::RemoveEmptyEntries)
$currentSetting = $x[1].Trim()
}
}
if( $currentSetting -notlike "*$($sidstr)*" ) {
Write-Host "Modify Setting ""Logon as a Service""" -ForegroundColor DarkCyan
if( [string]::IsNullOrEmpty($currentSetting) ) {
$currentSetting = "*$($sidstr)"
} else {
$currentSetting = "*$($sidstr),$($currentSetting)"
}
Write-Host "$currentSetting"
$outfile = #"
[Unicode]
Unicode=yes
[Version]
signature="`$CHICAGO`$"
Revision=1
[Privilege Rights]
SeServiceLogonRight = $($currentSetting)
"#
$tmp2 = [System.IO.Path]::GetTempFileName()
Write-Host "Import new settings to Local Security Policy" -ForegroundColor DarkCyan
$outfile | Set-Content -Path $tmp2 -Encoding Unicode -Force
#notepad.exe $tmp2
Push-Location (Split-Path $tmp2)
try {
secedit.exe /configure /db "secedit.sdb" /cfg "$($tmp2)" /areas USER_RIGHTS
#write-host "secedit.exe /configure /db ""secedit.sdb"" /cfg ""$($tmp2)"" /areas USER_RIGHTS "
} finally {
Pop-Location
}
} else {
Write-Host "NO ACTIONS REQUIRED! Account already in ""Logon as a Service""" -ForegroundColor DarkCyan
}
Write-Host "Done." -ForegroundColor DarkCyan
To set the identity for services, I have used a vbscript
Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name = 'Servicename'")
For Each objservice in colServiceList
errReturn = objService.Change( , , , , , ,WScript.Arguments.Item(0), WScript.Arguments.Item(1))
objService.StartService()
Next
Where WScript.Arguments.Item(0) is the username arg and WScript.Arguments.Item(1) is password.
Probably the issue is that it doesn't want quotes around the password. Same goes for the username.
It perhaps cannot tell whether the quotes are part of the password or not.
Alternatively it may be because the given account has not been granted the "log on as a service" privilege.
Generally you should check the Security event log, which will give the reason for the logon failure.
This worked for me:
sc.exe stop "<my_service>" 4:4:3
sc.exe config "<my_service>" obj= "./<local_acc_name>" password= "<local_acc_pass>"
sc.exe start "<my_service>"
So, in short:
stop the service before config the password and the start will work fine.

Resources