5

这是我在以下Bash 脚本中使用的代码片段:

  for user_input in `awk '{print}' testfile_$$.txt`
    do
    ipaddress=`echo $user_input | cut -d';' -f 1`
    command="${config_mode}`echo $user_input | cut -d';' -f 2-`"
            ping -w 1 $ipaddress 1> /dev/null 2> $ERR_LOG_FILE 1> $LOG_FILE
    if [ $? -eq 0 ];then
            ssh "$USERNAME@$ipaddress" "$command"
                                                  >> $LOG_FILE


    fi
    done

如何使用 Expect 自动在此脚本中进行 SSH 登录?

我对 Expect 很陌生,并开始测试它(它失败了):

#!/usr/bin/bash


set force_conservative 0  ;# Set to 1 to force conservative mode even if
                          ;# script wasn't run conservatively originally
if {$force_conservative} {
        set send_slow {1 .1}
        proc send {ignore arg} {
                sleep .1
                exp_send -s -- $arg
        }
}

#

set timeout -1
spawn ssh auto21@10.38.227.229 {uname -a; df -h}
match_max 100000
expect "*?assword: "
send -- "bar01\r"
expect eof

我需要在 Expect 脚本中重新编写 Bash 脚本,还是可以在 Bash 脚本中使用 Expect?

如果可以做到:

此外,我需要获取 Bash 变量$command$username$password$ipaddress并在 Expect 部分使用它。

你会建议什么解决方案?

或者我可以创建一个 Expect 脚本并从 Bash 脚本中调用它,仅用于登录、错误处理、执行和日志文件。

4

1 回答 1

8

那么,您将需要运行两个单独的脚本,一个调用 Expect 脚本的 shell 脚本:

#!/usr/bin/bash


set force_conservative 0  ;

将上述更改为

#!/usr/bin/expect

set force_conservative 0  ;

或者,在您的 shell 脚本中,我不确定格式,但您可以发送expect -c执行命令:

expect -c "send \"hello\n\"" -c "expect \"#\""
expect -c "send \"hello\n\"; expect \"#\""

实际上,还有另一种选择:

#!/bin/bash

echo "shell script"

/usr/bin/expect<<EOF

set force_conservative 0  ;# Set to 1 to force conservative mode even if
                          ;# script wasn't run conservatively originally
if {$force_conservative} {
        set send_slow {1 .1}
        proc send {ignore arg} {
                sleep .1
                exp_send -s -- $arg
        }
}

#

set timeout -1
spawn ssh auto21@10.38.227.229 {uname -a; df -h}
match_max 100000
expect "*?assword: "
send -- "bar01\r"
expect eof
EOF
于 2013-02-28T11:13:43.673 回答