Search code examples
pythonregexparamiko

Parse the output of a linux command


I'm trying to match one specific line to capture an address in the output of a bridge control command on a remote host. I'm not sure if this should be done using stdout and readlines. I'm a noob...

import paramiko
import re

hostname = "192.168.88.79"
port = 22
username = "admin"
password = "password"


def lan0_mac():
    s = paramiko.SSHClient()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(hostname, port, username, password)
    command = "brctl showmacs br0"
    stdin, stdout, stderr = s.exec_command(command)
    for line in stdout.readlines():
        mac = re.search(r'1\s{5}(([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}))\s{7}no', line).group(1)
        print (mac)
    s.close()


lan0_mac()

I'm getting:

Traceback (most recent call last):
File "/home/user/bridgetable.py", line 22, in <module>
lan0_mac()
File "/home/user/bridgetable.py", line 17, in lan0_mac
mac = re.search(r'1\s{5}(([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}))\s{7}no', line).group(1)
AttributeError: 'NoneType' object has no attribute 'group'

Here is the sample output:

port no mac addr                is local?       ageing timer

  2     24:5a:4c:34:xx:xx       no                13.74

  2     24:5a:4c:34:xx:xx       no                 7.96

  2     24:5a:4c:34:xx:xx       no                 0.88

  2     24:5a:4c:34:xx:xx       no                 0.05

  2     24:5a:4c:34:xx:xx       yes                0.00

  1     24:5a:4c:34:xx:xx       yes                0.00

  2     24:5a:4c:34:xx:xx       no                 5.52

  2     24:5a:4c:34:xx:xx       no                 0.57

  2     24:5a:4c:34:xx:xx       no                15.76

  1     50:d4:f7:5e:xx:xx       no                 7.97

  2     24:5a:4c:34:xx:xx       no                 0.42

  2     24:5a:4c:34:xx:xx       no                22.09

  2     24:5a:4c:34:xx:xx       no                 9.48

  2     24:5a:4c:34:xx:xx       no                 1.16

Solution

  • Taking your code and modifying it assuming it is getting multiple lines of output:

    import paramiko
    import re
    
    hostname = "192.168.88.79"
    port = 22
    username = "admin"
    password = "password"
    
    
    def lan0_mac():
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        s.connect(hostname, port, username, password)
        command = "brctl showmacs br0"
        stdin, stdout, stderr = s.exec_command(command)
        for line in stdout.readlines():
            test_result = re.search(r'1\s{5}(([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}))\s{7}no', line)
            if test_result:
                mac = test_result.group(1)
                print (mac)
        s.close()
    
    
    lan0_mac()