问题
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
i get this response now
spawn sftp user@server
user@server´s password: user@hostname: /home/user
basically it return to the normal terminal state
回答1:
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 $?
The keywords here are <<-EOF
and EOF
. The code in between is executed by expect
.
EDIT:
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 $?
来源:https://stackoverflow.com/questions/56183907/can-you-run-half-a-script-in-bash-and-the-other-half-in-expect