使用restful请求华三模拟器上的设备接口数据

一、resful介绍

RESTful采用C/S模型。RESTful客户端为使用Python、Ruby或Java等编程语言开发出的RESTful客户端程序或脚本。RESTful服务器为网络设备。通过RESTful功能配置和维护设备的过程为:

(1) 客户端向服务器发送HTTP/HTTPS请求报文,通过HTTP的方法来操作指定的RESTful API接口。RESTful支持的HTTP操作方法包括GET、PUT、POST和DELETE。

(2) 服务器根据HTTP/HTTPS请求报文,完成对指定RESTful API接口的操作后,通过HTTP/HTTPS应答报文将操作结果返回给客户端。

在HTTP/HTTPS请求和应答报文中,请求和应答数据均采用JSON格式进行编码。

二 实验搭建

使用HCL模拟器添加一台网络设备关联本地网卡,

在设备进行基础配置

# 配置互联IP
interface GigabitEthernet1/0/0
ip address 192.168.1.198 255.255.255.0

# 放通策略
security-policy ip
rule 0 name pass_all
action pass

# 接口加入安全域
security-zone name Trust
import interface GigabitEthernet1/0/0

# 开启restful功能
restful https enable

# 创建本地账号并开启对应https http功能
local-user admin class manage
password simple acdbk@9182
service-type http https
authorization-attribute user-role network-admin

# 设备账号的 restful 权限
role name admin
rule 1 permit read xml-element rpc/
vlan policy deny
permit vlan 1
permit vlan 4094
#

配置完后在本地测试端口联通性

import requests
import base64
import pandas as pd
import urllib3


class Rsful_Device:
    def __init__(self, user, passwd, host):
        """
        :param user: 网络设备的用户名
        :param passwd: 网络设备的密码
        :param host: 网络设备的地址和端口,如果https采用其他端口直接拼接在后面 例 192.168.1.1:8443
        """
        self.host = host
        url = f'https://{host}/api/v1/tokens'
        # 组合用户名和密码,使用冒号连接
        credentials = f'{user}:{passwd}'
        # 对组合后的字符串进行BASE64编码
        encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
        encoded_credentials = 'Basic ' + encoded_credentials
        # 定义登录请求头
        headers = {"Authorization": encoded_credentials, "Content-type": "application/json",
                   "Accept": "application/json"}
        print(url, headers)
        # verify=False 表示不进行证书验证
        login_req = requests.post(url, headers=headers, verify=False)
        self.token = login_req.json()['token-id']
        # 拼接后续请求用的请求头
        self.headers = {"X-Auth-Token": self.token, "Content-type": "application/json", "Accept": "application/json"}
        # print(self.headers)
        # print(self.token)

    def get(self, url):
        """
        url示例 其他接口可以参考华三官网API接口文档
        /api/v1/Ifmgr/Interfaces   #获取接口数据
        /api/v1/SecurityPolicies/GetRules  #获取防火墙规则
        """
        url = f'https://{self.host}{url}'
        req = requests.get(url, headers=self.headers, verify=False)
        return req


def write_to_excel(data, filename):
    # Create a DataFrame from the data
    df = pd.DataFrame(data)
    column_headers = []
    for i in data:
        for key, value in i.items():
            column_headers.append(key)
        break
    # Reorder the columns according to the specified headers
    df = df[column_headers]
    # Write the DataFrame to an Excel file
    df.to_excel(filename, index=False)


if __name__ == '__main__':
    # 取消不安全验证的请求告警
    urllib3.disable_warnings()
    # 初始化一台设备
    FW1060 = Rsful_Device('admin', 'acdbk@9182', '192.168.1.198')
    # 获取设备的接口数据写入到表格中
    inter_data = FW1060.get('/api/v1/Ifmgr/Interfaces').json()['Interfaces']
    print(inter_data)
    write_to_excel(inter_data, 'F1060_接口数据.xlsx')

三、接口数据展示

部分字段解释

Column name Column description Column type Data type and restrictions Remarks
IfIndex Interface index Index Unsigned integer. N/A
Name Full name of an interface N/A String. Read-only.
Length: 2 to 47 characters.
AbbreviatedName Abbreviated name of an interface N/A String. Read-only.
Length: 2 to 47 characters.
PortIndex Port index N/A Unsigned integer. Read-only.
Value range: 0 to 65535.
ifTypeExt Interface extension type N/A Unsigned integer. Read-only.
For more information, see Table 2.
ifType Interface type N/A Unsigned integer. Read-only.
Additional values for ifType are assigned by the Internet Assigned Numbers Authority (IANA) through updating the syntax of the IANA ifType textual convention.
Description Interface description N/A String. N/A
Length: 1 to 255 characters.
AdminStatus Interface administration status N/A Enumeration: N/A
1—Administratively up.
2—Administratively down.
OperStatus Interface operation status N/A Enumeration: Read-only.
1—up. For more information, see Table 1.
2—down.
3—testing.
4—unknown.
5—dormant.
6—notPresent.
7—lowerLayerDown.

更多API接口和详细介绍可以参考华三官方文档

posted @ 2024-04-27 11:51  风子的乐园  阅读(108)  评论(0编辑  收藏  举报