Thursday, March 9, 2017

Linux minicom pexpect-ing and piping with subprocess Popen & PIPE

I have E1 rack device (parabel ELF), which sometimes serving improper in such situations I always connected to the ELF and restarted it via minicom (this device is connecting using USB - and USB to serial ttyUSB). I tried with Python pexpect:

[root@localhost ~]# vi elf_restart.py
#!/usr/bin/python

from subprocess import PIPE,Popen
import pexpect
import time

#piping (`PIPE`) `dmesg` to find USB Serial Device
#it will be in line like:
#usb 1-1.4: FTDI USB Serial Device converter now attached to ttyUSB1
proc1 = Popen(["/bin/dmesg"], stdout=PIPE)
#using output of proc1 as input for proc 2 to use `grep ttyUSB`
proc2 = Popen(["/bin/grep", "ttyUSB"], stdin=proc1.stdout, stdout=PIPE)
#using output of proc2 as input for proc 3 - showing one last line
proc3 = Popen(["/usr/bin/tail", "-n", "1"], stdin=proc2.stdout, stdout=PIPE)
#splitting line from the `tail` output to the `words`
dmesg = (proc3.communicate()[0].split(" "))
#taking last word (containing ttyUSB)
usb_console = dmesg[-1].strip()
print usb_console
#will use `-s` option to enter setup-mode
connection_string = 'minicom -s'
#connecting to serial emulator and starting logging to the file `elf_pexpect.log`
elf = pexpect.spawn(connection_string)
elf.logfile = open("elf_pexpect.log", "w")
#wait for minicom for 3 seconds
time.sleep(3)
#press down arrow 2 times to select `Serial port setup`
for press in range(2):
 elf.send('j')
#send `Enter`
elf.sendcontrol('m')
#enter `A - Serial Device`
elf.send('a')
#backspace 5 times to erase `modem` word
for press in range(5):
 elf.send('\10')
#inputing actial USB Serial Device name & pressing `Enter`
elf.send(usb_console)
elf.sendcontrol('m')
#enteing ` E -    Bps/Par/Bits`
elf.send('e')
#we select `D:  38400`
elf.send('d')
#press `Enter`
elf.sendcontrol('m')
#make `F - Hardware Flow Control` uqual `No` - default is `Yes`
elf.send('f')
elf.sendcontrol('m')
#move to the `Exit` and exit setup-mode
for press in range(5):
 elf.send('j')
elf.sendcontrol('m')
#wait for the device for 5 seconds
time.sleep(5)
#here are device specific commands to restart device,
#you can use commands appropriate for your device
for press in range(2):
 elf.send('0')
elf.send('9')
#after restarting wait for the device for 5 seconds
time.sleep(5)
#3 lines to exit minicom
elf.sendcontrol('a')
elf.send('q')
elf.sendcontrol('m')
#if something went wrong you can use below command
#for manually interacting device
#elf.interact()

No comments:

Post a Comment