Using Expect Command To Automate User Creation on RHEL 6

Many a time my job requires me to add a number of users on a number of servers. The task can soon become painful once the number increases 😦

Thankfully, we have an amazing utility called Expect. Below is how I used Expect to automate user creation task. 🙂 This is basically a small script with self-explanatory tokens. I am also trying to incorporate a for /while loop so as to fully automate this task. This script is ideal for multiple users with same password.

#!/usr/bin/expect -f
#The script uses 2 arguments. user_name & password. Checking this condition.
if {[llength $argv] != 2} {
puts "usage: expect ./ user_name Password"
exit 1
set user [lindex $argv 0] #set user variable. Using first argument as username.
set pass [lindex $argv 1] #set password variable. Using second argument as username.
spawn useradd $user
puts "$user added" #print a message
expect "?server \r"
spawn passwd $user
expect "?Changing password for user $user. \r"
send "$pass\r"
expect "?Retype new password: \r"
send "$pass\r"
expect eof
puts "Password for $user set."

Below is the output 🙂

[shashank@server scripts]$ sudo expect ./ test4 Password
spawn useradd test4
test4 added
spawn passwd test4
Changing password for user test4.
New password:
BAD PASSWORD: it is based on a dictionary word
Retype new password:
passwd: all authentication tokens updated successfully.
Password for test4 set.

2 thoughts on “Using Expect Command To Automate User Creation on RHEL 6

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s