Groovy

Общие сведения[править]

Groovy telnet-скрипты представляют из себя полноценные скрипты на языке программирования Groovy.

Согласно правилам языка Groovy строки нужно брать в одинарные или двойные кавычки. В одинарных кавычках все отправляется как есть, в двойных интерполируются имена переменных с долларом (превращаются в значения).

def port = "Ethernet1/5"
println "The port is $port"

выведет The port is Ethernet1/5.

def port = "Ethernet1/5"
println 'The port is $port'

выведет The port is $port.

Если переменная используется не внутри сроки, то доллар вначале ставить не нужно.

def port = "Ethernet1/5"
println port

выведет Ethernet1/5.

Язык Groovy является надмножеством языка Java, поэтому практически любые Java-конструкции в нем так же будут работать.

Скобки при вызове метода ставить не обязательно только в том случае, если метод имеет хотя бы один аргумент.
Так: withTimeout(5, SECONDS).expect(regexp("# $")) эквивалентно withTimeout 5, SECONDS expect regexp("# $").

Комментарии начинаются с //.

Доступные команды:[править]

expect "string"[править]

Ожидать, пока telnet-сессия выведет в output string.

Примеры:

  • expect "#"
  • expect prompt
  • expect "# port_$port_number sn:$onu_sn"


expect Matcher[править]

Ожидать, пока telnet-сессия выведет в output строку, соответствующую Matcher.

Возможные Matcher-ы:

  • allOf(Matcher, Matcher...) - Creates a matcher that matches if the examined input matches all of the specified matchers.
  • anyOf(Matcher, Matcher...) - Creates a matcher that matches if the examined input matches any of the specified matchers.
  • anyString() - Creates a matcher that matches when at least one character exists in the input buffer.
  • contains(String) - Creates a matcher of String that matches when examined input contains the given substring.
  • eof() - Creates a matcher that matches if input reaches the end of stream (closed telnet session).
  • exact(String) - Creates a matcher that matches when the given string is equal to the input buffer contents.
  • matches(String) - Creates a matcher of String that matches when examined input fully matches the given regular expression.
  • matches(Pattern) - Creates a matcher of Pattern that matches when examined input fully matches the given regular expression.
  • regexp(String) - Creates a matcher of String that matches when examined input contains the given regular expression.
  • regexp(Pattern) - Creates a matcher of Pattern that matches when examined input contains the given regular expression.
  • sequence(Matcher, Matcher...) - Matches the given matchers one by one. Every successful matches updates the internal buffer. The consequent match operation is performed after the previous match has succeeded.
  • startsWith(String) - Creates a matcher that matches when the input buffer starts with the given string.
  • times(int, Matcher) - Creates a matcher that matches if the given Matcher matches the number of times.

Примеры:

  • expect contains("vasya") - то же самое, что и expect "vasya"
  • expect regexp("# $") - ожидать, пока в output появится строка, соответствующая регулярному выражению "# $" (output будет заканчиваться на решетку и пробел)
  • expect times(3, contains("vasya_$num")) - ожидать, пока в output 3 раза встретится строка "vasya_$num" ($num будет интерполировано)
  • expect anyOf(contains("vasya"), contains("petya")) - ожидать, пока в output появится либо "vasya", либо "petya"
  • expect sequence(contains("vasya"), contains("petya")) - ожидать, пока в output появится "vasya", а затем "petya" (именно в этом порядке)
  • expect allOf(contains("vasya"), contains("petya")) - ожидать, пока в output появится "vasya" и "petya" (в любом порядке)


send "string"[править]

Отослать в telnet-сессию string (без Enter в конце).

Примеры:

  • send "con t"
  • send "\b\b\b\b\b"
  • send "man $port_number\n"


sendLine "string"[править]

Отослать в telnet-сессию stringEnter в конце).
То же самое, что send "string\n".

Примеры:

  • sendLine "con t"
  • sendLine login
  • sendLine "man $port_number"


sendLine()[править]

Отослать Enter.
То же самое, что send "\n" или sendLine "".

Примеры:

  • sendLine()


withTimeout duration, TimeUnit[править]

Переопределить таймаут для последующей команды.
Обычно используется совместно с expect.

Примеры:

  • withTimeout 30, SECONDS expect "# "
  • withTimeout 1, MINUTES expect prompt
  • withTimeout 3000, MILLISECONDS expect "all done"


withTimeoutMs duration[править]

То же самое, что и withTimeout duration, MILLISECONDS.

Примеры:

  • withTimeoutMs 7000 expect "# "


Примеры скриптов[править]

CommutatorLogin[править]

expect "sername:"
sendLine login
expect "assword:"
sendLine password
expect prompt

PortAuth[править]

(olt_port, onu_number) = port_number.tokenize(':')
sendLine "con t"
expect prompt
sendLine "interface gpon-olt_$olt_port"
expect prompt
sendLine "no onu $onu_number"
withTimeout 30, SECONDS expect prompt

if (onu_sn != null) {
  sendLine "onu $onu_number type $onu_model sn $onu_sn"
  expect prompt
  sendLine "exit"
  expect prompt
  sendLine "interface gpon-onu_$port_number"
  expect prompt
  sendLine "tcont 1 name T1 profile 500M"
  expect prompt
  sendLine "gemport 1 unicast tcont 1 dir both"
  expect prompt
  sendLine "service-port 1 vport 1 user-vlan $vlan_number vlan $vlan_number"
  expect prompt
  sendLine "name $port_name"
  expect prompt
  sendLine "port-location format flexible-syntax vport 1"
  expect prompt
  sendLine "dhcp-option82 enable vport 1" 
  expect prompt
  sendLine "dhcp-option82 trust true replace vport 1" 
  expect prompt
  sendLine "ip dhcp snooping enable vport 1"
  expect prompt
  sendLine "security storm-control broadcast rate 200 direction ingress vport 1"
  expect prompt
  sendLine "security storm-control broadcast rate 200 direction egress vport 1"
  expect prompt
  sendLine "security storm-control unknowncast rate 200 direction ingress vport 1"
  expect prompt
  sendLine "security storm-control unknowncast rate 200 direction egress vport 1"
  expect prompt
  sendLine "no shutdown"
  expect prompt
  sendLine "exit"
  expect prompt
  sendLine "pon-onu-mng gpon-onu_$port_number"
  expect prompt
  sendLine "interface eth eth_0/1 state lock" 
  expect prompt
  sendLine "service HSI type internet gemport 1 cos 0 vlan $vlan_number"
  expect prompt
  sendLine "vlan port eth_0/1 mode tag vlan $vlan_number priority 0"
  expect prompt
  sendLine "loop-detect ethuni eth_0/1 enable" 
  expect prompt
  Thread.sleep(5000)
  sendLine "interface eth eth_0/1 state unlock" 
  expect prompt
}

sendLine "exit"
expect prompt
sendLine "exit"
expect prompt

CommutatorLogout[править]

sendLine 'exit'