Jumpserver API调用 python

Jumpserver API调用

使用pandas 作为数据筛选工具

import requests
import datetime
import uuid
from httpsig.requests_auth import HTTPSignatureAuth
from pypinyin import lazy_pinyin
import json
import pandas as pd
import os



class JumpServer():
    def __init__(self):
        self.KEY_ID = ''    # KEY_ID
        self.SECRET = ''    # SECRET
        self.groups_id = {"测试": ["f3aa9f1f89a04d578f0f6f8b1de196f0"],    # group id  在数据库中查询,这块暂时懒得写。。id从数据库中查出来。
                          "开发": ["def367be15354f5b8ac124a7dc790fca", "71b050839ade464395329667cd972dea"]}
        self.signature_headers = ['(request-target)', 'accept', 'date', 'host']
        self.GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
        self.headers = {
            'Accept': 'application/json',
            'Date': datetime.datetime.utcnow().strftime(self.GMT_FORMAT)
        }
        self.auth = HTTPSignatureAuth(key_id=self.KEY_ID, secret=self.SECRET,
                                      algorithm='hmac-sha256',
                                      headers=self.signature_headers)
        self.host = ""  # 设置地址
        self.node_list = self.get_node_list()

    def update_node_list(self):
        self.node_list = self.get_node_list()

    def create_users(self, users: [], groups: []):
        groupid_list = []
        for i in groups:
            groupid_list += self.groups_id[i]
        for name in users:
            username = self.getStrAllAplha(name)
            data = {
                "id": str(uuid.uuid5(uuid.NAMESPACE_DNS, str(uuid.uuid1()))).replace("-", ""),
                "name": name,
                "username": username,
                "password": "设置密码",
                "email": "%s@邮箱地址后缀" % username,
                "public_key": "",
                "groups": groupid_list,
                "role": "User",
                "wechat": "",
                "phone": "",
                "mfa_level": 2,
                "comment": "",
                "source": "local",
                "is_active": "true",
                "date_expired": "2099-05-28T02:29:45.567Z"
            }
            req = requests.post('http://%s/api/v1/users/users/' % self.host,
                                auth=self.auth, headers=self.headers, data=data)
            if req.status_code == 201:
                print(name, username, "Create OK")
            else:
                print(name, "Create FALIED")
                print(req.content)

    # 获取节点
    def get_node_list(self):
        req = requests.get('http://%s/api/v1/assets/nodes/' % self.host,
                           auth=self.auth, headers=self.headers)
        node_list_json = json.loads(req.content.decode())
        node_list_df = pd.DataFrame.from_records(
            node_list_json, columns=["id", "name", "full_value", "key"])
        node_list_df["full_value"] = node_list_df["full_value"].str.replace(
            " ", "")
        return node_list_df

        # 获取节点
    def get_node_list_1(self):
        req = requests.get('http://%s/api/v1/assets/nodes/' % self.host,
                           auth=self.auth, headers=self.headers)
        print(req.content.decode())

    # 创建节点
    def create_node(self, fullpath):
        if self.get_nodeid_by_fullpath(fullpath):
            print("%s exsists" % fullpath)
            return

        name = os.path.basename(fullpath)
        F_path = os.path.dirname(fullpath)
        F_nodeid = self.get_nodeid_by_fullpath(F_path)

        if not F_nodeid:
            print("父节点 %s 不存在" % F_path)
            exit(9)

        # F_key = self.node_list[self.node_list["id"]
        #                        == F_nodeid]["key"].str.cat()
        # node_list = self.node_list[self.node_list["key"].str.startswith(
        #     F_key + ":")]["key"].to_list()
        # for _ in range(0, 100):
        #     node_key = F_key + ":" + str(_)
        #     if node_key in node_list:
        #         continue
        #     break
        data = {
            "name": name,
            "value": name
        }
        print(data)
        req = requests.post('http://%s/api/v1/assets/nodes/%s/children/' % (self.host, F_nodeid),
                            auth=self.auth, headers=self.headers, data=data)
        if req.status_code == 201:
            print("%s Create SUCCESSED" % fullpath)
            self.update_node_list()
        else:
            print("%s Create FALIED" % fullpath, req.content.decode())

    # 创建资产
    def create_asset(self, fullpath, ip_str, prefix=""):
        if prefix:
            prefix += "_"

        node_id = self.get_nodeid_by_fullpath(fullpath)
        if not node_id:
            print("没有找到对应节点 %s" % fullpath)
            exit(10)
        ip_list = [line.strip() for line in ip_str.strip().split("\n")]

        for ip in ip_list:
            data = {
                "ip": ip,
                "hostname": prefix + ip,
                "platform": "Linux",
                "admin_user": "54eb2ab5-d4c1-4de3-b20f-e4000c60934b",
                "nodes": node_id,
                "is_active": True
            }
            req = requests.post('http://%s/api/v1/assets/assets/' % self.host,
                                auth=self.auth, headers=self.headers, data=data)
            if req.status_code == 201:
                print("%s add into %s SUCCESSED" % (ip, fullpath))
            else:
                print("%s add into %s FALIED" % (ip, fullpath))

    # 获取节点id
    def get_nodeid_by_fullpath(self, fullpath=None):
        node_id = self.node_list["full_value"] == fullpath
        if node_id.any():
            return self.node_list[node_id]["id"].str.cat()
        else:
            return None

    def getStrAllAplha(self, name):
        return ''.join(lazy_pinyin(name))


if __name__ == "__main__":
    Jumpserver = JumpServer()

    fullpath = "Default/ops-tool/test1"

    # 创建节点
    Jumpserver.create_node(fullpath)

    # 添加资产
    ip_str = '''118.178.89.242
    123.233.233.233
    '''
    
    Jumpserver.create_asset(fullpath, ip_str, prefix="test")

    # 创建用户
    # Jumpserver.create_users(["张三", "李四"], ["开发"])

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值