我写了一个expect脚本,它有助于在远程机器上执行命令。执行完成后,我想获得一行用户输入,然后将其发送到远程bash,这是代码片段:
#! /usr/bin/env expect
...
spawn ssh -l $user $host
...
send_tty -- "Enter your command: "
set timeout -1
# match only printable characters (prevent from pressing TAB)
expect_tty eof exit -re {([[:print:]]*)\n}
send_tty -- "\n"
set timeout 10
# send the command to remote shell
send "$expect_out(1,string)"
expect "$GENERAL_PROMPT"
但是,如果输入类似于:ls /"
,我的程序将被阻止,因为远程shell希望通过提示字符串“>”获得更多字符。实际上,我希望bash不会提示输入更多信息,而不仅仅是打印错误信息:
$ read COMMAND
ls /"
$ eval "$COMMAND"
bash: unexpected EOF while looking for matching `"'
bash: syntax error: unexpected end of file
我可以在我的剧本中实现这一目标吗?
答案 0 :(得分:1)
#!/usr/bin/expect
set prompt "#|%|>|\\\$ $"; # A generalized prompt to match known prompts.
spawn ssh -l dinesh xxx.xx.xx.xxx
expect {
"(yes/no)" { send "yes\r";exp_continue}
"password"
}
send "mypassword\r"
expect -re $prompt
send_tty -- "Enter your command: "
set timeout -1
# match only printable characters (prevent from pressing TAB)
expect_tty eof exit -re {([[:print:]]*)\n}
send_tty -- "\n"
set timeout 10
puts "\nUSER INPUT : $expect_out(1,string)"
# send the command to remote shell
# Using 'here-doc', to handle possible user inputs, instead of quoting it with any other symbol like single quotes or backticks
send "read COMMAND <<END\r"
expect -re $prompt
send "$expect_out(1,string)\r"
expect -re $prompt
send "END\r"
expect -re $prompt
# Since we want to send the literal dollar sign, I am sending it within braces
send {eval $COMMAND}
# Now sending 'Return' key
send "\r"
expect -re $prompt
为什么&#39; here-doc&#39;用过?
如果我使用反引号或单引号来转义命令,那么如果用户在命令本身中给出了反引号或单引号,那么它可能会失败。所以,为了克服这个问题,我已经添加了here-doc。
输出
dinesh@MyPC:~/stackoverflow$ ./zhujs
spawn ssh -l dinesh xxx.xx.xx.xxx
dinesh@xxx.xx.xx.xxx's password:
[dinesh@lab ~]$ matched_literal_dollar_sign
Enter your command: ls /"
USER INPUT : ls /"
read COMMAND <<END
> ls /"
> END
[dinesh@lab ~]$ eval $COMMAND
-bash: unexpected EOF while looking for matching `"'
-bash: syntax error: unexpected end of file
[dinesh@lab ~]$ dinesh@MyPC:~/stackoverflow$
更新:
使用here-doc
的主要原因是它使读取作为非阻塞命令。即我们可以快速完成下一个命令。否则,我们必须等到Expect
的超时。 (当然,我们可以动态更改超时值。)
这只是一种做法。只要拥有read
命令,您就可以根据需要更改它。
答案 1 :(得分:1)
我认为这对interact
来说是一个很好的例子 - 期望放弃并让用户直接与衍生程序进行交互。
spawn ssh -l $user $host
#...
send_user "You are now about to take control: type QQQ to return control to the program\n"
interact {
QQQ return
}
send_user "Thanks, I'm back in charge ...\n"
答案 2 :(得分:0)
这是一个单行版本
read > export cmd ; eval $cmd ; unset cmd