最近管理的一批機器,有個需求是要統一修改一個帳號的使用者名稱密碼,比如將qa帳號的密碼改為1234,後來還為了指令碼化,很方便的執行,還使用了非互動式地修改使用者的密碼。簡單記錄一下吧。
1. 互動式配置本機使用者的密碼:passwd 命令
複製代碼 代碼如下:
[root@host_221-81 ~]# passwd qa
Changing password for user qa.
New password:
BAD PASSWORD: it is too short
BAD PASSWORD: is too simple
Retype new password:
passwd: all authentication tokens updated successfully.
2. 非互動式修改本機使用者的密碼:chpasswd
複製代碼 代碼如下:
# chpasswd命令使用起來很簡潔
[root@host_221-81 ~]# echo "qa:1234" | chpasswd
# 使用passwd命令,也可以實現非互動式修改密碼
[root@host_221-81 ~]# echo "1234" | passwd --stdin "qa"
Changing password for user qa.
passwd: all authentication tokens updated successfully.
3. 使用expect來處理互動式輸入,從而實現非互動密碼修改。
複製代碼 代碼如下:
#!/bin/sh
# \
exec expect -f "$0" "$@"
if { $argc != 2 } {
puts "Usage: $argv0 <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
注意:指令碼的第二行,這種寫法可能比較陌生,這是在TCL語言中的文法,The backslash is recognized as part of a comment to sh, but in Tcl the backslash continues the comment into the next line which keeps the exec command from executing again.
該指令碼的執行結果為:
複製代碼 代碼如下:
[root@smilejay ~]# ./change-pwd-expect.sh qa 1234
spawn passwd qa
Changing password for user qa.
New password:
BAD PASSWORD: it is too short
BAD PASSWORD: is too simple
Retype new password:
passwd: all authentication tokens updated successfully.