我正在尝试将一个expect脚本实现为一个bash脚本。因为我对bash / expect很新,所以请耐心等待。
以下是期望脚本按预期工作:
log_user 0
file delete foo.txt
set fh [open foo.txt a]
set servers {xxx@server1 xxx@server2}
foreach s $servers {
spawn ssh $s
expect "password: "
send "PASSWORD\r"
expect "$ "
send "grep "something" /some/log/file.log"
expect "$ " { puts $fh "$expect_out(buffer)"}
send "exit\r"
}
close $fh
现在,我希望将这个expect脚本包含在bash脚本中,但它不能按预期工作。
这是我到目前为止所做的:
#!/bin/bash
XYZ=$(expect -c "
file delete foo.txt
set fh [open foo.txt a]
set servers {xxx@server1 xxx@server2}
foreach s $servers {
spawn ssh $s
expect "password: "
send "PASSWORD\r"
expect "$ "
send "grep "something" /some/log/file.log"
expect "$ " { puts $fh "$expect_out(buffer)"}
send "exit\r"
}
close $fh
")
echo "$XYZ"
我得到的错误是:
command substitution: line 42: syntax error near unexpected token `('
command substitution: line 42: `expect "$ " { puts $fh "$expect_out(buffer)"}'
我愿意接受任何其他方式来实现这一点! :)
答案 0 :(得分:2)
您可以使用/usr/bin/expect -c
执行expect
命令:
#!/bin/bash
/usr/bin/expect -c '
file delete foo.txt
set fh [open foo.txt a]
set servers {xxx@server1 xxx@server2}
foreach s $servers {
spawn ssh $s
expect "password: "
send "PASSWORD\r"
expect "$ "
send "grep "something" /some/log/file.log"
expect "$ " { puts $fh "$expect_out(buffer)"}
send "exit\r"
}
close $fh
'
答案 1 :(得分:0)
Bertrand的回答是解决问题的一种方法,但并没有解释你正在做的事情的问题。
Bash尝试在双引号字符串中扩展变量,因此您的expect
脚本会看到您要查看$servers
,$s
和$fh
的空格。此外,你有三层嵌套的双引号字符串,这将导致解析expect
的参数时出现各种问题。
这是一个意见问题,但我认为当某些事情被某个特定点视为自己的程序时,它应该被分成一个单独的文件。
#!/usr/bin/expect
log_user 0
file delete foo.txt
set fh [open foo.txt a]
set servers {xxx@server1 xxx@server2}
foreach s $servers {
spawn ssh $s
expect "password: "
send "PASSWORD\r"
expect "$ "
send "grep 'something' /some/log/file.log"
expect "$ " {
puts $fh "$expect_out(buffer)"
}
send "exit\r"
}
close $fh
确保它是可执行的,然后从bash
脚本中调用它:
#!/bin/bash
/usr/local/bin/my_expect_script
(为了做到这一点,你应该设置公钥认证,然后通过直接从bash运行ssh server "grep 'something' /some/log/file.log"
来完全摆脱期望