静的なIPアドレス割当を行う際に、InfobloxではFixed Addressという機能を用いる。このFixed Addressを抽出してみよう。細かなことはさておき、まずは動くものを作る。必要になりそうな機能は徐々に肉付けしていこう。
開発環境:
Python 3.9.2
NIOS 8.5.2
この記事のメタクラスをmetaconst.pyとしてこのスクリプトと同じディレクトリに配置した。このスクリプトの定数用クラスであるibConstはmetaconst.pyのMetaConstantを継承している。
import json
import requests
from metaconst import MetaConstant # metaconst.pyのMetaConstantクラス
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# Infoblox WAPI用定数
class ibConst(metaclass=MetaConstant):
GM = '192.168.3.51' # Grid Master
USER = 'admin' # API Username
PASS = 'infoblox' # API Password
VER = 'v2.11.2' # API Version
API = f'https://{GM}/wapi/{VER}/'
ibConnectクラスでInfobloxへのHTTPセッションを行う。以下の処理を行っている。
Grid Masterという役割を担う機器のREST APIに対してアクセスする
Fixed Addressというオブジェクトを検索する
Fixed Addressのipv4addressフィールドに「192.168.」が含まれるレコードを抽出する
検索結果のフィールドは、name,mac,dhcp_client_identifier,ipv4addrとする
HTTPリクエストのタイムアウトは3秒としてHTTPセッションを行う
class ibConnect(ibConst):
def __init__(self):
self.fixed = []
def get_fixed(self):
# InsecureRequestWarningを非表示
requests.packages.urllib3.disable_warnings\
(InsecureRequestWarning)
with requests.Session() as s:
s.auth = (ibConst.USER, ibConst.PASS)
s.verify = False
# リターンフィールドで抽出するフィールドを指定する
options = '?ipv4addr~=192.168.'\
'&_return_fields=name,mac,'\
'dhcp_client_identifier,ipv4addr'
# URI生成
uri = f'{ibConst.API}fixedaddress{options}'
try:
# HTTP GET実行、タイムアウトは3秒
res = s.get(uri, timeout=3.0)
except Exception as e:
print(e)
else:
self.fixed = res.json()
finally:
# HTTPステータスコードを表示する
print(f'Status Code: {res.status_code}')
メイン関数では以下の処理を行っている。
ibConnectのインスタンスを生成しメソッドのget_fixedを呼び出す
get_fixedの実行結果はインスタンス変数のfixedに格納される
Fixed Addressの検索結果が格納されたfixedを出力する
def main():
ib = ibConnect()
ib.get_fixed()
fixed = ib.fixed
print(fixed)
if __name__ == '__main__':
main()
出力サンプル:
Status Code: 200
[{'_ref': 'fixedaddress/ZG5zLmZpeGVkX2FkZHJlc3MkMTkyLjE2OC4xMS4xLjAuLg:192.168.11.1/default', 'dhcp_client_identifier': '', 'ipv4addr': '192.168.11.1', 'mac': '00:11:22:00:00:01', 'name': 'test001'}, {'_ref': 'fixedaddress/ZG5zLmZpeGVkX2FkZHJlc3MkMTkyLjE2OC4xMS4yLjAuLg:192.168.11.2/default', 'dhcp_client_identifier': '', 'ipv4addr': '192.168.11.2', 'mac': '00:11:22:00:00:02', 'name': 'test002'}]
まとめ:
HTTPセッションを行う単純なスクリプトである
InfobloxのREST APIの応答はJSON形式
JSON形式は辞書型として操作出来る
関連する投稿: