Monday, 28 November 2016

Setting the password non-interactively in Linux using bash shell


Manually resetting passwords of a large chunk of users is a painfully boring task & is definitely not the best use of our time. In this article I'll share just a couple of methods of somewhat automate this process. So here we go!

Method 1: use chpasswd
Using chpasswd we can set or reset login passwords for many users non-interactively. WE just need to add the username & password in a text file in the form of a key-value pair & serve the resultant text file as input to chpasswd command & our work is done. Here's a demo:

I've created a user named testuser & I want to set its password to 123. So, I've added the key-value pair in a text file shown below:

[root@centops ~]# cat pass.txt
testuser:123
[root@centops ~]#

Now we just need to feed it to chpasswd.

[root@centops ~]# chpasswd <pass.txt


Method 2: use stdin
This is another simple method wherein we echo out the password to passwd <user name> command via --stdin. Here's an example:

[root@centops ~]# echo "456"  | passwd testuser --stdin
Changing password for user testuser.
passwd: all authentication tokens updated successfully.


Method 3: use expect
Expect is an awesome tool for supplying input to interactive programs to automate them. Here's the expected expect code to accomplish a non-interactive password reset:

#!/usr/bin/expect

set timeout 10

set user [lindex $argv 0]

set password [lindex $argv 1]

spawn passwd $user

expect "password:"
send "$password\r"
expect "password:"
send "$password\r"

expect eof


The test looks like this:

# ./e3.sh testuser 123

spawn passwd testuser
Changing password for user testuser.
New password:
BAD PASSWORD: it is WAY too short
BAD PASSWORD: is too simple
Retype new password:
passwd: all authentication tokens updated successfully.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...