import time
import paramiko, time
import socks
from getpass import getpass
import re
import pandas as pd
import os
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
from concurrent.futures import ThreadPoolExecutor, as_completed
import threading
def juniper_parse(ip_a, u_id, u_pas, lock):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip_a, username=u_id, password=u_pas)
print(f"{ip_a}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))
with lock:
wb = openpyxl.load_workbook("juniper_data.xlsx")
ws = wb["Sheet1"]
ws.column_dimensions["C"].width = 14
ws.column_dimensions["E"].width = 14
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)
def main():
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")
max_threads = 5
thread_pool = ThreadPoolExecutor(max_workers=max_threads)
lock = threading.Lock()
futures = [thread_pool.submit(juniper_parse, device, u_id, u_pas, lock)for device in content]
for future in as_completed(futures):
future.result()
if __name__ == "__main__":
print ("we are ready to start")
main()
해당 코드는 Network automation -3- 에서 만든 코드를 업그레이드 한 것이며
multi thread를 사용하여 최대 5개의 SSH 세션을 열게 만들었으며 excel 파일에 gettering 한 정보를
작성할때 충돌을 피하기 위해 Lock을 사용하여 이전 작업이 끝나기를 기다렸다가 작업하게 하였음
엑셀에는 순서대로 호스트네임, 모델, 시리얼, 버전, 아이피가 기입됨
해당코드는 주니퍼 EX series와 QFX 5000 Series에 맞게 제작 되었으며 정규화 표현식만
원하는 코드에 맞추면 어느장비든 사용할 수 있음.
'파이썬 코드' 카테고리의 다른 글
파이썬 자동화 -6- (0) | 2023.03.20 |
---|---|
network automation -5- (0) | 2023.03.14 |
networkautomation -3- (0) | 2023.02.23 |
텍스트 파일에서 주니퍼 장비 정보 파싱하기 (0) | 2023.02.22 |
Network automation -2- (0) | 2023.02.14 |