이 페이지 내용
BLE 가져오기(사용 사례)
이 예제를 읽고 따라 BLE(Bluetooth Low Energy) 자산을 가져오고 Python 스크립트 및 API를 사용하여 유용하고 설명적인 이름을 지정합니다.
Juniper Mist Asset Visibility로 위치 기반 서비스를 설정하고 활성화하면 관리자가 모든 BLE 클라이언트와 자산을 볼 수 있습니다. 또한 실내 평면도나 지도에서 바로 정확한 위치를 볼 수 있습니다.
BLE 자산 태그를 사용하는 사이트의 경우 컨텍스트를 제공하는 쉽게 읽을 수 있는 이름을 제공하여 이러한 디바이스를 추적하는 것이 편리합니다. Juniper Mist 포털 내에서 이러한 이름을 개별적으로 추가하고 표시할 수 있지만 관리할 자산이 많은 경우 하나씩 수행하는 데 상당한 시간이 소요될 수 있습니다. 이를 수행하는 더 쉬운 방법은 스크립트를 실행하여 BLE 자산을 가져오고 이름을 대량으로 할당하는 것입니다.
이 사용 사례의 경우 다음을 수행해야 합니다.
-
각 사이트에 대한 사이트 설정에서 자산 가시성을 사용하도록 설정합니다.
-
자산 가시성에 대한 활성 라이선스가 있는지 확인합니다.
-
평면도에 호환되는 AP를 배치했는지 확인합니다.
이 사용 사례에는 및 mist-client.py의 두 가지 스크립트가 main.py 포함됩니다. 세 번째 파일인 CSV 파일assets.csv에는 BLE 자산과 해당 이름이 포함되어 있습니다.
BLE 자산을 가져와야 할 때 따라야 하는 단계 순서는 다음과 같습니다.
-
먼저 Mist API 토큰, 사이트 UUID(Universally Unique Identifier) 및 조직이 호스팅되는 지역(또는 클라우드)Mist 사용하여 스크립트를 업데이트 main.py 합니다.
-
그런 다음 파일 내에서 BLE 디바이스와 해당 이름을 추가, 제거 또는 검사합니다 assets.csv .
-
main.py CSV 컨텐츠를 사용하여 Juniper Mist에서 자산을 만드는 스크립트를 실행합니다.
Main.py 스크립트
대본의 main.py 무대 뒤에서 많은 일이 일어납니다. 스크립트는 CSV 파일에서 데이터를 가져오고 데이터를 JSON 형식으로 변환합니다. 그런 다음 스크립트는 각 디바이스에 대해 BLE 자산을 생성하고 스크립트를 트리거합니다 mist-client.py . 이 mist-client.py 스크립트는 Juniper Mist API에 필요한 모든 호출을 수행하는 작업을 수행합니다.
#!/usr/bin/python
#
# main.py
#
# Update main.py with your Mist API Token and Juniper Mist site UUID.
#
# Inspect the "assets.csv" file to update the assets being created, then run this exercise to automatically create BLE assets from CSV.
import sys, csv, json, re
from mist_client import Admin # Import the Juniper Mist client
mist_api_token = '' # Your Juniper Mist API token goes here. Documentation: https://api.mist.com/api/v1/docs/Auth#api-token
site_id = '' # Your Site ID goes here
csv_file = 'assets.csv'
# Convert CSV file to JSON object.
def csv_to_json(file):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([ {title[i]: row[title[i]] for i in range(len(title))} ])
return csv_rows
# Creates BLE assets using the given CSV file and the Juniper Mist API
def create_assets(admin, data):
for d in data:
try:
mac = re.sub(r'[^0-9a-fA-F]', '', d.get('MAC', '')).lower()
assert len(mac) == 12
assert mac.isalnum()
except:
print('Invalid MAC {}, skipping this Asset.'.format(d.get('MAC', '(none)')))
continue
# Build the asset payload
payload = {'name': d['Name'].strip(), 'mac': mac}
# Create the BLE Asset and note the targeted region (or cloud)
api_url = 'https://api.mist.com/api/v1/sites/{}/assets'.format(site_id)
(success, result) = admin.post(api_url, payload)
# Add the new BLE Asset to the return list
if result == None:
print('Failed to create BLE Asset {}'.format(mac))
else:
if success:
print('Created BLE Asset \"{}\" ({})'.format(result.get('name', '(unnamed)'), result['mac']))
else:
print('BLE Asset \"{}\" already exists with MAC Address {}'.format(d.get('Name', '(unnamed)'), mac))
# Main function
if __name__ == '__main__':
# Check for required variables
if mist_api_token == '':
print('Please provide your Mist API token as mist_api_token')
sys.exit(1)
elif site_id == '':
print('Please provide your Mist Site UUID as site_id')
sys.exit(1)
# Create Mist client
admin = Admin(mist_api_token)
print()
print('Converting file {} to JSON...\n'.format(csv_file))
# Convert CSV to valid JSON
data = csv_to_json(csv_file)
if data == None or data == []:
print('Failed to convert CSV file to JSON. Exiting script.')
sys.exit(2)
print(json.dumps(data, indent=4, sort_keys=True))
print('\n=====\n')
# Create the BLE Assets from CSV file
print('Creating BLE Assets...\n')
create_assets(admin, data)
print()
Mist_client.py 스크립트
스크립트는 mist_client.py Juniper Mist API와 상호 작용하기 위한 일반 RESTful 클라이언트처럼 작동합니다. 스크립트는 CSV 파일의 입력과 스크립트의 출력을 기반으로 API를 호출합니다 main.py . 또한 스크립트는 mist-client.py API의 HTTP 응답을 오류 검사하고 다음과 같이 출력을 표시합니다.
#!/usr/bin/python
#
# mist_client.py
#
# Mist API client session.
import json, requests
# Mist CRUD operations
class Admin(object):
def __init__(self, token=''):
self.session = requests.Session()
self.headers = {
'Content-Type': 'application/json',
'Authorization': 'Token ' + token
}
def get(self, url):
session = self.session
headers = self.headers
print('GET {}'.format(url))
response = session.get(url, headers=headers)
if response.status_code != 200:
print('Failed to GET')
print('\tURL: {}'.format(url))
print('\tResponse: {} ({})'.format(response.text, response.status_code))
return False
return json.loads(response.text)
def post(self, url, payload, timeout=60):
session = self.session
headers = self.headers
#print('POST {}'.format(url))
response = session.post(url, headers=headers, json=payload)
if response.status_code == 400:
return (False, response.text)
elif response.status_code != 200:
'''
print('Failed to POST')
print('\tURL: {}'.format(url))
print('\tPayload: {}'.format(payload))
print('\tResponse: {} ({})'.format(response.text, response.status_code))
'''
return (False, None)
return (True, json.loads(response.text))
Assets.csv
이 예 assets.csv 에서 파일은 및 main.py 파일과 동일한 디렉터리에 mist_client.py 있습니다. 다음 예는 BLE 자산의 이름 및 관련 MAC 주소로 CSV 파일의 형식을 지정하는 방법을 보여줍니다.
Name,MAC Amber Badge,aa:bb:cc:dd:ee:ff Mark Badge,11-22-33-44-55-66 Invalid MAC,xx.yy.zz.xx.yy.zz
자동화는 RESTful API와 Python을 사용하는 것 이상입니다. WebSocket 및 웹훅 API와 같은 다른 옵션을 사용할 수 있습니다. 자동화를 위해 이러한 다른 옵션을 탐색할 수 있습니다.