加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在bash脚本中使用expect

发布时间:2020-12-15 21:54:12 所属栏目:安全 来源:网络整理
导读:这是我在 following 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
这是我在 following 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登录.

我很期待并开始测试它(它失败了):

#!/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 -- "bar01r"
expect eof

我是否需要在expect脚本中重新编写bash脚本,或者它可以在bash脚本中使用
如果可以的话:

更多我需要获取bash变量$command,$username,$password,$ipaddress并在期望部分中使用它

你会建议什么解决方案?
要么
我可以创建一个expect脚本并从bash脚本调用它只是为了登录,错误处理,执行,日志文件

解决方法

那么你需要运行两个单独的脚本一个调用expect脚本的shell脚本

#!/usr/bin/bash


set force_conservative 0  ;

改为上面

#!/usr/bin/expect


set force_conservative 0  ;

或者在你的shell脚本中,我不确定格式,但你可以发送expect -c with command来执行:

expect -c "send "hellon"" -c "expect "#"" 
expect -c "send "hellon"; 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 -- "bar01r"
expect eof
EOF

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读