如何读取 expect 的 output 到一个变量?

2017-11-07 20:17:31 +08:00
 crytis

我在脚本里用 expect ssh 到机器上执行命令,比如 ls,如何把这个结果拿回来在脚本里使用?

expect -c "
    spawn  ssh -f -o StrictHostKeyChecking=no root@2.2.2.2 ls
    expect {
        \"*assword\" {set timeout 6000; send \"123456\`\n\"; exp_continue ; sleep 30; }
        \"yes/no\" {send \"yes\n\"; exp_continue;}

        }
    interact"

搜了半天没整明白

3260 次点击
所在节点    Linux
4 条回复
araraloren
2017-11-08 09:12:17 +08:00
ssh 应该可以获取执行的程序的返回值

try this: echo $(ssh -f -o StrictHostKeyChecking=no root@2.2.2.2 ls)
crytis
2017-11-08 10:15:23 +08:00
@araraloren 但是我要用 expect 输入密码
dongrenwen
2020-09-07 15:19:14 +08:00
ret=$(
expect -c "
spawn ssh -f -o StrictHostKeyChecking=no root@2.2.2.2 ls
expect {
\"*assword\" {set timeout 6000; send \"123456\`\n\"; exp_continue ; sleep 30; }
\"yes/no\" {send \"yes\n\"; exp_continue;}

}
interact"
)

cat <<EOF
${ret}
EOF
dongrenwen
2020-09-07 15:20:24 +08:00
```bash
ret=$(
expect -c "
spawn ssh -f -o StrictHostKeyChecking=no root@2.2.2.2 ls
expect {
\"*assword\" {set timeout 6000; send \"123456\`\n\"; exp_continue ; sleep 30; }
\"yes/no\" {send \"yes\n\"; exp_continue;}

}
interact"
)

cat <<EOF
${ret}
EOF
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/404412

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX