Commit 796be4e3 authored by Mr Phong's avatar Mr Phong

Add multi log file

parent 4f225073
......@@ -28,7 +28,10 @@ Trong cả 2 trường hợp, giả sử rằng thư mục source code đã down
Chứa thông tin về host, dữ liệu đầu vào theo chuẩn csv, các trường dữ liệu cách nhau vởi dấu *,*
Thông tin các trường dữ liệu như sau :
- device_type : Loại thiết bị, lưu ý chọn đúng kiểu thiết bị. Tham khảo thêm tại https://github.com/ktbyers/netmiko/blob/develop/PLATFORMS.md
- name : Là tên định danh thiết bị
- device_type : Loại thiết bị, lưu ý chọn đúng kiểu thiết bị. Tham khảo thêm tại https://github.com/ktbyers/netmiko/blob/develop/PLATFORMS.md.
Có thể hỗ trợ device_type là autodetect để tự động nhận dạng loại thiết bị, tuy nhiên ko recommend vì nhiều lúc chức năng này hoạt động ko chính xác, nếu có thể thì input chính xác device_type theo danh sách trên.
- host : ip truy cập
- username : username truy cập
- password : mật khẩu truy cập
......@@ -52,13 +55,17 @@ Thì dấu nhắc mới có thể là
Thì expect_string có thể là *walled-garden>*
### 3. File output.txt
### 3. File log.txt
Chứa log kết quả chạy cho toàn bộ thiết bị
### 4. Thư mục output_dir
Chứa kết quả thực thi
Chứa toàn bộ file log thực thi, mỗi thiết bị là 1 file với tên file là tên thiết bị được xác định bởi trường name trong file hosts.txt
### 4. File config.py
### 5. File config.py
Về cơ bản có thể chạy các ứng dụng với các thông số mặc định. Nếu người dùng cần tùy chỉnh các thông số thì điều chỉnh ở file này. File này chứa cấu hình đường dẫn các file trên, có thể đổi tên file hay đường dẫn nếu muốn. Ngoài ra có format ghi log file output, có thể điều chỉnh thêm thời gian ghi log nếu muốn bằng cách chỉnh lại định dạng log format (tham khảo thêm tại https://realpython.com/python-logging/)
Về cơ bản có thể chạy các ứng dụng với các thông số mặc định. Nếu người dùng cần tùy chỉnh các thông số thì điều chỉnh ở file này. File này chứa cấu hình đường dẫn các file trên, có thể đổi tên file hay đường dẫn nếu muốn. Ngoài ra có format ghi file log, có thể điều chỉnh thêm thời gian ghi log nếu muốn bằng cách chỉnh lại định dạng log format (tham khảo thêm tại https://realpython.com/python-logging/)
## III. Cài đặt và chạy ứng dụng
......
from asyncio.log import logger
from typing import List
import sys
from netmiko import ConnectHandler, BaseConnection
from netmiko import ConnectHandler, BaseConnection, SSHDetect
from pandas import read_csv, DataFrame
from config import host_file, command_file, output_file, log_fomartter
from config import host_file, command_file, log_file, output_dir, log_fomartter
import logging
import re
......@@ -16,7 +16,7 @@ stream = logging.StreamHandler()
stream.setFormatter(fomartter)
logger.addHandler(stream)
file = logging.FileHandler(output_file)
file = logging.FileHandler(log_file)
file.setFormatter(fomartter)
logger.addHandler(file)
......@@ -47,15 +47,28 @@ def run_commands(connection: BaseConnection, df_command: DataFrame):
df_host = read_csv(host_file)
df_command = read_csv(command_file)
with open(output_file, 'w') as file_output:
with open(log_file, 'w') as file_output:
file_output.truncate()
sys.stdout = file_output
for index, row in df_host.iterrows():
logger.info("Connect to host: " + str(row['host']))
if(str(row['name'])==''):
row["session_log"]=output_dir+str(index)+'.txt'
else:
row["session_log"]=output_dir+str(row['name'])+'.txt'
row = row.drop(labels=['name'])
if(str(row["device_type"]).strip()=="autodetect"):
guesser = SSHDetect(**row)
best_match = guesser.autodetect()
if(best_match!=''):
row["device_type"] = best_match
try:
with ConnectHandler(**row) as device_connect:
logger.info("Connect to host : " + str(row['host']) + " success !")
run_commands(device_connect, df_command)
except Exception as ex:
logger.info(ex)
logger.error("ERROR when execute command with device "+ str(row["host"]))
logger.error(ex)
sys.stdout.close()
host_file = "hosts.txt"
command_file = "commands.txt"
output_file = "output.txt"
log_file = "log.txt"
output_dir = "./output/"
log_fomartter = "%(message)s"
# Nếu muốn thêm thời gian thì dùng format bên dưới
# log_fomartter = "%(asctime)s:%(message)s"
\ No newline at end of file
device_type,host,username,password,port
mikrotik_routeros,42.117.236.56,admin,Yenly.Router@#$2022,22
name,host,username,password,port,device_type
test,42.117.236.56,admin,Yenly.Router@#$2022,22,mikrotik_routeros
test1,172.16.20.2,admin,@wIng202!#manager,22,extreme_wing
\ No newline at end of file
......@@ -12,3 +12,16 @@ add dst-host=awifi.vn action=all
[admin@MikroTik] /ip hotspot walled-garden>
Connect to host: 172.16.20.2
Connect to host : 172.16.20.2 success !
ERROR when execute command with device 172.16.20.2
Pattern not detected: 'walled-garden>' in output.
Things you might try to fix this:
1. Explicitly set your pattern using the expect_string argument.
2. Increase the read_timeout to a larger value.
You can also look at the Netmiko session_log or debug log for more information.
MMM MMM KKK TTTTTTTTTTT KKK
MMMM MMMM KKK TTTTTTTTTTT KKK
MMM MMMM MMM III KKK KKK RRRRRR OOOOOO TTT III KKK KKK
MMM MM MMM III KKKKK RRR RRR OOO OOO TTT III KKKKK
MMM MMM III KKK KKK RRRRRR OOO OOO TTT III KKK KKK
MMM MMM III KKK KKK RRR RRR OOOOOO TTT III KKK KKK
MikroTik RouterOS 6.47.9 (c) 1999-2020 http://www.mikrotik.com/
[?] Gives the list of available commands
command [?] Gives help on the command and list of arguments
[Tab] Completes the command/word. If the input is ambiguous,
a second [Tab] gives possible options
/ Move up to base level
.. Move up one level
/command Use command at the base level
[admin@MikroTik] >
[admin@MikroTik] > /ip hotspot walled-garden
[admin@MikroTik] /ip hotspot walled-garden> add dst-host=awifi.vn action=all
[admin@MikroTik] /ip hotspot walled-garden> exit
AWING-AP-TEST*>
AWING-AP-TEST*>terminal width 512
no page
/ip hotspot walled-garden
AWING-AP-TEST*>no page
AWING-AP-TEST*>/ip hotspot walled-garden
^
% Invalid input detected 9999 at '^' marker.
AWING-AP-TEST*>
AWING-AP-TEST*>exit
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment