Ramana Reddy
Ramana Reddy

Reputation: 399

Issue with pexpect match

I have a python-pexpect code snippet something like this:

while True:
    master.sendline("show rsu-set all")
    status=master.expect(["[sS]nmp.*[ ]*=[ ]*[0-9].*[0-9]","Savari>>",TIMEOUT,EOF],4)
    if status == 0:
        old_slave_ip = master.match.group().split("=")[1]
        master.sendline("config rsu-set delete "+old_slave_ip)
        master.expect("Savari>>")

        master.sendline("config rsu-set commit")
        master.expect("Savari>>")
        continue
    elif status == 1:
        break
    else:
        print "Timed out or EOF reached"
        exit_flag = 1
        exit(1)

Actual output from the shell:

Savari>> show rsu-set all 

Mode                = master
SnmpSlaveIPAddress  = 192.168.20.204
SnmpSlaveIPAddress  = 192.168.20.210

Here, before configuring new ips I'm trying to delete, old ips. So I'm trying to match the ip address and then send instruction to delete that ip.

So I'm expecting the ip using "[sS]nmp.*[ ]*=[ ]*[0-9].*[0-9]" and then extracting the ip using split() method.

I was expecting the old_slave_ip value to be ip address only. But it also has SnmpSlaveIPAddress of the next line which is causing some misbehavior.

The output of the script is like:

Savari>> show rsu-set all

Mode                = master
SnmpSlaveIPAddress  = 192.168.20.204
SnmpSlaveIPAddress  = 192.168.20.210

Savari>> config rsu-set delete  192.168.20.204

Savari>>

Savari>> SnmpSlaveIPAddress
          ^Command not found

Savari>> config rsu-set commit

Savari>> show rsu-set all

Mode                = master
SnmpSlaveIPAddress  = 192.168.20.210

Savari>> config rsu-set delete  master

Invalid value

This continues in an infinite loop.

When there is only one ip address the script works fine. This is happening only when there are more than one ip in the list.

Please help me out to figure this.

Thanks in advance

Upvotes: 2

Views: 537

Answers (1)

quemeraisc
quemeraisc

Reputation: 492

When your 'expect' matches only one address it gets something like :

SnmpSlaveIPAddress  = 192.168.20.204

but in case there more address it catches more than what you really wants, something like:

SnmpSlaveIPAddress  = 192.168.20.204
SnmpSlaveIPAddress  =

So, your 'old_slave_ip' gets the address, plus the part you don't want. In order to get rid of that I would try :

old_slave_ip = master.match.group().split("=")[1].split('\n')[0]

That is to say, only what's on the first line of what was caught by expect. And it should work in both cases (only one address, and more)

Upvotes: 2

Related Questions