Коммутатор Linux Expect / TCL Comm Port Commication Cisco - PullRequest
0 голосов
/ 15 октября 2018

Я много читал о TCL / Expect и написал следующий скрипт для подключения к комм-порту на моем RPi-Kali-Linux box.

#!/usr/bin/expect -f

set timeout -1

;#set the portID and open it for reading and writing
set portID [open /dev/ttyUSB0 r+]
set baud 9600

;#Configure the port with the baud rate
;#and dont block on read, dont buffer output
fconfigure $portID -mode "9600,n,8,1"
fconfigure $portID -blocking 0 -buffering none

;#Write to the comm port by sending a carrage return
spawn -open $portID
puts -nonewline $portID "<CR>\r"
after 1000
puts "Modem echo: [read $portID]"


close $portID

Все работает нормально, пока я не попытаюсь прочитатьиз последовательного порта.

Когда я подключаюсь к коммутатору вручную с помощью minicom, меня приветствует стандартный баннер "Welcome to minicom".Оттуда я нажимаю ввод (возврат каретки), и затем я могу взаимодействовать с коммутатором со стандартными командами Cisco AT.Но при использовании приведенного выше сценария я не вижу выходных данных.

Поэтому я не знаю, что «ожидать», поэтому я не могу соответственно выполнить настройку переключателя с помощью сценария.

Любая помощь илиСовет будет очень признателен.

Заранее спасибо.





РЕДАКТИРОВАТЬ: Из комментариев и больше чтения, я изменил приведенный выше сценарий к тому, чтомы видим ниже.Команды теперь передаются на коммутатор Cisco, хотя кажется, что последовательный порт все еще получает трафик.Терминал также зависает, когда я пытаюсь вручную войти в коммутатор, чтобы проверить конфигурацию.Я думаю, что последовательный порт не закрыт.Я не уверен, что я сделал неправильно.

Мне также сказали не вызывать $ portID вручную после использования команды "spawn".Поэтому я прокомментировал любые «путы», которые бы называли этот порт.Из-за этого я не уверен, как отобразить результаты вывода во время выполнения сценария.

#!/usr/bin/expect -f
;#exp_internal 1 ;#Can enable this line for debugging. add -df above

;#set the portID and open it for reading and writing
set portID [open /dev/ttyUSB0 r+]
set baud 9600

;#Configure the port with the baud rate
;#and dont block on read, dont buffer output
fconfigure $portID -mode "9600,n,8,1"
fconfigure $portID -blocking 0 -buffering none

spawn -open $portID
set timeout 2
send -- "\r"
after 100
;#puts "Modem Echo: $portID"

;#expect -re "Would you like to enter the initial configuration dialog?" ;#Something wrong with this line, it is not matching
;#using the below instead
expect -re "yes/no"
after 100
send -- "no\r"
after 100

send -- "enable\r"
after 100
;#puts "Modem Echo: [read $portID]"
after 100

send -- "configure terminal\r"
;#puts "Modem Echo: [read $portID]"
after 100

;#At a later date, modify this next line to take user input on the number
;#of ports on the switch in question
send -- "interface range GigabitEthernet 0/1-8\r"
;#puts "Modem Echo: [read $portID]"
after 100

send -- "power inline static\r"
;#puts "Modem Echo: [read $portID]"
after 2000

send -- "no cdp enable\r"
;#puts "Modem Echo: [read $portID]"
after 100

send -- "exit\r"
;#puts "Modem Echo: [read $portID]"
after 100

send -- "exit\r"
;#puts "Modem Echo: [read $portID]"
after 100

send -- "copy running-config startup-config\r"
after 100
;#puts "Modem Echo: [read $portID]"

after 100
;#expect -re "Destination filename" ;#Problem with this line
;#going to ignore what to expect and just send a return
send -- "\r"
expect "#"
after 100
send -- "exit\r"
expect "#"

;#close $portID
close

1 Ответ

0 голосов
/ 16 октября 2018

Не смешивайте операции Expect на канале с Tcl;как только вы передадите управление с помощью spawn -open, вам нужно будет использовать send вместо puts для записи в канал и expect вместо read для чтения из канала.

set portID [open /dev/ttyUSB0 r+]
fconfigure $portID -mode "9600,n,8,1"
spawn -open $portID
# From here on, DO NOT USE $portID YOURSELF!

send "\r"
# You may need to think what you're trying to receive here
set timeout 2
expect {
    -re {(.*)\n} {
        puts "Received line: $expect_out(1,string)"
        exp_continue;   # <<< KEEP ON WAITING
    }
    timeout {
        # Do nothing on timeout
    }
}

close
...