このページの内容
BLEインポート(ユースケース)
この例を読んで従い、Bluetooth Low Energy(BLE)アセットをインポートし、PythonスクリプトとAPIを使用してわかりやすい名前を付けます。
Juniper Mistアセットの可視化で位置情報サービスを設定して有効化すると、管理者はすべてのBLEクライアントとアセットを確認できます。また、屋内の間取り図や地図上で正確な位置を確認することもできます。
BLE アセット タグを使用するサイトの場合、コンテキストを提供する読みやすい名前を付けて、これらのデバイスを追跡すると便利です。これらの名前は、ジュニパー Mistポータル内で個別に追加して表示することはできますが、管理するアセットが多数ある場合、1つずつ管理するのはかなり時間がかかります。これを行う簡単な方法は、スクリプトを実行して BLE アセットをインポートし、名前を一括で割り当てることです。
このユースケースでは、以下のことを行う必要があります。
-
各サイトのサイト設定でアセットの可視性を有効にします。
-
アセットの可視化のアクティブなライセンスがあることを確認します。
-
間取り図に互換性のあるAPが配置されていることを確認します。
このユースケースには、 main.py と mist-client.pyの2つのスクリプトが含まれます。3 番目のファイルである assets.csv という CSV ファイルには、BLE アセットとそれに対応する名前が含まれています。
BLEアセットをインポートする必要がある場合に従う手順の順序は次のとおりです。
-
まず、 main.py スクリプトを Mist API トークン、サイトのユニバーサル一意識別子 (UUID)、組織がホストされている地域 (またはクラウド) Mist更新します。
-
次に、 assets.csv ファイル内のBLEデバイスとその名前を追加、削除、または検査します。
-
CSVコンテンツを使用してMistにアセットを作成する main.py スクリプトを実行しますジュニパー。
スクリプト Main.py
main.py脚本の舞台裏では多くのことが起こります。スクリプトは、CSVファイルからデータをインポートし、データをJSON形式に変換します。その後、デバイスごとにBLEアセットを作成し、mist-client.pyスクリプトをトリガーします。このmist-client.pyスクリプトは、ジュニパー 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.
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-host}/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スクリプトは、ジュニパー Mist APIと対話するための通常のRESTfulクライアントのように機能します。スクリプトは、CSVファイルからの入力とmain.pyスクリプトの出力に基づいてAPI呼び出しを行います。また、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 ファイルは mist_client.py ファイルおよび main.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 や Webhook API などの他のオプションも利用できます。自動化目的で、これらの他のオプションも検討できます。