import time
import paramiko, time
from getpass import getpass
import re
import pandas as pd
import os
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
def juniper_parse(ip_a, u_id, u_pas):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip_a, username=u_id, password=u_pas)
print("Connected Complete")
#interactive shell 선언
connection = ssh.invoke_shell()
time.sleep(3)
connection.send("set cli screen-length 0\n")
time.sleep(1)
connection.send("show version\n"
"show chassis hard\n")
time.sleep(3)
data = connection.recv(65535)
data = (data.decode())
ssh.close()
host = re.compile(r"Hostname: (\w{1,30})")
model = re.compile(r"Model: (\w{1,7}-\w{1,7})")
ver = re.compile(r"Junos: (\w{1,2}.\w{1,3})")
serial = re.compile(r"FPC \d{1} \w{1,3} \d{1,2} \w{1,3}-\w{1,6} (\w{1,13})")
h=host.findall(str(data))
m=model.findall(str(data))
s=serial.findall(str(data))
v=ver.findall(str(data))
raw_data = {"hostname" : h,
"model": m,
"serial" : s,
"version" : v,
"ip address" : ip_a}
df = pd.DataFrame(raw_data)
print(df)
with open("juniper_rawdata.txt", 'a', newline="") as f:
f.write(str(data))
wb = openpyxl.load_workbook("juniper_data.xlsx")
ws = wb["Sheet1"]
rows = dataframe_to_rows(df, index=False, header=False)
for r_idx,row in enumerate(rows, ws.max_row+1):
for c_idx, value in enumerate(row, 1):
ws.cell(row=r_idx, column=c_idx, value=value)
wb.save("juniper_data.xlsx")
except paramiko.AuthenticationException:
print("###### Invalid Username or Password ######\n")
except paramiko.ssh_exception.SSHException as e:
print("something is wrong with SSH : {}".format(e))
except Exception as ex:
print("연결오류",ex)
with open ("switch_list_test device.txt") as f:
content=f.read().splitlines()
u_id = input("Enter your Username:")
if not u_id:
u_id = "admin"
print(f"if you No Username input please Enter to keep goning default ID {u_id}")
u_pas= getpass(f"Enter Password of the user {u_id}: ")or "admin"
file = "juniper_rawdata.txt"
if os.path.isfile(file):
os.remove(file)
print("RAW data file removed")
else:
print("raw data file not found keep going")
for device in content:
print(device)
juniper_parse(device, u_id, u_pas)
해당 코드는 앞서 진행하였던 SSH 접속 코드와 주니퍼 장비 파싱 코드를 합처 놓은 코드이며 show version 과 show chassis hardware 명령어를 입력후 해당 정보를 기반으로 호스트네임, 모델, 시리얼, 버전, 아이피를 엑셀파일에 저장하는 코드 이다 주니퍼 스위치 중 EX 시리즈와 QFX 5000번대를 기반으로 작성되었다
'파이썬 코드' 카테고리의 다른 글
network automation -5- (0) | 2023.03.14 |
---|---|
Network Automation -4- (0) | 2023.02.24 |
텍스트 파일에서 주니퍼 장비 정보 파싱하기 (0) | 2023.02.22 |
Network automation -2- (0) | 2023.02.14 |
Network automation (0) | 2023.02.14 |