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
## 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
Chứa tập lệnh cần chạy, có các lưu ý sau
- Mỗi lệnh là 1 dòng
- 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
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
- 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
- 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
......
......@@ -5,6 +5,7 @@ from netmiko import ConnectHandler, BaseConnection
from pandas import read_csv, DataFrame
from config import host_file, command_file, output_file, log_fomartter
import logging
import re
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
......@@ -20,20 +21,12 @@ file.setFormatter(fomartter)
logger.addHandler(file)
def read_devices(csv_file: str) -> DataFrame:
df = read_csv(csv_file)
return df
def read_commands(command_file: str) -> List[str]:
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"):
def run_commands(connection: BaseConnection, df_command: DataFrame):
for index, row in df_command.iterrows():
command = str(row['command']).strip()
expect_string = str(row['expect_string'])
if(str(row['command']).strip()!=""):
""" if(command.strip()=="#enable_mode"):
logger.info("Entering enable mode")
connection.enable()
elif(command.strip()=="#end_enable_mode"):
......@@ -45,22 +38,22 @@ def run_commands(connection: BaseConnection, command_list: List[str]):
elif(command.strip()=="#end_config_mode"):
logger.info("Exiting config mode")
connection.exit_config_mode()
else:
output= connection.send_command(command)
logger.info(output)
else: """
output= connection.send_command(command, strip_prompt=False, strip_command=False, expect_string=expect_string)
logger.info(output)
df = read_devices(host_file)
command_list = read_commands(command_file)
df_host = read_csv(host_file)
df_command = read_csv(command_file)
with open(output_file, 'w') as file_output:
file_output.truncate()
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']))
try:
with ConnectHandler(**row) as device_connect:
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:
logger.info(ex)
sys.stdout.close()
show clock
#enable_mode
show adoption status
#end_enable_mode
\ No newline at end of file
command,expect_string
/ip hotspot walled-garden,walled-garden>
add dst-host=awifi.vn action=all,walled-garden>
\ No newline at end of file
host_file = "hosts.csv"
host_file = "hosts.txt"
command_file = "commands.txt"
output_file = "output.txt"
log_fomartter = "%(message)s"
......
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 : 172.16.20.2 success !
2022-05-24 18:05:43 ICT
Entering enable mode
--------------------------------------------------------------------------------------------------------------------------------
DEVICE-NAME VERSION CFG-STAT MSGS ADOPTED-BY LAST-ADOPTION UPTIME IPv4-ADDRESS
--------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------
Total number of devices displayed: 0
Exiting enable mode
Connect to host: 42.117.236.56
Connect to host : 42.117.236.56 success !
/ip hotspot walled-garden
[admin@MikroTik] /ip hotspot walled-garden>
add dst-host=awifi.vn action=all
[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