首页 > 解决方案 > 期望脚本 - 密码输入已磨损然后再次去获取密码

问题描述

我将在第一部分获取密码,脚本将转到登录部分。在那里,如果输入的密码错误,系统将检查密码我想显示密码错误,然后再次返回获取密码部分。

我该怎么做?

#Grabbing Password to be used in script further
stty -echo
send_user -- "Enter the Password: "
expect_user -re "(.*)\n"
send_user "\n"
stty echo
set pass $expect_out(1,string)

#Loggin into the Gateway as Normal user
spawn ssh -o StrictHostKeyChecking=No $USER@$IP
expect "$USER@$IP's password:"
send "$pass\n"

标签: expect

解决方案


这就是使用 procs 有助于代码重用的地方。你会想要这样的东西:

proc passwd {} {
    stty -echo
    send_user -- "Enter the Password: "
    expect_user -re "(.*)\n"
    send_user "\n"
    stty echo
    return $expect_out(1,string)
}

set pass [passwd]
spawn ssh -o StrictHostKeyChecking=No $USER@$IP
expect {
    "$USER@$IP's password:" {
        send "$pass\n"
        exp_continue
    }
    "please try again." {
        # you may need to adjust the "incorrect password" pattern there
        set pass [passwd]
        exp_continue
    }
    eof {
        send_user "you have not entered the correct password. login failed.\n"
        exit 1
    }
    -re $prompt
}

# now you're logged in

推荐阅读