Commit e913d4c0 authored by Mr Phong's avatar Mr Phong

Init

parents
__pycache__/
ThaoTestLinhTinh/
*.ipynb_checkpoints
# *.ipynb
utils/
.coverage
coverage.xml
junit.xml
research results
\ No newline at end of file
import requests
import json
def append_known_ip(filename, ip: str):
f = open(filename, "a")
f.writelines([ip, "\n"])
f.close()
def read_known_ips(filename):
f = open(filename, "a+")
f.close() # tạo file nếu chưa tồn tại
f = open(filename, "r")
known_ips = [line.rstrip() for line in f.readlines()]
f.close()
return known_ips
def sort_result(filename):
known_ips = read_known_ips(filename)
known_ips.sort()
f = open(filename, "w")
for ip in known_ips:
f.writelines([ip, "\n"])
f.close()
filename = "known_ips.txt"
known_ips = read_known_ips(filename)
count = 100
domain = "ad.doubleclick.net"
while count>0:
try:
if(count%100 == 0):
print("call next 100 request from backward count="+str(count))
headers = {'accept': 'application/dns-json'}
r = requests.get("https://1.1.1.1/dns-query?name="+domain, headers=headers)
data = json.loads(r.text)
ip = data['Answer'][0]['data']
if ip not in known_ips:
print('found new ip '+ip)
known_ips.append(ip)
append_known_ip(filename,ip)
except:
pass
count=count-1
# sắp xếp lại ip theo thứ tự để dễ theo dõi
sort_result(filename)
142.250.199.70
142.250.66.38
142.250.204.134
142.250.204.38
142.251.220.38
142.251.220.6
142.251.220.70
142.251.220.102
172.217.24.230
172.217.24.70
172.217.25.6
172.217.27.38
172.217.27.6
172.217.31.6
216.58.200.230
216.58.203.70
# Hướng dẫn sử dụng ssh-tool.
ssh-tool là ứng dụng viết bằng python và trên thư viện netmiko để chạy 1 tập lệnh cho 1 tập các thiết bị nhằm mục đích tiết kiệm thời gian và tránh sai sót khi cấu hình cùng lúc nhiều thiết bị theo một kịch bản (tập lệnh) cố định.
Tool có thể chạy trên tất cả các HĐH miễn là có thể cài đặt python và các gói liên quan.
[[_TOC_]]
## I. Download source code
Để chạy ứng dụng thì ta cần download mã nguồn về máy để chạy, có 2 phương pháp
### 1. Dùng git
Nếu đã biết các sử dụng git thì dùng git để download mã nguồn về
*git clone https://gitlab.awing.vn/awing-public/sshtool.git*
### 2. Download thủ công
Nếu không dùng git thì có thể download thẳng source code về máy, cũng tương tự như dùng git
Trong cả 2 trường hợp, giả sử rằng thư mục source code đã download về máy là C:\\sshtool\>
## II. Thiết lập thông số
### 1. File hosts.txt
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 :
- 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
- 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ũng theo chuẩn csv giống như file hosts, có các trường dữ liệ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, nếu để trống thì được hiểu là so sánh với dấu nhắc mặc định của thiết bị. Thường dùng nếu các câu lệnh thay đổi dấu nhắc của thiết bị hoặc các trường hợp kết quả trả về không chứa dấu nhắc mặc đinh của thiết bị (ví dụ yêu cầu confirm, yêu cầu input thêm thông tin, ..)
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 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 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
### 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, level và định dạng ghi file log (tham khảo thêm tại https://realpython.com/python-logging/)
## III. Cài đặt và chạy ứng dụng
### 1. Cài đặt python
Để chạy ứng dụng, ta cài đặt python version 3.7 trở lên. Truy cập https://www.python.org/ và tìm gói cài đặt tương ứng, sau khi cài đặt thành công thì kiểm tra xem python đã hoạt động chưa bằng cách mở command và gõ lệnh
*C:\\>python*
Nếu hiển thị thông tin version và dấu nhắc >>> thì nghĩa là đã cài đặt thành công, ví dụ
\>\>\> *Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32*
*Type "help", "copyright", "credits" or "license" for more information.*
### 2. Cài đặt pip
PIP (Preferred Installer Program), là trình quản lý package trên python, đa phần khi cài đặt python thì đã kèm pip, để kiểm tra ta mở command và gõ lệnh
*C:\\>pip -V*
Nếu hiển thị thông tin version nghĩa là đã có sẵn pip
*pip 22.0.4 from D:\Python37\lib\site-packages\pip (python 3.7)*
Ngược lại thì ta phải cài đặt pip, tham khảo và cài đặt tại đường dẫn https://pip.pypa.io/en/stable/installation/
### 3. Cài đặt các gói cần thiết để chạy ứng dụng
Mở command, enter vào thư mục chứa ứng dụng và chạy lệnh sau để cài đặt các gói
*C:\\sshtool\>pip install -r requirements.txt --no-cache-dir --compile*
### 4. Chạy ứng dụng
Mở command, enter vào thư mục chứa ứng dụng và chạy lệnh sau để chạy ứng dụng
*C:\\sshtool\>python app.py*
\ No newline at end of file
from asyncio.log import logger
from typing import List
import sys
from netmiko import ConnectHandler, BaseConnection, SSHDetect
from pandas import read_csv, DataFrame
from config import host_file, command_file, log_file, output_dir, log_level, log_fomartter
import logging
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"):
logger.info("Exiting enable mode")
connection.exit_enable_mode()
elif(command.strip()=="#config_mode"):
logger.info("Entering config mode")
connection.config_mode()
elif(command.strip()=="#end_config_mode"):
logger.info("Exiting config mode")
connection.exit_config_mode()
else:
output= connection.send_command(command, strip_prompt=False, strip_command=False, expect_string=expect_string)
logger.info(output)
logger = logging.getLogger(__name__)
logger.setLevel(log_level)
fomartter = logging.Formatter(log_fomartter)
stream = logging.StreamHandler()
stream.setFormatter(fomartter)
logger.addHandler(stream)
file = logging.FileHandler(log_file)
file.setFormatter(fomartter)
logger.addHandler(file)
logger.info("Start !")
df_host = read_csv(host_file)
df_command = read_csv(command_file)
with open(log_file, 'a') as file_output:
#file_output.truncate()
sys.stdout = file_output
for index, row in df_host.iterrows():
site_name = str(row['name'])
logger.info("Connect to site " + site_name + " with host " + str(row['host']))
if(site_name==''):
row["session_log"]=output_dir+str(index)+'.txt'
else:
row["session_log"]=output_dir+site_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.error("ERROR when execute command in site " + site_name + " with device "+ str(row["host"]))
logger.error(ex)
sys.stdout.close()
logger.info("End !")
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.txt"
command_file = "commands.txt"
log_file = "log.txt"
output_dir = "./output/"
log_level = "INFO" # DEBUG < INFO < WARNING < ERROR < CRITICAL < FATAL
#log_fomartter = "%(message)s"
# Nếu muốn thêm thời gian và loglevel thì dùng format bên dưới
log_fomartter = "%(asctime)s:%(levelname)s:%(message)s"
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
2022-06-03 13:44:53,627:INFO:Connect to host: 42.117.236.56
2022-06-03 13:44:54,203:INFO:Connect to host : 42.117.236.56 success !
2022-06-03 13:44:54,250:INFO:/ip hotspot walled-garden
[admin@MikroTik] /ip hotspot walled-garden>
2022-06-03 13:44:54,297:INFO:add dst-host=awifi.vn action=all
[admin@MikroTik] /ip hotspot walled-garden>
2022-06-03 13:44:54,300:INFO:Connect to host: 172.16.20.2
2022-06-03 13:44:57,454:INFO:Connect to host : 172.16.20.2 success !
2022-06-03 13:45:09,685:ERROR:ERROR when execute command with device 172.16.20.2
2022-06-03 13:45:09,685:ERROR:
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.
2022-06-03 13:45:51,485:INFO:Connect to host: 42.117.236.56
2022-06-03 13:45:52,084:INFO:Connect to host : 42.117.236.56 success !
2022-06-03 13:45:52,270:INFO:/ip hotspot walled-garden
[admin@MikroTik] /ip hotspot walled-garden>
2022-06-03 13:45:52,317:INFO:add dst-host=awifi.vn action=all
[admin@MikroTik] /ip hotspot walled-garden>
2022-06-03 13:45:52,319:INFO:Connect to host: 172.16.20.2
2022-06-03 13:45:55,427:INFO:Connect to host : 172.16.20.2 success !
2022-06-03 13:46:07,687:ERROR:ERROR when execute command with device 172.16.20.2
2022-06-03 13:46:07,687:ERROR:
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.
2022-06-03 13:50:14,307:ERROR:ERROR when execute command with device 172.16.20.2
2022-06-03 13:50:14,308:ERROR:
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.
2022-06-23 11:40:50,139:ERROR:ERROR when execute command with device 42.117.236.56
2022-06-23 11:40:50,139:ERROR:TCP connection to device failed.
Common causes of this problem are:
1. Incorrect hostname or IP address.
2. Wrong TCP port.
3. Intermediate firewall blocking access.
Device settings: mikrotik_routeros 42.117.236.56:22
2022-06-23 11:41:06,302:ERROR:ERROR when execute command with device 172.16.20.2
2022-06-23 11:41:06,303:ERROR:
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.
2022-06-23 11:41:25,186:INFO:Start !
2022-06-23 11:41:25,193:INFO:Connect to site test with host: 42.117.236.56
2022-06-23 11:41:35,204:ERROR:ERROR when execute command with device 42.117.236.56
2022-06-23 11:41:35,205:ERROR:TCP connection to device failed.
Common causes of this problem are:
1. Incorrect hostname or IP address.
2. Wrong TCP port.
3. Intermediate firewall blocking access.
Device settings: mikrotik_routeros 42.117.236.56:22
2022-06-23 11:41:35,207:INFO:Connect to site test1 with host: 172.16.20.2
2022-06-23 11:41:38,339:INFO:Connect to host : 172.16.20.2 success !
2022-06-23 11:41:50,589:ERROR:ERROR when execute command with device 172.16.20.2
2022-06-23 11:41:50,589:ERROR:
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.
2022-06-23 11:41:50,592:INFO:End !
2022-06-23 12:02:32,537:INFO:Start !
2022-06-23 12:02:32,542:INFO:Connect to site test with host 42.117.236.56
2022-06-23 12:03:47,120:INFO:Start !
2022-06-23 12:03:47,128:INFO:Connect to site test with host 42.117.236.56
2022-06-23 12:03:57,139:ERROR:ERROR when execute command in site test with device 42.117.236.56
2022-06-23 12:03:57,139:ERROR:TCP connection to device failed.
Common causes of this problem are:
1. Incorrect hostname or IP address.
2. Wrong TCP port.
3. Intermediate firewall blocking access.
Device settings: mikrotik_routeros 42.117.236.56:22
2022-06-23 12:03:57,142:INFO:Connect to site test1 with host 172.16.20.2
2022-06-23 12:04:00,417:INFO:Connect to host : 172.16.20.2 success !
2022-06-23 12:04:12,640:ERROR:ERROR when execute command in site test1 with device 172.16.20.2
2022-06-23 12:04:12,641:ERROR:
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.
2022-06-23 12:04:12,643:INFO:End !
AWING-AP-TEST*>
AWING-AP-TEST*>terminal width 512
no page
AWING-AP-TEST*>no page
/ip hotspot walled-garden
AWING-AP-TEST*>/ip hotspot walled-garden
^
% Invalid input detected 9999 at '^' marker.
AWING-AP-TEST*>
AWING-AP-TEST*>exit
pandas
netmiko
\ No newline at end of file
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