有几个相同的帖子,但我仍然无法使我的期望脚本正常工作。我的目的是自动化所有内容,但保留密码输入给用户。所以脚本有3个部分:
所以我有将要生成的脚本,它有3个读取命令。第一个和最后一个应该由Expect填充,第二个我想进入我自己:
#!/bin/ksh
read user?User:
echo "Expect entered the username $user"
read pass?Password:
echo "User entered the password $pass"
read command?"Shell>"
echo "Expect entered the command $command"
我期待的剧本:
#!/usr/bin/expect
spawn ./some_script
expect User
send I-am-expect\r
expect Password
interact
expect Shell
send I-am-expect-again
不幸的是,在我输入密码之后,脚本不会继续并保持在交互模式中:
[root@localhost ~]# ./my-expect
spawn ./some_script
User:I-am-expect
Expect entered the username I-am-expect
Password:i am user
User entered the password i am user
Shell>
最后当我在" Shell"然后按[ENTER]退出并显示错误:
Expect entered the command
expect: spawn id exp4 not open
while executing
"expect Shell"
(file "./my-expect" line 7)
[root@localhost ~]#
我赞成对此问题的任何解释或解决方案。我正在使用期待版本5.45
答案 0 :(得分:3)
您可以自己阅读(expect_user
)用户密码,然后send
将其写入spawn'ed程序。例如:
[STEP 101] # cat foo.exp
proc expect_prompt {} \
{
global spawn_id
expect -re {bash-[.0-9]+(#|\$)}
}
spawn ssh -t 127.0.0.1 bash --noprofile --norc
expect "password: "
stty -echo
expect_user -timeout 3600 -re "(.*)\[\r\n]"
stty echo
send "$expect_out(1,string)\r"
expect_prompt
send "exit\r"
expect eof
[STEP 102] # expect foo.exp
spawn ssh -t 127.0.0.1 bash --noprofile --norc
root@127.0.0.1's password:
bash-4.3# exit
exit
Connection to 127.0.0.1 closed.
[STEP 103] #
答案 1 :(得分:0)
应为#!/bin/bash
read -p "User: " user
echo "Expect entered the username $user"
read -p "Password: " pass
echo "User entered the password $pass"
while :
do
# Simply executing the user inputs in the shell
read -p "Shell> " command
$command
done
提供适当的退出标准条件。
以下脚本将在shell中执行用户命令
<强> exeCmds.sh 强>
#!/usr/bin/expect
spawn ./exeCmds.sh
expect User
send dinesh\r
expect Password
send welcome!2E\r
expect Shell>
puts "\nUser can interact now..."
puts -nonewline "Type 'proceed' for the script to take over\nShell> "
while 1 {
interact "proceed" {puts "User interaction completed.";break}
}
puts "Script take over the control now.."
# Now, sending 'whoami' command from script to shell
send "whoami\r"
expect Shell>
# Your further code here...
<强> automateCmdsExec.exp 强>
automateCmdsExec.exp
脚本interact
将解决bash脚本的登录需求,当提示到达时,它会将控件移交给用户。
我们应该为proceed
定义一个退出条件,我使用了interact
这个词。 (您可以根据需要改变它。)
proceed
匹配单词send
后。它会将控件返回到expect脚本。
出于演示目的,我又保留了一对expect
- send "whoami\r"
expect Shell>
命令。
即。
interact
您可以将更多代码保留在.zip
下方,因此可以通过脚本执行。