linux - telnet - 带有expect的脚本

时间:2014-09-18 21:18:48

标签: tcl telnet expect

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

用法:

./edit.expect

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"

如果我发送命令&#34; me&#34;我得到了我需要评估的服务器的回复。 来自服务器的回复看起来像这个例子......&#34; nick = NICK id = ID group = GROUP login = LOGIN&#34;。

如何提取回复的ID并在send-command中使用它?

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

2 个答案:

答案 0 :(得分:2)

您也可以尝试这种方式。

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,并注意在{}命令中使用带-re标记的大括号expect

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

答案 1 :(得分:1)

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...

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