REST API への GET リクエストの送信
rpc コマンドの場合、エンドポイントの一般的な形式は次のとおりです。
scheme://device-name:port/rpc/method[@attributes]/params
-
scheme:httpまたはhttps -
method: 任意の Junos OSrpcコマンドの名前。method名は、tag 要素と同じです。詳細については、 Junos XML API Explorer を参照してください。 -
params: 省略可能なパラメーター値 (name[=value])。
要求を認証するには、次のいずれかの方法を使用できます。 netrc オプションの方が安全性が高いため、使用することをお勧めします。
-
認証ヘッダーに含まれる base64 でエンコードされたユーザー名とパスワードを送信します。
curl -u "username:password" http://device-name:port/rpc/get-interface-information -
または、 .netrc ファイルを使用して資格情報を保存します。
ユーザーのホーム ディレクトリで .netrc ファイルを作成し、リモート デバイスのホスト名、ユーザー名、およびパスワードを指定します。例えば:
user@host:~$ cat ~/.netrc machine 172.16.2.1 login username password password
ユーザーのみがファイルの読み取りと書き込みのアクセス許可を持っていることを確認します。
user@host:~$ chmod 600 .netrc
要求で、
--netrcオプションを指定します。例えば:user@host:~$ curl --netrc http://172.16.2.1:3000/rpc/get-interface-information
GET 要求の URI でrpcデータをクエリ文字列として指定するには、URI の後に複数の引数を区切る&区切り記号を持つ?を使用するか、次の同等の cURL 呼び出しに示すように、/区切り記号を使用します。
例えば:
curl --netrc http://device-name:port/rpc/get-interface-information?interface-name=cbp0&snmp-index=1curl --netrc http://device-name:port/rpc/get-interface-information/interface-name=cbp0/snmp-index=1
HTTP 受け入れヘッダーを使用すると、次のいずれかのコンテンツ タイプ値を使用して戻り形式を指定できます。
-
アプリケーション/XML (デフォルト)
-
アプリケーション/JSON
-
テキスト/プレーン
-
テキスト/html
たとえば、次の cURL 呼び出しでは、JSON の出力形式を指定します。
curl --netrc http://device-name:port/rpc/get-interface-information?interface-name=cbp0 --header "Accept: application/json"
Junos OS RPCのオプションの format パラメーターを使用して、出力形式を指定することもできます。
たとえば、 <get-software-information> タグ要素は、ソフトウェア プロセスのリビジョン レベルを取得します。次の HTTPS GET リクエストは、このコマンドを実行し、結果を JSON 形式で取得します。
https://device-name:port/rpc/get-software-information@format=json
次のPythonプログラムは、RESTインターフェイスを使用して get-route-engine-information RPCを実行し、応答からデータを抽出し、CPU負荷平均のグラフをプロットします。 requests モジュールは、指定されたデバイスに関連付けられている資格情報について、ユーザーの .netrc ファイルを自動的にチェックします。または、要求に auth=(username, password ) 引数を含めて資格情報を指定することもできます。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import requests
def update_line(num, data, line):
if num == 0:
return line,
global temp_y
x_data.append(num)
if num != 0 and num%8 == 1:
r = requests.get('http://' + device + '/rpc/get-route-engine-information@format=json')
if r: temp_y = r.json()['route-engine-information'][0]['route-engine'][0]['load-average-one'][0]['data']
y_data.append(float(temp_y))
line.set_data(x_data, y_data)
return line,
device = input('Enter device:port ')
temp_y = 1
fig1 = plt.figure()
x_data = []
y_data = []
l, = plt.plot([], [])
plt.xlim(0, 80)
plt.ylim(0, 1.5)
plt.xlabel('Time in seconds')
plt.ylabel('CPU utilization (load average)')
plt.title('REST-API test')
line_ani = animation.FuncAnimation(fig1, update_line, 80, fargs=(0, l), interval=1000, blit=True)
plt.show()