使用期望脚本发送命令输出并存储在文件中 [英] Using an expect Script to send the output of a command and store in a file
问题描述
我正在尝试将通过spawn ssh远程窗口运行的命令的输出存储到本地主机中,这是我的新手,无法弄清楚我哪里出了错。
我的代码:
#!/ bin / bash
而读取行
do
/ usr / bin / expect<< EOD
spawn ssh mininet @ $ line
期望 assword:
send- mininet\r
设置输出[打开 outputfile.txt a +]
期望 mininet @ mininet-vm:*
发送- ls\r
设置结果$ expect_out(buffer)
发送 \r
放入$ output $ outcome
close $ output
期望 mininet @ mininet-vm:*
发送-退出
互动
期望eof
EOD
完成< read_ip.txt
我遇到错误
期望:生成ID exp6无法打开
在执行
时期望 mininet @ mininet-vm:*
请任何机构帮助我
您在shell heredoc中有期望程序。 Shell将在启动期望之前中扩展变量。您必须从外壳保护Expect的变量。
一种方法是使用带引号的 heredoc,然后将shell变量传递给环境以期望:
#!/ bin / bash
导出主机##环境变量
而读主机
/ usr / bin / expect<<'EOD'##注意这里的引号
spawn ssh mininet @ $ env(host)##从环境中获取值
期望 assword:
发送- mininet\r
设置输出[打开 outputfile.txt a +]
期望 mininet @ mininet-vm:*
send- ls\r
设置结果$ expect_out(buffer)
send \r
放置$ output $ outcome
close $ output
期望 mininet @ mininet-vm:*
发送- exit\r
期望eof ##既不想交互又要期望eof
EOD
完成了< read_ip.txt
在Heredoc终止符周围加上单引号,意味着整个Heredoc的行为就像一个单引号的字符串,而Expect的变量留待期望处理。 p>
您可能还会调查期望的 log_file
命令:您可以随意启用和禁用日志记录,就像手动操作一样在这里。
Hi I am trying to store the output of a command run through a spawn ssh remote window into my local host, I am new to expect and am not able to figure out where I am wrong. My Code:
#!/bin/bash
while read line
do
/usr/bin/expect <<EOD
spawn ssh mininet@$line
expect "assword:"
send -- "mininet\r"
set output [open "outputfile.txt" "a+"]
expect "mininet@mininet-vm:*"
send -- "ls\r"
set outcome $expect_out(buffer)
send "\r"
puts $output "$outcome"
close $output
expect "mininet@mininet-vm:*"
send -- "exit\r"
interact
expect eof
EOD
done <read_ip.txt
I am getting the error
expect: spawn id exp6 not open while executing "expect "mininet@mininet-vm:*""
Please can any body help me on this code.
You have your expect program in a shell heredoc. The shell will expand variables in the heredoc before launching expect. You have to protect expect's variables from the shell.
One way is to use a 'quoted' heredoc, and pass the shell variable to expect through the environment:
#!/bin/bash
export host ## an environment variable
while read host
do
/usr/bin/expect <<'EOD' ## note the quotes here
spawn ssh mininet@$env(host) ## get the value from the environment
expect "assword:"
send -- "mininet\r"
set output [open "outputfile.txt" "a+"]
expect "mininet@mininet-vm:*"
send -- "ls\r"
set outcome $expect_out(buffer)
send "\r"
puts $output "$outcome"
close $output
expect "mininet@mininet-vm:*"
send -- "exit\r"
expect eof ## don't want both "interact" and "expect eof"
EOD
done <read_ip.txt
Putting single quotes around the heredoc terminator means the whole heredoc acts like a single quoted string, and expect's variables are left for expect to handle.
You might also investigate the expect log_file
command: you can enable and disable logging at will, much as you are doing manually here.
这篇关于使用期望脚本发送命令输出并存储在文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!