【问题标题】:linux - telnet - script with expectlinux - telnet - 带有期望的脚本
【发布时间】:2014-11-13 09:03:18
【问题描述】:

我正在编写一个通过 telnet 与服务器通信的期望脚本,但现在我需要评估来自服务器的回复。

用法:

./edit.expect

期望脚本:

#!/usr/bin/expect<br>
spawn telnet ip port
expect "HUH?"
send "login testuser pass\r"
expect "good"
send "select 1\r"
expect "good"
send "me\r"
expect "nick=testuser id=ID group=testgroup login=testuser"
send "edit id=ID group=3\r"
expect "good"
send "quit\r"

如果我发送命令“我”,我会收到来自服务器的回复,我需要对其进行评估。 来自服务器的回复类似于此示例...“nick=NICK id=ID group=GROUP login=LOGIN”。

如何提取回复的 id 并在发送命令中使用它?

我希望你能帮助我。非常感谢!

【问题讨论】:

    标签: tcl telnet expect


    【解决方案1】:

    你也可以试试这个方法。

    set user_id {}
    expect -re {nick=(.*)\s+id=(.*)\s+group=(.*)\s+login=(.*)\n} {
            #Each submatch will be saved in the the expect_out buffer with the index of 'n,string' for the 'n'th submatch string
            puts "You have entered : $expect_out(0,string)"; #expect_out(0,string) will have the whole expect match string including the newline
            puts "Nick : $expect_out(1,string)"
            puts "ID : $expect_out(2,string)"
            puts "Group : $expect_out(3,string)"
            puts "Login : $expect_out(4,string)"
            set user_id $expect_out(2,string)
    }
    
    send "This is $user_id, reporting Sir! ;)"
    #Your further 'expect' statements goes below.
    

    您可以根据自己的意愿自定义regexp,并注意在expect 命令中使用大括号{}-re 标志。

    如果你使用大括号,Tcl 不会做任何变量替换,如果你需要在expect 中使用变量,那么你应该使用双引号,相应地你需要转义反斜杠和通配符。

    【讨论】:

    • 谢谢 - 我明白了!我记得这个语法一点点,但不知道期望使用 TCL/Tk。 ;-) 非常感谢!
    【解决方案2】:

    expect 允许您将传入的字符串与正则表达式匹配,并在 expect_out() 数组中获取子匹配项。在您的示例中,您可以使用

    send "me\r"
    expect -re {nick=([^ ]*) id=([^ ]*) group=([^ ]*) login=([^ ]*)}
    set nick $expect_out(1,string)
    set id $expect_out(2,string)
    set group $expect_out(3,string)
    set login $expect_out(4,string)
    puts "GOT nick: $nick  id: $id  group: $group  login: $login"
    send "edit id=$id group=3\r"
    etc...
    

    编辑:字符串必须在 {} 中以避免命令扩展

    【讨论】:

    • 酷,这对我有很大帮助,但我收到了这个错误invalid command name "^" while executing "^ " invoked from within "expect -re "nick=([^ ]*) id=([^ ]*) group=([^ ]*) login=([^ ]*)""。看起来,因为 telnet 会话说:Escape character is '^]'. 有什么想法吗?
    • 哎呀,适合我打字而不是粘贴。在双引号内,[] 被 tcl 视为命令扩展。
    猜你喜欢
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 2014-01-16
    • 2017-01-22
    • 2015-07-30
    • 2013-01-01
    • 2019-08-22
    相关资源
    最近更新 更多