Jump to content
support

Reset Linux Password (by Click Studios)

Recommended Posts

Script Name
Reset Linux Password
 
Description
SSH to Linux/Unix host and reset password
 
System Requirements

  • SSH access to the remote Host
  • Firewall allowing access

Successfully Tested Against

  • Redhat
  • Ubuntu
  • Fedora
  • Suse

Failed Testing Against

  • None reported 

PowerShell Script

<#
.SYNOPSIS
Connect to a Linux host via SSH, and change the password for an account.
#>
#------------------------------------------------------------------------------------
# Define the Read and Write Stream functions for the script to be used
#------------------------------------------------------------------------------------
function ReadStream($reader)
{
	$line = $reader.ReadLine();
	while ($line -ne $null)
	{
		$line
		$line = $reader.ReadLine()
	}
}

function WriteStream($cmd, $writer, $stream)
{
	$writer.WriteLine($cmd)
	while ($stream.Length -eq 0)
	{
		start-sleep -milliseconds 500
	}
}


#------------------------------------------------------------------------------------
# Define Cmdlet to SSH to client and execute custom script to change account password
#------------------------------------------------------------------------------------
function Set-LinuxHostPassword
{
	[CmdletBinding()]
	param (
		[String]$HostName,
		[int]$Port,
		[String]$UserName,
		[String]$OldPassword,
		[String]$NewPassword
	)
	
	#Script to be called once a SSH session has been established. Add one command per line.
	$Script = @"
    echo -e '$OldPassword\n$NewPassword\n$NewPassword' | passwd $UserName
"@
	
	try
	{
		#Make a connection to the host
		Add-Type -Path "[PasswordstateBinFolderPath]\Renci.SshNet.dll" #Include SSH.NET Assembly
		$connectionInfo = New-Object Renci.SshNet.PasswordConnectionInfo($HostName, $Port, $UserName, $OldPassword)
		$connectionInfo.Timeout = New-TimeSpan -Seconds 30
		
		$sshclient = New-Object Renci.SshNet.SshClient($connectionInfo)
		$sshclient.Connect()
		$sshclient.SendKeepAlive()
		
		if ($sshclient.IsConnected)
		{
			#Now that we are connected, attempt to execute the script above
			$stream = $sshclient.CreateShellStream("ssh_stream", 80, 24, 800, 600, 1024)
			
			$reader = new-object System.IO.StreamReader($stream)
			$writer = new-object System.IO.StreamWriter($stream)
			$writer.AutoFlush = $true
			
			while ($stream.Length -eq 0)
			{
				start-sleep -milliseconds 500
			}
			ReadStream $reader | out-null #Suppress any output so we don't capture any login banners
			
			WriteStream $Script $writer $stream
			
			#Dispose of SSH Client
			$stream.Dispose()
			$sshclient.Disconnect()
			$sshclient.Dispose()
			
			#Use a Switch statement to build up a list of exceptions to capture as required. If there is no matching exception, it is assumed the execution of the script was a success
			$results = $reader.ReadToEnd()
			switch -wildcard ($results.ToString().ToLower())
			{
				"*invalid input detected*" { Write-Output "Failed to execute script correctly against Host '$HostName' for the account '$UserName'. Error = " $results; break }
				#Add other wildcard matches here as required
				default { Write-Output "Success" }
			}
		}
		else
		{
			Write-Output "Failed to connect to the Host '$HostName' to reset the password for the account '$UserName'. Please check the Host is online, or if a Firewall is blocking access."
		}
	}
	catch
	{
		switch -wildcard ($error[0].Exception.ToString().ToLower())
		{
			"*Permission denied (password)*" { Write-Output "Failed to connect to the Host '$HostName' to reset the password for the account '$UserName'. Please check the UserName and OldPassword values passed are correct. Error = 'Permission denied (password)'."; break }
			"*failed to respond*" { Write-Output "Failed to connect to the Host '$HostName' to reset the password for the account '$UserName'. Please check the Host is online and accessible on the network."; break }
			"*Socket read operation has timed out*" { Write-Output "Failed to connect to the Host '$HostName' to reset the password for the account '$UserName'. Please check the port number for the Host is correct."; break }
			#Add other wildcard matches here as required
			default { Write-Output "Failed to reset password for account '$UserName' on Host '$HostName'. Error = " $error[0].Exception }
		}		
	}
}

#Make a call to the Set-LinuxHostPassword function
Set-LinuxHostPassword -HostName '[HostName]' -Port '[RemoteConnectionPort]' -UserName '[UserName]' -OldPassword '[OldPassword]' -NewPassword '[NewPassword]'

Share this post


Link to post
Share on other sites

For the script above to work with CentOS, you need to modify the line:

 

 echo -e '$OldPassword\n$NewPassword\n$NewPassword' | passwd $UserName

 

 

to

 

echo -e '$OldPassword\n$NewPassword\n$NewPassword' | passwd

 

Share this post


Link to post
Share on other sites

For the script above to work with CentOS, you need to modify the line:

 

 

to

 

CentOS 6.6 does ask for the CURRENT password before letting you chanage it. It does NOT allow to specify the user.

 

It should be:

 

 echo -e '$OldPassword\n$NewPassword\n$NewPassword' | passwd

 

And the script should verify that we got the proper response: "all authentication tokens updated successfully"

 

For CentOS 6.6 is at follows:

 

[test@dev ~]$ cat /etc/centos-release

CentOS release 6.6 (Final)

[test@dev ~]$ passwd

Changing password for user test.

Changing password for test.

(current) UNIX password:

New password:

Retype new password:

passwd: all authentication tokens updated successfully.

[test@dev ~]$

Share this post


Link to post
Share on other sites

Hi esteban,

 

Many thanks, and you are correct with this, so we've update the post above. We just tested this on CentOS 7 and it works fine.

 

Regards

Click Studios

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×