求教大神,通过python从交换机中取出的配置文件中上下行中有空行该如何去除?

各位大神,小弟刚学写脚本不久,现在碰都一个问需要麻烦一下各位,大概逻辑流程是这样的:
下面的这段代码读取Excep表格中的IP地址、端口、用户名和密码通过SSH方式进入到网络交换机中,用python发送一些交换机的指令,通过这些指令把交换机中的配置文件(字符串的形式)输出到电脑上以.txt的格式保存并生成新的文件。
问题:输出的配置文件中上下行的间距有空格和#号,我想把行与行之间的空格和#号去掉,就先去除一下空格,调用了config = config.replace()这个命令,却发现没有效果依旧有空格,代码如下所示:该代码config = config.replace()命令被注释了。
求各位大神看下为何空格不能去掉呢,谢谢了。

import xlwings as xw
import paramiko
import time
import os

app = xw.App(visible=False, add_book=False)
app.display_alerts = False
app.screen_updating = False

wb = app.books.open(r'C:\Users\HeMaoYuan_Move_PC\Desktop\devices.xlsx')
ws = wb.sheets[0]
rows, cols = ws.used_range.shape  #取出Excel表格中的行数和列数
headings = ws[0, :cols].value  #第0行所有列的值

for row in range(1, rows):
    devices = {}
    for col in range(cols):
        if col == 2:  #当Excel表中的值等于第2列时
            devices[headings[col]] = int(ws[row, col].value)
        else:
            devices[headings[col]] = ws[row, col].value
    print('######### backup {} {} {}#########'.format(devices['dname'], devices['ip'], devices['device_type']))
    print('>>> login {} {} '.format(devices['dname'], devices['ip']))
    ssh = paramiko.SSHClient()
#通过读取excel表格中的IP地址、端口号、用户名和密码来登录设备
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=devices['ip'],
        port=devices['port'],
        username=devices['username'],
        password=devices['password'],
        allow_agent=False,
        look_for_keys=False)
    vty = ssh.invoke_shell()
    vty.send('system-view\n')#操作设备的指令
    time.sleep(0.1)
    vty.send('user-interface vty 0 4\n')#操作设备的指令
    time.sleep(0.1)
    vty.send('screen-length 0\n')#操作设备的指令
    time.sleep(0.1)
    vty.send('return\n')#操作设备的指令
    time.sleep(0.1)
    vty.send('display current-configuration\n')#操作设备的指令(该命令会以文本的形式显示出设备的配置文件,要导出的.txt格式的文本就是该命令)
    vty.send('\n')#操作设备的指令
    vty.send('system-view\n')#操作设备的指令
    time.sleep(0.1)
    vty.send('user-interface vty 0 4\n')#操作设备的指令
    time.sleep(0.1)
    vty.send('undo screen-length\n')#操作设备的指令
    vty.send('return\n')#操作设备的指令
    time.sleep(20)
    config = vty.recv(10000000).decode('utf-8', 'ignore')#取出设备的配置文件
#config = config.replace()
    ssh.close()

    timestr = time.strftime('%Y-%m-%d',             time.localtime(time.time()))
    filename = '{}_{}_{}.txt'.format(devices['ip'], devices['dname'], timestr)
    save = open(filename, 'w',encoding='utf-8')
    save.write(config)
    print('######### backup end {} {} #########'.format(devices['dname'], devices['ip']))
save.close()
wb.close()
app.quit()

Excel表格如下:

求教大神,通过python从交换机中取出的配置文件中上下行中有空行该如何去除?

输出的交换机的配置文件如下:

求教大神,通过python从交换机中取出的配置文件中上下行中有空行该如何去除?

Info: The max number of VTY users is 5, and the number

of current VTY users on line is 1.

system-view

Enter system view, return user view with Ctrl+Z.

[Quidway]user-interface vty 0 4

[Quidway-ui-vty0-4]screen-length 0

[Quidway-ui-vty0-4]return

display current-configuration

#

!Software Version V100R006C05

sysname Quidway

#

vlan batch 10

#

lldp enable

#

undo icmp-reply fast

#

acl number 4000

description Moniter

rule 5 deny source-mac 849a-403d-b488

rule 100 permit

#

aaa

authentication-scheme default

authorization-scheme default

accounting-scheme default

domain default

domain default_admin

local-user hmy password cipher %@%@>CXr8.;,H-TDyJ#y&jE:Sc^8%@%@

local-user hmy privilege level 15

local-user hmy service-type telnet ssh http

local-user admin password cipher %@%@5d~9:M^ipCfL\iB)EQd>3Uwe%@%@

local-user admin privilege level 15

local-user admin service-type http

#

interface Vlanif1

ip address 192.168.121.173 255.255.255.0

#

interface Ethernet0/0/1

description to NAC

port link-type trunk

port trunk allow-pass vlan 2 to 4094

#

interface Ethernet0/0/2

description to 2FAP

port link-type trunk

port trunk allow-pass vlan 2 to 4094

#

interface Ethernet0/0/3

#

interface Ethernet0/0/4

#

interface Ethernet0/0/5

#

interface Ethernet0/0/6

#

interface Ethernet0/0/7

#

interface Ethernet0/0/8

#

interface GigabitEthernet0/0/1

#

interface NULL0

#

ip route-static 0.0.0.0 0.0.0.0 192.168.121.1

#

stelnet server enable

ssh user hmy

ssh user hmy authentication-type password

ssh user hmy service-type stelnet

#

user-interface con 0

authentication-mode password

user privilege level 15

set authentication password cipher %@%@9T-‘:U}mS1e0=>HgyNb0,.LMcm7H(*XHPI20a7F<t8m!.LP,%@%@

idle-timeout 35791 0

user-interface vty 0 4

authentication-mode aaa

user privilege level 15

idle-timeout 35791 0

screen-length 0

protocol inbound all

#

return

system-view

Enter system view, return user view with Ctrl+Z.

[Quidway]user-interface vty 0 4

[Quidway-ui-vty0-4]undo screen-length

[Quidway-ui-vty0-4]return

讨论数量: 3
Jason990420
for row in range(1, rows):
    ...
    config = vty.recv(10000000).decode('utf-8', 'ignore')#取出设备的配置文件
    #config = config.replace()
    ...
    save = open(filename, 'wt', encoding='utf-8')
    print('######### backup end {} {} #########'.format(devices['dname'], devices['ip']))
save.close()
wb.close()
app.quit()

It show something

  • no write to file, like save.wite(config)
  • only last file called method close, maybe wrong indent
for row in range(1, rows):
    ...
    config = vty.recv(10000000).decode('utf-8', 'ignore')#取出设备的配置文件
    config = config.replace('#\n', '')        # Need to confirm if the blank line is '#\n' or else
    ...
    with open(filename, 'wt', encoding='utf-8') as f:
        f.write(config)
    print('######### backup end {} {} #########'.format(devices['dname'], devices['ip']))

wb.close()
app.quit()
1年前 评论
HeMaoYuan (楼主) 1年前

replace("旧字符","新字符",替换最大次数)

如替换所有空格:config = config.replace(" ","")

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!