期望 - telnet 连接

expect - telnet connection

我正在尝试创建一个简单的 telnet 连接脚本。 我生成 telnet 进程。根据版本的不同,它可能会或可能不会要求输入密码。

之后它要求用户名和密码以及接受规则。登录成功后提示输入命令。

但是,我写的东西不起作用。

#/usr/bin/expect -f
set IP [lindex $argv 0]
set timeout 10
set send_slow {10 .5}
log_user 1

spawn telnet -l cli $IP

expect {
    timeout {
        puts "Network Connection Problem"
        close
    }
    "Password:" {
        send -s -- "cli\r"
        exp_continue
    }
    "Username:" {
        send -s -- "admin\r"
        expect "Password:"
        send -s -- "admin\r"
        exp_continue
    }
    "(Y/N)?" {
        send -s -- "Y\r"
        exp_continue
    }   
}
expect "# "
send -s -- "show version\r"

在运行脚本之后,我通过登录和协议。一旦显示提示,脚本不会执行 show version 命令。几秒钟后光标闪烁我看到信息:

expect: spawn id exp6 not open while executing "expect "# ""

有人可以纠正我的错误吗?我已经阅读了 expect 手册,浏览了示例性脚本,但找不到任何解决方案。我确信这很简单,但我在这里挣扎。

帮帮我队长。

你在这里发表声明

spawn telnet -l cli $IP

为 telnet 会话指定用户名 cli。因此,永远不会达到以 admin 登录的代码。

管理员的默认 shell 提示是

'# '

cli 的默认 shell 提示符是

'$ '

更改您的代码以处理寻找 shell 提示。

您需要在该 expect 命令中至少有一个分支执行 not "exp_continue": 将提示的模式作为 expect 命令中的最后一个模式,没有动作:当expect看到提示时,expect命令结束,你的脚本可以继续。

expect {
    timeout {
        puts "Network Connection Problem"
        close
        exit    ;# if you don't exit, your next command is "send" which will fail
    }
    "Password:" {
        send -s -- "cli\r"
        exp_continue
    }
    "Username:" {
        send -s -- "admin\r"
        expect "Password:"
        send -s -- "admin\r"
        exp_continue
    }
    "(Y/N)?" {
        send -s -- "Y\r"
        exp_continue
    }   
    "# "
}
send -s -- "show version\r"