Home » excel » excel – Get first string/column from a block of string python

excel – Get first string/column from a block of string python

Posted by: admin May 14, 2020 Leave a comment

Questions:

Script on VSCODE:

import paramiko
ip =x.x.x.x
port = x
username = username
password = password
cmd='show interface status' 

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print (resp)

Current Output:

PORT          NAME           STATUS       VLAN         DUPLEX  SPEED
Gi1/0/11                     notconnect   33           auto   auto 
Gi1/0/12                     notconnect   6            auto   auto 
Gi1/0/13                     notconnect   60           auto   auto 

Desired Output:

PORT             STATUS       VLAN         
Gi1/0/11        notconnect     33           
Gi1/0/12        notconnect     6            
Gi1/0/13        notconnect     60        

My plan was to extract these column of strings in the terminal output and transfer these strings to an excel file, but currently I’m having problems getting these strings I’ve tried looping to get string from only one column but as I’ve observed, a blank value in a column is numbered by this format in array(see below example) there’s nothing assigned to a blank value.

PORT         NAME        STATUS        VLAN      DUPLEX     SPEED
string [0]   string [?]   string [1]    string [2] string[3]  string [4]

 Gi1/0/11                 notconnect      33        auto        auto 
string [5]    string[?]    string[6]    string [7]  string[8]  string[9] 
How to&Answers:

If you have data as presented:

data = """PORT          NAME           STATUS       VLAN         DUPLEX SPEED
Gi1/0/11                     notconnect   33           auto   auto
Gi1/0/12                     notconnect   6            auto   auto
Gi1/0/13                     notconnect   60           auto   auto
Gi1/0/13                     notconnect   60           auto   auto
"""

Then first you may collect columns sizes:

headers = {}

header_line = data.split('\n')[0]
name = ''
position = 0
for char in header_line:
    if char != ' ' and len(name) != len(name.rstrip()):
        headers[name.rstrip()] = position
        name = ''
        position = 0
    name += char
    position += 1

headers[name.rstrip()] = None

print(headers)

Then you will have columns with their sizes in chars (where last column length is just all what left)

{'PORT': 14, 'NAME': 15, 'STATUS': 13, 'VLAN': 13, 'DUPLEX': 7, 'SPEED': None}

When you will have such map, then you may extract and print only for allowed header

allowed_headers = ['PORT', 'STATUS', 'VLAN']

for line in data.strip().split('\n'):
    for header, length in headers.items():
        if length:
            value = line[:length]
            line = line[length:]
        else:
            value = line
        if header in allowed_headers:
            print(value, end="")
    print()

–>

PORT          STATUS       VLAN         
Gi1/0/11      notconnect   33           
Gi1/0/12      notconnect   6            
Gi1/0/13      notconnect   60           
Gi1/0/13      notconnect   60 

Of course you may collect this as dict instead of printing and then you may do what you want with that data:

elements = []

for line in data.strip().split('\n')[1:]:
    element = {}
    for header, length in headers.items():
        if length:
            value = line[:length]
            line = line[length:]
        else:
            value = line
        element[header] = value.rstrip()
    elements.append(element)

print(elements)

[{'PORT': 'Gi1/0/11', 'NAME': '', 'STATUS': 'notconnect', 'VLAN': '33', 'DUPLEX': 'auto', 'SPEED': 'auto'}, {'PORT': 'Gi1/0/12', 'NAME': '', 'STATUS': 'notconnect', 'VLAN': '6', 'DUPLEX': 'auto', 'SPEED': 'auto'}, {'PORT': 'Gi1/0/13', 'NAME': '', 'STATUS': 'notconnect', 'VLAN': '60', 'DUPLEX': 'auto', 'SPEED': 'auto'}, {'PORT': 'Gi1/0/13', 'NAME': '', 'STATUS': 'notconnect', 'VLAN': '60', 'DUPLEX': 'auto', 'SPEED': 'auto'}]

Note:
If you have tabulators in output you may need extend script:

if char != ' ':

need to be changed to:

if char not in ' \t':

Answer:

I would split the output and select only the requested indices for output:

import re
...
outlines=re.split(r' +', stdout.readlines()) #or re.split(r'\t+',...) for tabs
outlines='\t'.join([outlines[0], outlines[1], outlines[2]])
...

It means with your code:

import paramiko
import re
ip =x.x.x.x
port = x
username = username
password = password
cmd='show interface status' 

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=re.split(r' +', stdout.readlines())
resp='\t'.join([outlines[0], outlines[1], outlines[2]])
print (resp)