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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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 @   adam2010  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示