[英]how to use expect inside shell script
我有一个 bash+expect 脚本,它必须连接普通用户,我想读取特定文件并将其存储到变量中,以便在 root 用户中的特定文件之后使用。 我怎样才能获得价值? 我的脚本是:
#!/bin/bash
set prompt ">>> "
set command ls /root/test1
expect << EOF
spawn su root
expect "password:"
send "rootroot\r"
expect "$prompt\r"
send "$command\r"
expect "$prompt\r"
expect -re "(.*)\r\n$prompt\r\n"
EOF
echo "$command"
if [ ! -f "$command" ]; then
echo "file is not exist"
else
echo "file is exist"
fi
每当我执行我的 shell 脚本时,它都会显示以下输出:
ls: /root/: 权限被拒绝
文件不存在
基本上测试在那里,但它显示“文件不存在”
这个问题很老了,但我希望有人能从这个答案中得到帮助。
--> 您应该使用#!/usr/bin/expect
或#!/bin/expect
来正确使用expect
, expect<<EOF
可能会起作用,但这不是编写脚本的常规方法。
--> 你的脚本应该以EOF
语句结束。 前任。
#!/usr/bin/expect << EOF
<some stuff you want to do>
EOF
--> 关于spawn
一些基本知识。 您在spawn
编写的任何内容都会执行,但不会对整个脚本产生影响。 它不像环境变量。
简而言之, spawn
将启动新进程并且您的命令不在 spawn 进程中。 前任。
#!/usr/bin/expect
spawn bash -c "su root '<your-cmd-as-root>'"
<some-expect-send-stuff-etc>
现在在你的脚本中, $command
应该写在spawn
里面,就像我在上面的例子中展示的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.