AP 이름 변경(사용 사례)
이 예제를 읽고 따라 Python 스크립트 및 API를 사용하여 액세스 포인트(AP)의 이름을 빠르게 바꿉니다.
사용자 및 다른 무선 관리자가 특정 사이트에 있는 Juniper Mist 네트워크 액세스 포인트(AP)의 이름을 바꿔야 하는 경우가 있습니다. 일관된 이름 지정은 네트워크 인벤토리 문서에서 질서와 일관성을 제공하는 데 도움이 됩니다. 예를 들어 사이트가 물리적으로 새 위치로 이동되고 새 명명 규칙을 사용할 수 있습니다.
이 이름 바꾸기 작업을 수행하기 위해 Juniper Mist 포털에서 정규식을 사용하여 대량 이름 바꾸기 작업을 수행할 수 있습니다. 이 옵션은 쉽고 쉽게 사용할 수 있지만 이름을 바꿀 장치가 많은 경우 복잡해질 수 있습니다.
또 다른 옵션은 Python 스크립트를 생성하여 AP 이름을 바꾸는 것입니다. 이 옵션은 많은 장치의 이름을 바꾸는 작업을 단순화합니다. 아래 예제 스크립트는 Python 스크립트 이름 바꾸기 시퀀스를 보여 줍니다. 스크립트는 사이트에 이미 클레임된 특정 AP의 이름을 바꿉니다. 스크립트는 다음과 같이 세 개의 파일을 사용합니다.
-
첫 번째 파일(config.json)에는 구성 변수가 포함되어 있습니다.
-
두 번째 파일(ap-names.csv)은 이름을 바꿀 AP의 MAC 주소과 AP의 새 이름이 포함된 CSV 파일입니다.
-
세 번째 파일(main-rename-ap.py)은 다른 두 파일에서 정보를 가져오는 Python 스크립트 자체입니다.
스크립트를 사용하려면 세 파일을 모두 동일한 작업 디렉터리에 배치합니다.
JSON(JavaScript Object Notation) 형식 구성이 포함된 첫 번째 파일에는 지정된 AP를 찾고 이름을 바꾸는 데 필요한 호출을 수행하기 위해 API에 연결하는 데 필요한 변수가 포함되어 있습니다.
-
API를 사용하여 구성을 변경할 때 수정 중인 데이터를 이해해야 합니다. 또한 유효성 검사를 수행하여 여전히 제대로 작동하는지 확인하십시오.
-
자리 표시자 값을 조직 ID, 사이트 ID, AP 이름 등과 같은 실제 값으로 바꿉니다.
{
"api": {
"org_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"token": "ApUYc...hsO",
"mist_url": "https://{api-endpoint}.mist.com/api/v1/"
},
"site": {
"id": "{site-id}"
}
}
{api-endpoint} 대신 글로벌 지역의 API 엔드포인트를 사용합니다. API 엔드포인트 및 글로벌 리전을 참조하십시오.
Python 스크립트는 CSV 파일의 내용을 사용하여 AP를 식별하고(MAC 주소 기준으로) 새 이름 ap-names.csv로 이름을 바꿉니다.
name,mac
{ap-name1},aabbcc001122
{ap-name2},aabbcc001123
{ap-name3},aabbcc001124
기본적으로 처음 AP를 클레임할 때 AP는 자체 MAC 주소의 이름을 사용합니다. 기본 Python 스크립트는 다음 함수로 구성된 AP를 찾고 이름을 바꾸는 실제 작업을 수행합니다.
-
(def) - 이름을 변경할 AP의 MAC 주소 가져옵니다.
-
사이트에서 AP를 찾습니다.
-
AP의 이름을 바꿉니다.
main 함수(def)는 다른 함수를 사용하여 필요에 따라 작업과 루프를 완료합니다.
스크립트는 main-rename-ap.py 다음과 같습니다.
#!/usr/bin/env python3
"""
The format of the MAC address part of this CSV file must be the following:
aabbccddeeff
"""
import argparse
import time
import json
import requests
import csv
from pprint import pprint
def is_ap_in_site(configs: dict, ap_mac: str):
"""
This function checks for an AP assigned to a site.
Parameters:
- configs: dictionary containing all configuration information
- site_id: ID of the site we will to assign the AP to
Returns:
- the ID of the AP if the AP is assigned to the site
- the current name of the AP
"""
api_url = f"{configs['api']['mist_url']}sites/{configs['site']['id']}/devices"
headers = {'Content-Type': 'application/json',
'Authorization': 'Token {}'.format(configs['api']['token'])}
response = requests.get(api_url, headers=headers)
if response.status_code == 200:
devices = json.loads(response.content.decode('utf-8'))
for device in devices:
if device['mac'] == ap_mac:
return (device['id'], device['name'])
else:
print('Something went wrong: {}'.format(response.status_code))
return (None, None)
def rename_ap(configs: dict, ap_id: str, new_ap_name: str, ap_old_name: str):
"""
This function renames an AP.
Parameters:
- configs: dictionary containing all configuration information
- ap_id: ID of the AP device object
- new_ap_name: name to apply to the AP
- ap_old_name: current name of the AP
"""
api_url = f"{configs['api']['mist_url']}sites/{configs['site']['id']}/devices/{ap_id}"
headers = {'Content-Type': 'application/json',
'Authorization': 'Token {}'.format(configs['api']['token'])}
body = {}
body['name'] = new_ap_name
response = requests.put(api_url, headers=headers, data=json.dumps(body))
if response.status_code == 200:
device = json.loads(response.content.decode('utf-8'))
print(f"{device['mac']} renamed from {ap_old_name} to {device['name']}")
else:
print(f"AP ID: {ap_id}\tSomething went wrong: {response.status_code}")
def retreive_ap_mac_list(csv_filename: str):
"""
This function converts the content of the CSV file to a Python dictionary.
Parameters:
- csv_filename: the name of the comma separated value file.
Returns:
- A dictionary containing the content of the CSV file
"""
ap_csv = csv.DictReader(csv_filename)
ap_list = []
for line in ap_csv:
ap_list.append(line)
return ap_list
def main():
"""
This script batch renames the APs listed in a CSV file.
"""
parser = argparse.ArgumentParser(description='Configures a Mist AP for an APoS site survey')
parser.add_argument('config', metavar='config_file', type=argparse.FileType(
'r'), help='file containing all the configuration information')
parser.add_argument('ap_list', metavar='aps_names', type=argparse.FileType(
'r'), help='csv file containing new AP names')
args = parser.parse_args()
configs = json.load(args.config)
ap_mac_list = retreive_ap_mac_list(args.ap_list)
for ap in ap_mac_list:
ap_id, ap_old_name = is_ap_in_site(configs, ap['mac'])
if ap_id:
rename_ap(configs, ap_id, ap['name'], ap_old_name)
else:
print(f"AP {ap['name']} is not part of site {configs['site']['id']}")
if __name__ == '__main__':
start_time = time.time()
print('** Start the batch renaming of APs...\n')
main()
run_time = time.time() - start_time
print("\n** Time to run: %s sec" % round(run_time, 2))
스크립트를 실행하려면 스크립트를 호출 main-rename-ap.py 하고 config.json 파일 이름과 ap-names.csv 파일 이름을 인수로 제공합니다. 예를 들어:
user@linux-host} python main-rename-ap.py config.json ap-names.csv
스크립트를 실행한 후 출력은 다음과 같아야 합니다.
** Start the batch renaming of APs... aabbcc001121 renamed from OLD-AP-01 to NEW-AP-01 aabbcc001122 renamed from OLD-AP-02 to NEW-AP-02 aabbcc001122 renamed from OLD-AP-03 to NEW-AP-03 ** Time to run: 3.24 sec
Juniper Mist 포털을 확인하고 디바이스의 인벤토리를 확인하여 변경 사항을 확인할 수도 있습니다. 자동화는 RESTful API 및 Python에만 국한되지 않습니다. WebSocket 및 웹훅 API 사용과 같은 다른 자동화 옵션과 개발 프로세스에 도움이 되는 도구를 찾을 수 있습니다.