Expect脚本中兼容有密码和无密码的Shell操作
问题由来
在持续集成过程中,我们使用expect脚本来实现软件参数修改和自动部署。有些平台不能使用root用户直接操作,但是给部署用户分配了sudo权限。使用中发现,第一次登陆系统更改文件的时候有密码,但是第二次再次修改文件的时候就不需要密码。所以需要考虑一个兼容这2种情况的实现方法。
示例代码
```bash
#!/usr/bin/expect
set argc [ llength $argv ]
set user [ exec whoami ]
set timeout -1
set username [lindex $argv 0]
set password [lindex $argv 1]
set remoteIP [lindex $argv 2]
if { "$username" == "root" } {
set expChar "# "
} else {
set expChar "$ "
}
spawn ssh -p 22 $username@$remoteIP
while 1 {
expect {
"(yes/no)?" {
send "yes\n"
continue
}
"password: " {
send "$password\n"
break
}
}
}
expect $expChar
send "cd /etc\n"
expect $expChar
send "sudo sed -i '2a list1\\nlist2\\nlist3' ntp.conf\n"
expect {
#这里会弹出提示,输入密码:
":" {
send "$password\n"
expect $expChar
}
#这里不用输入密码,就什么也不干
$expChar {
}
}
send "sudo sed -i '3,4d' ntp.conf\n"
expect {
#这里会弹出提示,输入密码:
":" {
send "$password\n"
expect $expChar
}
#这里不用输入密码,就什么也不干
$expChar {
}
}
send "exit\n"
``
这里做个记录吧。