向 REST API 提交 GET 请求
rpc
对于命令,终结点的一般格式为:
scheme://device-name:port/rpc/method[@attributes]/params
-
scheme
:http
或https
-
method
:任何 Junos OSrpc
命令的名称。该method
名称与标记元素相同。有关详细信息,请参阅 Junos XML API 资源管理器。 -
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=1
curl --netrc http://device-name:port/rpc/get-interface-information/interface-name=cbp0/snmp-index=1
HTTP 接受标头可用于使用以下内容类型值之一指定返回格式:
-
应用程序/XML(默认值)
-
应用程序/JSON
-
文本/纯文本
-
文本/网页
例如,以下 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()
