python网络设备信息采集和正则表达式regex匹配

import paramiko
import telnetlib
import time
import re
import pandas as pd
import matplotlib.pyplot as plt

def get_via_ssh(hostname, username, password, command):
    # 创建SSH客户端
    # 自动添加主机密钥
    # 连接服务器
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname, port=22, username=username, password=password)
    print("成功连接", hostname)

    # 调用shell
    # 设置terminal length为0
    command_line = ssh.invoke_shell()
    command_line.send("terminal length 0\n")
    time.sleep(0.5)
    response = command_line.recv(65535).decode()
    print(type(response))
    print(response)

    # 使用单次命令方式
    command_line.send(command+"\n")
    time.sleep(0.5)
    response = command_line.recv(65535).decode()
    print(response)

    # 关闭ssh连接
    ssh.close()

    return response

def interactive_via_ssh(hostname, username, password):
    # 创建SSH客户端
    # 自动添加主机密钥
    # 连接服务器
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname, port=22, username=username, password=password)
    print("成功连接", hostname)

    # 调用shell
    # 设置terminal length为0
    command_line = ssh.invoke_shell()
    command_line.send("terminal length 0\n")
    time.sleep(0.5)
    response = command_line.recv(65535).decode()
    print(response)

    # 使用交互式命令方式
    commands=input('#')
    while(commands!='logout'):
       command_line.send(commands+'\n')
       time.sleep(0.5)
       response = command_line.recv(65535).decode()
       print(response)
       commands = input('#')

    ssh.close()

def get_via_telnet(hostname, username, password, command):
    # 设置telnet对象
    # 启动telnet连接
    tn = telnetlib.Telnet()
    tn.open(hostname, port=23, timeout=5)
    print('%s connected success !' % hostname)

    # 登陆操作
    response = tn.read_until(b'Username:', timeout=5)
    print(response)
    tn.write(username.encode('ascii') + b'\n')
    time.sleep(0.5)

    response = tn.read_until(b'Password:', timeout=5)
    print(response)
    tn.write(password.encode('ascii') + b'\n')
    time.sleep(0.5)

    response = tn.read_until(b'#', timeout=5)
    print(response)
    if b'#' not in response:
        print('%s登录失败' % hostname)
    else:
        print('%s登录成功' % hostname)

    # 使用单次命令方式
    tn.write(b'terminal length 0\n')
    time.sleep(0.5)
    tn.write(bytes(command+'\n', encoding='utf-8'))
    time.sleep(0.5)
    # response = tn.read_until(b'#').decode('ascii')
    response = tn.read_very_eager().decode('ascii')
    print(response)

    tn.close()

    return response

def interactive_via_telnet(hostname, username, password):
    # 设置telnet对象
    # 启动telnet连接
    tn = telnetlib.Telnet()
    tn.open(hostname, port=23, timeout=5)
    print('%s connected success !' % hostname)

    # 登陆操作
    response = tn.read_until(b'Username:', timeout=5)
    print(response)
    tn.write(username.encode('ascii') + b'\n')
    time.sleep(0.5)

    response = tn.read_until(b'Password:', timeout=5)
    print(response)
    tn.write(password.encode('ascii') + b'\n')
    time.sleep(0.5)

    response = tn.read_until(b'#', timeout=5)
    print(response)
    if b'#' not in response:
        print('%s登录失败' % hostname)
    else:
        print('%s登录成功' % hostname)

    # 使用单次命令方式
    tn.write(b'terminal length 0\n')
    time.sleep(0.5)

    # 使用交互式命令方式
    commands=input('#')
    while(commands!='logout'):
        tn.write(bytes(commands,encoding='utf-8')+b'\n')
        time.sleep(0.3)
        response = tn.read_very_eager().decode('ascii')
        print(response)
        commands = input('#')

    tn.close()

# \s    匹配任何空白非打印字符
# \S    匹配任何非空字符
def regex_show_int_des(text):
    # 正则匹配
    pattern = re.compile(r'([xsv]\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+\r\n(\S*)\s*\r\n', re.S)
    interfaces = pattern.findall(text)
    print(interfaces)

    # 处理表格
    pd_data = pd.DataFrame(interfaces)
    pd_data.columns = ['Interface', 'AdminStatus', 'PhyStatus', 'Protocol', 'Description']
    print(pd_data)
    pd_data.to_csv('c:/response/int_des.csv', index=None, encoding='utf-8')

def regex_show_int_bri(text):
    # 正则匹配
    pattern = re.compile(r'([xsv]\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+\r\n(\S*)\s*\r\n', re.S)
    interfaces = pattern.findall(text)
    print(interfaces)

    # 处理表格
    pd_data = pd.DataFrame(interfaces)
    pd_data.columns = ['Interface', 'Attribute', 'Mode', 'BW', 'Admin', 'Phy', 'Prot', 'Description']
    print(pd_data)
    pd_data.to_csv('c:/response/int_bri.csv', index=None, encoding='utf-8')


def regex_show_ip_int(text):
    # 正则匹配
    pattern = re.compile(r'([xsv]\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+', re.S)
    interfaces = pattern.findall(text)
    print(interfaces)

    # 处理表格
    pd_data = pd.DataFrame(interfaces)
    pd_data.columns = ['Interface', 'IP-Address', 'Mask', 'Admin', 'Phy', 'Prot']
    print(pd_data)
    pd_data.to_csv('c:/response/ip_int.csv', index=None, encoding='utf-8')

def regex_show_ospf(text):
    # 正则匹配
    pattern = re.compile(r'Neighbor\s+(\S+)\r\n.*?area\s+(\S+).*?interface\s+(\S+).*?State is (\S+),', re.S)
    ospf = pattern.findall(text)
    print(ospf)

    # 处理表格
    pd_data = pd.DataFrame(ospf)
    pd_data.columns = ['Neighbor', 'area', 'interface', 'State']
    print(pd_data)
    pd_data.to_csv('c:/response/ospf.csv', index=None, encoding='utf-8')

def plot_pic(dir):
    pd_data=pd.read_csv(dir)
    # pd_data.sort_values('tx_bytes', inplace=True, ascending=False)
    # inplace = True:不创建新的对象,直接对原始对象进行修改
    print(pd_data)
    pd_data.plot(x="port_name", y=["rx_bytes", "tx_bytes"], kind="line", figsize=(10, 10))
    plt.show()

# 在if __name__ == 'main': 下的代码只有在文件作为脚本直接运行才会被执行,而 import 到其他脚本中是不会被执行的
if __name__ == '__main__':

    hostname = "2001:a0a:ffff:1001::27"
    username = "admin"
    password = "Admin@123"

    # 获取interface brief
    response = get_via_ssh(hostname, username, password, "show interface brief")
    regex_show_int_bri(response)
    print('----------------------------------------------')
    # 获取ip interface brief
    response = get_via_telnet(hostname, username, password, "show ip interface brief")
    regex_show_ip_int(response)
    # 获取ospf
    print('----------------------------------------------')
    response = get_via_telnet(hostname, username, password, "show ipv6 ospf neighbor detail")
    regex_show_ospf(response)

    # ssh交互式命令
    interactive_via_ssh(hostname, username, password)

    # telnet交互式命令
    interactive_via_telnet(hostname, username, password)

    plot_pic('c:/response/plot.csv')

  

posted @ 2024-10-09 14:08  adam2010  阅读(33)  评论(0)    收藏  举报