期望多次通过和多个主机

时间:2018-08-09 15:40:30

标签: bash expect

我需要一个带有Expect的脚本,以连接并执行differents命令。 问题是服务器使用不同的密码,当我尝试放入第二遍密码(登录的fisrt错误之后)不起作用 服务器列表位于服务器文件内部,密码位于脚本内部

#!/bin/bash

user=probe
pass1=pass1$
pass2=pass2$
command="cat /etc/init.d/probe"
command2="exit"
for i in `cat servers` ;
do
        /usr/bin/expect <<EOF
        set timeout -1
        log_user 1
        #exp_internal 1
        spawn ssh -o StrictHostKeyChecking=no -t  $user@$i
        expect {
        "*?assword:*" {
        send "$pass1\r"
        expect "(.*)\r"
        send "$pass2\r"
        expect "(.*)\r"
        send "$command\r"
        expect "*]$ "
        send "$command2\r"
        expect "*]$ "
        interact
        }
        }
EOF
done

谢谢!

1 个答案:

答案 0 :(得分:0)

不确定是否必须使用Expect。这是使用sexpect的示例。仅供参考。

[STEP 101] # cat servers
127.0.0.1
10.0.0.240
[STEP 102] # cat ssh.xsh
#!/bin/bash

user=foo
passwords=( 'foobar' 'barfoo' )
commands=( 'echo hello' 'echo world' )

sockprefix=/tmp/ssh-example.sock
timeout=10
re_PS1='bash-[0-9.]+[$#] '
nPasswords=${#passwords[@]}
for host in $( < servers); do
    echo "======== $host ========"

    export SEXPECT_SOCKFILE=$sockprefix-$host
    sexpect spawn -timeout $timeout \
        ssh -t -o StrictHostKeyChecking=no $user@$host bash --norc

    we_are_in=0
    for ((i = 0; i < nPasswords + 1; ++i)); do
        if ! sexpect expect -nocase -re "password:|$re_PS1"; then
            sexpect close
            sexpect wait
        fi

        out=$( sexpect expect_out -index 0 )
        if [[ $out == bash* ]]; then
            we_are_in=1
            break
        elif (( i < nPasswords )); then
            sexpect send -cr  "${passwords[i]}"
        else
            sexpect close
            sexpect wait
        fi
    done
    if (( ! we_are_in )); then
        continue
    fi

    for command in "${commands[@]}"; do
        sexpect send -enter "$command"
        sexpect expect -re "$re_PS1"
    done

    sexpect send -enter exit
    sexpect wait
done
[STEP 103] # bash ssh.xsh
======== 127.0.0.1 ========
foo@127.0.0.1's password:
bash-4.4$ echo hello
hello
bash-4.4$ echo world
world
bash-4.4$ exit
exit
Connection to 127.0.0.1 closed.
======== 10.0.0.240 ========
foo@10.0.0.240's password:
Permission denied, please try again.
foo@10.0.0.240's password:
bash-4.3$ echo hello
hello
bash-4.3$ echo world
world
bash-4.3$ exit
exit
Connection to 10.0.0.240 closed.
[STEP 104] #