您可以在bash中运行一半的脚本,而在期望中运行另一半的脚本吗? [英] can you run half a script in bash and the other half in expect
问题描述
我正在尝试使脚本自动进行ssh登录并为文件中保存的多个IP地址下载文件,即时通讯使用for i in $(cat /dir/file)
,问题是cat函数在预期中起作用,所以我不能使用它在用Expect解释的脚本上.
我想知道是否有可能使脚本的一半由bash解释,另一半由期望这样的解释
Im trying to make a script to automate ssh login and download of a file for multiple ip addresses that are kept in a file, im using a for i in $(cat /dir/file)
, problem is the cat function is working in expect so i cant use it on a script that is interpreted with expect.
I wanted to know if it is possible to make half of the script be interpreted by bash and the other half by expect like this
#!/bin/bash
code........
#!/usr/bin/expect
code........
我的代码现在看起来像这样
my code now looks like this
#!/bin/bash
expect <<-EOF
spawn sftp user@server
expect "*password:" { send "password\r" }
expect "*" { send "get /home/file\r" }
expect "*" { send "bye\r" }
EOF
我现在收到此回复
spawn sftp user@server
user@server´s password: user@hostname: /home/user
基本上可以恢复到正常的终端状态
basically it return to the normal terminal state
推荐答案
Heredoc might be the solution for you. I haven't used expect
before, so it might seem a little buggy, but the following script works:
#!/bin/bash
USER=user
SERVER=server
read -sp "password: " PASSWORD
expect <<-EOF
spawn ssh ${USER}@${SERVER}
expect "*: "
send "${PASSWORD}\r"
expect "*$ "
send "ls\r"
expect "*$ "
send "exit\r"
EOF
exit $?
此处的关键字是<<-EOF
和EOF
.介于两者之间的代码由expect
执行.
The keywords here are <<-EOF
and EOF
. The code in between is executed by expect
.
请注意,sftp
仅在您期望*>
时有效.字符串*
太宽,导致expect
对过早的文本做出反应(例如motd,已连接到服务器."等).
Note that sftp
only works when you expect *>
. The string *
is too broad, which causes expect
to react to premature text (e.g. motd, "Connected to server.", etc).
#!/bin/bash
USER=user
SERVER=server
read -sp "password: " PASSWORD
expect <<-EOF
spawn sftp ${USER}@${SERVER}
expect "* " { send "${PASSWORD}\r" }
expect "*> " { send "get derp\r" }
expect "*> " { send "bye\r" }
EOF
exit $?
这篇关于您可以在bash中运行一半的脚本,而在期望中运行另一半的脚本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!