Tcl linux-telnet-script和expect

Tcl linux-telnet-script和expect,tcl,telnet,expect,Tcl,Telnet,Expect,我正在编写一个expect脚本,它通过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

我正在编写一个expect脚本,它通过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"
如果我向我发送命令,我会从服务器得到一个需要评估的回复。 来自服务器的回复类似于此示例。。。尼克=尼克id=id组=组登录名=登录名

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


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

expect允许您将传入字符串与正则表达式匹配,并在expect\u 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...

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

您也可以尝试这种方法

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中使用变量,则应使用双引号,相应地,您需要避开反斜杠和通配符运算符。

很酷,这对我有很大帮助,但是我在执行从expect中调用的^时遇到了这个错误,命令名^无效-re nick=[^]*id=[^]*group=[^]*login=[^]*。看起来像,因为telnet会话说:转义字符是“^]”。有什么想法吗?哎呀,我很适合打字而不是粘贴。在双引号内,[]被tcl视为命令扩展。谢谢-我知道了!我记得这个语法,但不知道expect使用TCL/Tk谢谢!