Commit 5a5d46b1 authored by Mr Phong's avatar Mr Phong

add expect string

parent 2dd3cd59
...@@ -23,15 +23,32 @@ Trong cả 2 trường hợp, giả sử rằng thư mục source code đã down ...@@ -23,15 +23,32 @@ Trong cả 2 trường hợp, giả sử rằng thư mục source code đã down
## II. Thiết lập thông số ## II. Thiết lập thông số
### 1. File hosts.csv ### 1. File hosts.txt
Chứa thông tin về host, lưu ý chọn kiểu thiết bị device_type cho phù hợp. Tham khảo thêm tại https://github.com/ktbyers/netmiko/blob/develop/PLATFORMS.md 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
- host : ip truy cập
- username : username truy cập
- password : mật khẩu truy cập
- port : Cổng kết nối, thường là 22
### 2. File commands.txt ### 2. File commands.txt
Chứa tập lệnh cần chạy, có các lưu ý sau Chứa tập lệnh cần chạy, cũng theo chuẩn csv giống như file hosts, có các trường dữ iệu như sau
- Mỗi lệnh là 1 dòng - command : Lệnh cần thực thi
- Các lệnh đặc biệt #enable_mode, #exit_enable_mode, #config_mode, #exit_config_mode để đưa thiết bị vào trạng thái enable hay config mode
Các lệnh đặc biệt #enable_mode, #exit_enable_mode, #config_mode, #exit_config_mode để đưa thiết bị vào trạng thái enable hay config mode
- expect_string : Đoạn string pattern regex cần tìm trong kết quả trả về để xác định là command đã hoàn thành, thường dùng nếu các câu lệnh thay đổi dấu nhắc của thiết bị. Ví dụ thiết bị mikrotik_routeros gửi command như sau
/ip hotspot walled-garden
Thì dấu nhắc mới có thể là
[admin@MikroTik] /ip hotspot walled-garden>
Thì expect_string có thể là walled-garden>
### 3. File output.txt ### 3. File output.txt
......
...@@ -5,6 +5,7 @@ from netmiko import ConnectHandler, BaseConnection ...@@ -5,6 +5,7 @@ from netmiko import ConnectHandler, BaseConnection
from pandas import read_csv, DataFrame from pandas import read_csv, DataFrame
from config import host_file, command_file, output_file, log_fomartter from config import host_file, command_file, output_file, log_fomartter
import logging import logging
import re
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
...@@ -20,20 +21,12 @@ file.setFormatter(fomartter) ...@@ -20,20 +21,12 @@ file.setFormatter(fomartter)
logger.addHandler(file) logger.addHandler(file)
def read_devices(csv_file: str) -> DataFrame: def run_commands(connection: BaseConnection, df_command: DataFrame):
df = read_csv(csv_file) for index, row in df_command.iterrows():
return df command = str(row['command']).strip()
expect_string = str(row['expect_string'])
if(str(row['command']).strip()!=""):
def read_commands(command_file: str) -> List[str]: """ if(command.strip()=="#enable_mode"):
with open(command_file) as f:
return f.readlines()
def run_commands(connection: BaseConnection, command_list: List[str]):
for command in command_list:
if(command.strip()!=""):
if(command.strip()=="#enable_mode"):
logger.info("Entering enable mode") logger.info("Entering enable mode")
connection.enable() connection.enable()
elif(command.strip()=="#end_enable_mode"): elif(command.strip()=="#end_enable_mode"):
...@@ -45,22 +38,22 @@ def run_commands(connection: BaseConnection, command_list: List[str]): ...@@ -45,22 +38,22 @@ def run_commands(connection: BaseConnection, command_list: List[str]):
elif(command.strip()=="#end_config_mode"): elif(command.strip()=="#end_config_mode"):
logger.info("Exiting config mode") logger.info("Exiting config mode")
connection.exit_config_mode() connection.exit_config_mode()
else: else: """
output= connection.send_command(command) output= connection.send_command(command, strip_prompt=False, strip_command=False, expect_string=expect_string)
logger.info(output) logger.info(output)
df = read_devices(host_file) df_host = read_csv(host_file)
command_list = read_commands(command_file) df_command = read_csv(command_file)
with open(output_file, 'w') as file_output: with open(output_file, 'w') as file_output:
file_output.truncate() file_output.truncate()
sys.stdout = file_output sys.stdout = file_output
for index, row in df.iterrows(): for index, row in df_host.iterrows():
logger.info("Connect to host: " + str(row['host'])) logger.info("Connect to host: " + str(row['host']))
try: try:
with ConnectHandler(**row) as device_connect: with ConnectHandler(**row) as device_connect:
logger.info("Connect to host : " + str(row['host']) + " success !") logger.info("Connect to host : " + str(row['host']) + " success !")
run_commands(device_connect, command_list) run_commands(device_connect, df_command)
except Exception as ex: except Exception as ex:
logger.info(ex) logger.info(ex)
sys.stdout.close() sys.stdout.close()
show clock command,expect_string
#enable_mode /ip hotspot walled-garden,walled-garden>
show adoption status add dst-host=awifi.vn action=all,walled-garden>
#end_enable_mode \ No newline at end of file
\ No newline at end of file
host_file = "hosts.csv" host_file = "hosts.txt"
command_file = "commands.txt" command_file = "commands.txt"
output_file = "output.txt" output_file = "output.txt"
log_fomartter = "%(message)s" log_fomartter = "%(message)s"
......
device_type,host,username,password,port device_type,host,username,password,port
extreme_wing,172.16.20.2,admin,@wIng202!#manager,22 mikrotik_routeros,42.117.236.56,admin,Yenly.Router@#$2022,22
Connect to host: 172.16.20.2 Connect to host: 42.117.236.56
Connect to host : 172.16.20.2 success ! Connect to host : 42.117.236.56 success !
2022-05-24 18:05:43 ICT /ip hotspot walled-garden
Entering enable mode
--------------------------------------------------------------------------------------------------------------------------------
DEVICE-NAME VERSION CFG-STAT MSGS ADOPTED-BY LAST-ADOPTION UPTIME IPv4-ADDRESS
--------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------- [admin@MikroTik] /ip hotspot walled-garden>
Total number of devices displayed: 0 add dst-host=awifi.vn action=all
Exiting enable mode
[admin@MikroTik] /ip hotspot walled-garden>
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