Jumpserver批量添加资产并授权

一、当前环境:

  1. jumpserver环境:jumpserver-1.3
    接口:http://docs.jumpserver.org/zh/docs/user_api.html
    python环境:Python 3.6

二、两个脚本的功能

脚本1: 用读取csv的方式批量添加jumpserver中的管理用户、系统用户、资产节点(有节点的资产添加到当前节点)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import pymysql
import requests
import csv
from itsdangerous import TimedJSONWebSignatureSerializer
#
token = 'asdfghjklmc9a3901easd678qweasdasdsa'
host = '192.168.6.66'
# secret key
secret_key = '2vym+ky!997d5kkcc64mnz06y1mmui3lut#(^wd=%s_qj$1%x'
# DB
DB_HOST = '192.168.6.66'
DB_PORT = 3306
DB_USER = 'apiuser'
DB_PASSWORD = 'passwd'
DB_NAME = 'jumpserver'
def dbConn():
    try:
        conn = pymysql.connect(
            host=DB_HOST,
            port=DB_PORT,
            user=DB_USER,
            passwd=DB_PASSWORD,
            db=DB_NAME,
            charset='utf8',
        )
    except Exception as e:
        print(e)
    return conn
# jumpserver 管理用户,系统用户加密方法
def sign_t(value, expires_in=3600):
    s = TimedJSONWebSignatureSerializer(secret_key, expires_in=expires_in)
    return str(s.dumps(value), encoding="utf8")
headers = {'Authorization': 'token ' + token, 'content-type': "application/json"}
#添加系统用户API
system_userurl = "http://{host}/api/assets/v1/system-user/".format(host=host)
#添加管理用户API
admin_userurl = "http://{host}/api/assets/v1/admin-user/".format(host=host)
#添加资产/用户节点API
nodesurl = "http://{host}/api/assets/v1/nodes/".format(host=host)
#添加资产/主机API
assetsBulkurl = "http://{host}/api/assets/v1/assets-bulk/".format(host=host)
for data_options in csv.reader(open("E:\work\list.csv")):
    print(data_options[3])
    # 可显示的管理、系统用户名字
    sysname = data_options[0] + '_baseuser'
    adminname = data_options[0] + '_root'
    # 添加系统用户
    system_userData = {
        "name": sysname,
        "username": 'baseuser',
        "priority": 10,
        "protocol": "ssh",
        "become": 'true',
        "auto_push": 'false',
        "sudo": "/bin/whoami",
        "shell": "/bin/bash",
        "password": data_options[2]
    }
    # 添加管理用户
    admin_userData = {
        "name": adminname,
        "username": 'root',
        "comment": "string",
        "created_by": "string",
        "become": 'true',
        "become_method": "sudo",
        "become_user": "root",
        "password": data_options[1]
    }
    # 管理用户、系统用户
    conn = dbConn()
    cursor = conn.cursor()
    system_userData = json.dumps(system_userData)
    admin_userData = json.dumps(admin_userData)
    sqladminname = data_options[0] + '_root'
  #判断管理用户是否存在
    sql_ifadminuser = ('SELECT name FROM jumpserver.assets_adminuser WHERE name = %s')
    cursor.execute(sql_ifadminuser, (sqladminname))
    if cursor.rowcount == 0:
        admin_userreq = requests.post(admin_userurl, headers=headers, data=admin_userData)
        admin_userreq = json.loads(admin_userreq.text)
        print(admin_userreq)
    else:
        print(adminname+' 管理用户已存在,跳过')
  #判断系统用户是否存在
    sql_ifsysuser = ('SELECT name FROM jumpserver.assets_adminuser WHERE name = %s')
    cursor.execute(sql_ifsysuser, (sysname))
    if cursor.rowcount == 0:
        system_userreq1 = requests.post(system_userurl, headers=headers, data=system_userData)
        system_userreq = json.loads(system_userreq1.text)
        print(system_userreq)
    else:
        print(sysname+' 系统用户已存在,跳过')
    conn.commit()
    # 打印密码
    print(data_options[1], data_options[2])
  
    adminUserPasswd = data_options[1]
    admin_passwordValue = sign_t(adminUserPasswd)
    admin_nameValue = adminname
    sysUserPasswd = data_options[2]
    sys_passwordValue = sign_t(sysUserPasswd)
    sys_nameValue = sysname
    # 判断节点是否存在
    conn = dbConn()
    cursor = conn.cursor()
    sql_adminid = ('select id from jumpserver.assets_adminuser where name = %s')
    cursor.execute(sql_adminid, (adminname))
    adminID = cursor.fetchall()[0][0]
    print(adminID)
    print('--------------')
    # 查找用户节点ID,判断节点是否存在
    datausrname = data_options[3]
    user = '%' + datausrname + '%'
    sql_FindNodeID = ('select id from jumpserver.assets_node where value like %s')
    cursor.execute(sql_FindNodeID, (user))
    sql_UserNodeID = cursor.fetchall()
    if cursor.rowcount == 0:
        print(data_options[3] + ' —— 用户节点不存在,创建新的节点')
        nodename = '生产-' + data_options[3] + '资产'
        # 添加节点信息
        nodesData = {
            "key": '0:179:',
            "value": nodename
        }
        nodesData = json.dumps(nodesData)
        nodesreq = requests.post(nodesurl, headers=headers, data=nodesData)
        nodesreq = json.loads(nodesreq.text)
        print(nodesreq)
        print(data_options[3])
        conn = dbConn()
        cursor = conn.cursor()
        # 获取nodeID
        datausrname = data_options[3]
        nameusernodeid = '%' + datausrname + '%'
        sql_nodeid = ('select id from jumpserver.assets_node where value like %s')
        cursor.execute(sql_nodeid, (nameusernodeid))
        nodeID = cursor.fetchall()[0][0]
        print(cursor.rowcount)
        print('---------------')
        HostIP = data_options[0]
        sql_hostid = ('select id from jumpserver.assets_asset where ip = %s')
        cursor.execute(sql_hostid, (HostIP))
        print('打印HOSTIP')
        print(cursor.rowcount)
        HostID = cursor.fetchall()
        if cursor.rowcount == 0:
            print(data_options[0] + ' 在jumpserver中不存在,添加资产')
            bulkData = {
                "ip": data_options[0],
                "hostname": data_options[0],
                "port": 22,
                "is_active": '1',
                "admin_user": adminID,
                "nodes": [
                    nodeID
                ]
            }
            # 添加资产/添加主机
            bulkData = json.dumps(bulkData)
            assetsBulkreq = requests.post(assetsBulkurl, headers=headers, data=bulkData)
            assetsBulkreq = json.loads(assetsBulkreq.text)
            print(assetsBulkreq)
            print(data_options[1], data_options[3])
        else:
            print(data_options[0] + ' 已存在,添加已有资产到用户节点')
            UseHostID = HostID[0][0]
            print(UseHostID)
            sql_InsertHost = ('INSERT INTO jumpserver.assets_asset_nodes (asset_id,node_id) VALUE (%s,%s)')
            cursor.execute(sql_InsertHost, (UseHostID, nodeID))
            print(cursor.rowcount)
    else:
        print(data_options[3] + ' —— 用户节点已存在,取现有节点创建')
        HostIP = data_options[0]
        sql_hostid = ('select id from jumpserver.assets_asset where ip = %s')
        cursor.execute(sql_hostid, (HostIP))
        print('打印HostIP--------')
        print(cursor.rowcount)
        HostID = cursor.fetchall()
        if cursor.rowcount == 0:
            print(data_options[0] + ' 在jumpserver中不存在,添加资产')
            datausrname = data_options[3]
            nameusernodeid = '%' + datausrname + '%'
            print(nameusernodeid)
            sql_nodeid = ('select id from jumpserver.assets_node where value like %s')
            cursor.execute(sql_nodeid, (nameusernodeid))
            nodeID2 = cursor.fetchall()[0][0]
            print(cursor.rowcount)
            print(nodeID2)
            print('---------------')
            bulkData = {
                "ip": data_options[0],
                "hostname": data_options[0],
                "port": 22,
                "is_active": '1',
                "admin_user": adminID,
                "nodes": [
                    nodeID2
                ]
            }
            # 添加资产/添加主机
            bulkData = json.dumps(bulkData)
            assetsBulkreq = requests.post(assetsBulkurl, headers=headers, data=bulkData)
            assetsBulkreq = json.loads(assetsBulkreq.text)
            print(assetsBulkreq)
            print(data_options[1], data_options[3])
        else:
            print(data_options[0] + ' 已存在,添加已有资产到用户节点')
            # 获取nodeID
            datausrname = data_options[3]
            nameusernodeid = '%' + datausrname + '%'
            sql_nodeid = ('select id from jumpserver.assets_node where value like %s')
            cursor.execute(sql_nodeid, (nameusernodeid))
            NodeID3 = cursor.fetchall()
            print(cursor.rowcount)
            UseHostID = HostID[0][0]
            UseNodeID = NodeID3[0][0]
            print(UseHostID,UseNodeID)
            sql_InsertHost = ('INSERT INTO jumpserver.assets_asset_nodes (asset_id,node_id) VALUE (%s,%s)')
            cursor.execute(sql_InsertHost, (UseHostID, UseNodeID))
            print(cursor.rowcount)
    print('--------用户节点ID-------')
    print(sql_UserNodeID)
    print(user)
    print('------------------------')
    conn.commit()
    # 添加管理用户密码
    sql_adminUpdate = ('update jumpserver.assets_adminuser set _password = %s where name = %s')
    cursor.execute(sql_adminUpdate, (admin_passwordValue, admin_nameValue))
    print(cursor.rowcount)
    # 添加系统用户密码
    sql_sysUpdate = ('update jumpserver.assets_systemuser set _password = %s where name = %s')
    cursor.execute(sql_sysUpdate, (sys_passwordValue, sys_nameValue))
    print(cursor.rowcount)
    conn.commit()
cursor.close()
conn.close()

脚本2:把当前节点中的资产(具体授权资产取自csv)授权给用户,只能授权用户节点内自己的资产才能生效

import sys
import json
import pymysql
import requests
import os
import csv
from itsdangerous import TimedJSONWebSignatureSerializer
token = 'asdfghjklmc9a39012345678qweasdasdsa'
host = '192.168.6.66'
# secret key
secret_key = '2vym+ky!997d5kkcc64mnz06y1mmui3lut#(^wd=%s_qj$1%x'
# DB
DB_HOST = '192.168.6.66'
DB_PORT = 3306
DB_USER = 'apiuser'
DB_PASSWORD = 'passwd'
DB_NAME = 'jumpserver'
def dbConn():
    try:
        conn = pymysql.connect(
            host=DB_HOST,
            port=DB_PORT,
            user=DB_USER,
            passwd=DB_PASSWORD,
            db=DB_NAME,
            charset='utf8',
        )
    except Exception as e:
        print(e)
    return conn
headers = {'Authorization': 'token ' + token, 'content-type': "application/json"}
#资产授权API
permsurl = "http://{host}/api/perms/v1/asset-permissions/".format(host=host)
for data2_options in csv.reader(open("E:\work\list.csv")):
    conn = dbConn()
    cursor = conn.cursor()
    # 所添加资产授权
    # 查询用户id
    UserName = data2_options[3]
    sql_users_userid = ('select id from users_user where name = %s')
    cursor.execute(sql_users_userid, (UserName))
    if cursor.rowcount == 0:
        print(data2_options[3] + '---此用户不存在,请登录jumpserver激活用户!')
    else:
        usernameID = cursor.fetchall()[0][0]
        # 查询资产/主机id
        assetsIP = data2_options[0]
        sql_assetsid = ('SELECT id FROM assets_asset WHERE ip = %s')
        cursor.execute(sql_assetsid, (assetsIP))
        assetsipID = cursor.fetchall()[0][0]
        # 查询所有权资产所在节点的id
        assetsNodeID = '%' + data2_options[3] + '%'
        sql_assetsNodeid = ('select id from assets_node where value like %s')
        cursor.execute(sql_assetsNodeid, (assetsNodeID))
        DataNodesID = cursor.fetchall()[0][0]
        system_usersID = data2_options[0] + '_baseuser'
        sql_system_usersid = ('SELECT id FROM assets_systemuser WHERE name = %s')
        cursor.execute(sql_system_usersid, (system_usersID))
        DataUsersID = cursor.fetchall()[0][0]
        permsName = data2_options[0] + '_' + DataUsersID[0:4]
        permsData = {
            # 授权名称
            "name": permsName,
            # 是否激活
            "is_active": 'true',
            # 所授权用户的id
            "users": [
                usernameID
            ],
            # 授权资产/主机的id
            "assets": [
                assetsipID
            ],
            # 授权资产所在节点的id
            "nodes": [
                DataNodesID
            ],
            # 所授权资产/主机 登陆的baseuser用户id
            "system_users": [
                DataUsersID
            ]
        }
        permsData = json.dumps(permsData)
        permsreq = requests.post(permsurl, headers=headers, data=permsData)
        permsreq = json.loads(permsreq.text)
        print('-------------'+data2_options[3]+'授权资产--------------')
        print(permsreq)
    conn.commit()

 

"E:\work\list.csv

Jumpserver批量添加资产并授权_第1张图片

你可能感兴趣的:(工作日常,工作记)