cat login.expect
#!/usr/bin/expect
# expect 接受命令通过这种方式传进来
set HOSTNAME [lindex $argv 0]
set USERNAME [lindex $argv 1]
set PASSWORD [lindex $argv 2]
set CMD [lindex $argv 3]#设置永不超时
set timeout -1#具体的命令内容
spawn ssh $USERNAME@$HOSTNAME# 根据上一步命令返回的内容进行匹配
expect {
#如果是yes/no 就直接输入yes并换行继续"yes/no" {
send "yes\r"; exp_continue}"Permission denied," {
exit }"password:" {
send "$PASSWORD\r" ; exp_continue}" ~]"
}
send "$CMD\r"
expect {
"sudo] password for" {
send "$PASSWORD\r"; exp_continue}" ~]"
}
send "exit\r"
expect eof
exit
expect login.expect 192.168.2.10 root root@123 "sudo sh -c \"echo user1 ALL=\(ALL\) NOPASSWD: ALL >> /etc/sudoers\""