Recently, the Linux batch execution of the script is very interested in looking around the Internet for expect batch execution script, today to share a batch password modification script.
Script content:
Copy Code code as follows:
#!/usr/bin/expect
If {$ARGC <2} {
Send_user "Usage: $argv 0 Exit
}
# machine List data format: IP port old password new password
Set hostfile [Open [lindex $argv 0]]
# command List data format: A single command line
Set cmdfile [Open [lindex $argv 1]]
# data file delimiter, default to Space
Set part "\"
# Filter Keywords
Set Key_password "Password:\ "
Set Key_init "\ (yes/no\) \?\"
Set key_confirm "' Yes ' \ or\ ' no ': \ "
Set Key_ps "*]#\"
Set Key_newpassword "UNIX password:\ "
Set Timeout 30
Log_file./exprct.log
Match_max 20480
While {[gets $hostfile _hosts_] >= 0} {
Set hosts [string trim $_hosts_]
Set Str_index [string $part $hosts]
Set host [string trim [String range $hosts 0 $str _index]]
Set TEMP [string trim [String range $hosts [expr $str _index + 1] [string length $hosts]]]
Set Str_index [string $part $temp]
If {$str _index = = 1} {
Set Port 22
Set Pass $temp
Set Newpass $temp
} else {
Set port [string trim [String range $temp 0 $str _index]]
Set Temp_pass [string trim [String range $temp [expr $str _index + 1] [string length $temp]]]
Set Str_index [string $part $temp _pass]
Set pass [string trim [string range $temp _pass 0 $str _index]]]
Set newpass [string trim [String range $temp _pass [expr $str _index + 1] [string length $temp _pass]]]
}
Spawn Ssh-p $port $host
While {1} {
Expect {
"$key _password" {
Send "$pass \ r"
}
"$key _init" {
Send "yes\r"
}
"$key _confirm" {
Send "yes\r"
}
"$key _ps" {
While {[gets $cmdfile cmd] >= 0} {
Send "$cmd \ r"
Expect {
"$key _ps" {
Continue
}
"$key _newpassword" {
Send "$newpass \ r"
Expect "$key _newpassword" {
Send "$newpass \ r"
Expect "$key _ps"
Continue
}
}
}
}
Seek $cmdfile 0 start
Send_user "\ r"
Break
}
Timeout {
Puts "$host timeout\n"
Break
}
}
}
Send "exit\r"
Close
Wait
}
Close $hostfile
Close $cmdfile
Exit