在shell脚本中使用Expect [英] use expect in shell script
问题描述
我需要传递两个参数,第一个是要执行的命令,第二个是密码.
I need to pass two arguments to expect, first one is the command to execute, the second one is the password.
这是我的期望.sh
#!/usr/bin/expect
spawn [lrange $argv 0 0]
expect "password:"
send [lindex $argv 1]
interact
主脚本:
./expect.sh "ssh root@$SERVER1" $SERVER1_PASS
错误:
couldn't execute "{ssh root@xxx.xxx.xx.xxx}": no such file or directory
while executing
"spawn [lrange $argv 0 0]"
(file "./expect.sh" line 2)
为什么?
推荐答案
据我所知,spawn的第一个参数必须是字符串,而不是字符串列表.
As far as I can tell, spawn's first argument needs to be a string, not a list of string.
尝试将多字命令行作为单个字符串传递将导致问题.我认为您必须在调用spawn之前先对空格进行拆分,并且如果一个参数包含空格,那将会中断.也许最好将密码指定为第一个参数,然后将命令指定为其余参数.
And trying to pass a multi-word command line as a single string is going to cause problems. I think you'd have to split on spaces before calling spawn, and that's going to break if one argument contains a space. Maybe it's better to specify the password as the first argument, and the command as the rest of the arguments.
因此,请尝试以下操作:
So try something like:
#!/usr/bin/expect
spawn [lindex $argv 1] [lrange $argv 2 end]
expect "password:"
send [lindex $argv 0]
interact
但是即使那样也不起作用.
But then even that doesn't work.
根据回复:期望-生成失败,并带有参数列表 on comp.lang.tcl(
According to Re: expect - spawn fails with argument list on comp.lang.tcl (Google Groups version), we have to call eval
to split the list.
所以答案应该是:
#!/usr/bin/expect
eval spawn [lrange $argv 1 end]
expect "password:"
send [lindex $argv 0]
interact
最后,您需要在密码后发送Enter键,这样您就可以了:
Finally, you need to be sending Enter after the password, so you want:
#!/usr/bin/expect
eval spawn [lrange $argv 1 end]
expect "password:"
send [lindex $argv 0]
send '\r'
interact
然后切换顺序,调用时不引用命令
And then switch the order and don't quote the command when calling it:
./expect.sh "$SERVER1_PASS" ssh root@$SERVER1
但是其他人已经做到了.我们不需要重新发明轮子.
But others have already done this. We don't need to re-invent the wheel.
例如参见期望ssh登录脚本
这篇关于在shell脚本中使用Expect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!