最近管理的一批機器,有個需求是要統一修改一個帳號的用戶名密碼,比如將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.