can you run half a script in bash and the other ha

2019-08-29 10:00发布

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条回答
霸刀☆藐视天下
2楼-- · 2019-08-29 10:37

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 $?
查看更多
登录 后发表回答