Recently managed a number of machines, there is a need to unify the change of an account username password, such as the QA account password changed to 1234, and later for scripting, very convenient implementation, but also used to modify the user's password non-interactive. Simply record it.
1. Interactively configure the local user's password:passwd command
Copy Code code as follows:
[Root@host_221-81 ~]# passwd QA
Changing password for user QA.
New Password:
Bad password:it are too short
Bad Password:is too simple
Retype new Password:
Passwd:all authentication tokens updated successfully.
2. Non-interactive change password for local User:chpasswd
Copy Code code as follows:
# CHPASSWD commands are simple to use
[Root@host_221-81 ~]# echo "qa:1234" | chpasswd
# using the passwd command, you can also implement a non-interactive password change
[Root@host_221-81 ~]# echo "1234" | passwd--stdin "QA"
Changing password for user QA.
Passwd:all authentication tokens updated successfully.
3. Use expect to process interactive input, which enables non-interactive password modifications.
Copy Code code as follows:
#!/bin/sh
# \
EXEC expect-f "$" "$@"
If {$ARGC!= 2} {
Puts "Usage: $argv 0 <username> <passwd>"
Exit 1
}
Set password [lindex $argv 1]
Spawn passwd [lindex $argv 0]
Sleep 1
Expect "Assword:"
Send "$password \ r"
Expect "Assword:"
Send "$password \ r"
Expect EOF
Note: The second line of the script, which may be unfamiliar, is the syntax in the TCL language, the backslash is recognized as part of a comment to sh, but in Tcl the backslash Continu Es the comment into the next line which keeps the EXEC command from executing again.
The execution result of the script is:
Copy Code code as follows:
[Root@smilejay ~]#./change-pwd-expect.sh QA 1234
Spawn passwd QA
Changing password for user QA.
New Password:
Bad password:it are too short
Bad Password:is too simple
Retype new Password:
Passwd:all authentication tokens updated successfully.