SCRIPT:
#!/usr/bin/expect
set username "sv111111"
set password "Sandy789"
set f [open "servers.txt"]
set hosts [split [read $f] "\n"]
close $f
foreach host $hosts {
#spawn ssh -o StrictHostKeyChecking=no $username@$hosts
spawn ssh $username@$host
expect "$username@$host's password:"
send -- "$password\n"
expect "$"
send -- "sudo -u sandy /opt/sandy/ship/common/tools/arpq.sh\n"
expect "$username@$host's password:"
send -- "$password\n"
expect "$"
send -- "sudo -u sandy /opt/sandy/ship/common/tools/showps2.pl\n"
expect "$"
send -- "exit\n"
expect eof
close
}
在上面的脚本中,它完美地运行了servers.txt文件中提到的所有服务器的第一个sudo命令。第二个sudo命令没有执行,它显示以下错误。
spawn ssh sv111111@
ssh: : Name or service not known
send: spawn id exp10 not open
while executing
"send -- "$password\n""
("foreach" body line 5)
invoked from within
"foreach host $hosts {
#spawn ssh -o StrictHostKeyChecking=no $username@$hosts
spawn ssh $username@$host
expect "$username@$host's password:"
send -- ..."
(file "./sandy_try.sh" line 8)
请帮助
答案 0 :(得分:0)
read
命令使用尾随换行符获取文件内容。然后,当您在换行符上拆分时,列表中有一个空字符串的尾随元素。使用其中一个:
set f [open "servers.txt"]
set hosts [split [read -nonewline $f] "\n"]
# .....................^^^^^^^^^^
close $f
foreach host $hosts { ...
或
set f [open "servers.txt"]
while {[gets $f host] != -1} {
spawn ssh ...
}
close $f