从字符串python块中获取第一个字符串/列

时间:2019-01-09 08:07:14

标签: python excel

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)

当前输出:

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 

所需的输出:

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

我的计划是在终端输出中提取这些字符串列并将这些字符串传输到excel文件,但是目前我在获取这些字符串时遇到了问题,我试图循环从一列中获取字符串,但是已经观察到,一列中的空白值通过此格式在数组中编号(请参见下面的示例),没有为空白值分配任何内容。

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] 

2 个答案:

答案 0 :(得分:1)

我将拆分输出,并仅选择请求的索引进行输出:

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

这意味着您的代码:

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)

答案 1 :(得分:1)

如果您提供的数据如下:

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
"""

然后您首先可以收集列大小:

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)

然后,您将看到具有大小的字符列(其中最后一列长度仅剩剩余的所有字符)

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

当您有这样的地图时,则可以仅提取并打印允许的标题

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 

当然,您可以将其作为字典收集而不是打印,然后您可以对这些数据进行所需的操作:

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'}]

注意: 如果输出中包含制表符,则可能需要扩展脚本:

if char != ' ':

需要更改为:

if char not in ' \t':