9-17 23 views
一、当前环境:
jumpserver环境:jumpserver-1.3
接口:http://docs.jumpserver.org/zh/docs/user_api.html
python环境:Python 3.6
二、两个脚本的功能
1. 脚本1
用读取csv的方式批量添加jumpserver中的管理用户、系统用户、资产节点(有节点的资产添加到当前节点)
2. 脚本2
把当前节点中的资产(具体授权资产取自csv)授权给用户,只能授权用户节点内自己的资产才能生效
三、具体代码如下
脚本1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
#!/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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
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() |
————python新手的学习之作,指导人Eric Winn
如果想赏钱,可以用微信扫描下面的二维码,一来能刺激我写博客的欲望,二来好维护云主机的费用; 另外再次标注博客原地址 itnotebooks.com 感谢!

token 怎么来的?
http://note.youdao.com/s/WbTNRRyq
请问这一句中”E:\work\list.csv”内需要加入什么内容?? for data_options in csv.reader(open(“E:\work\list.csv”)):
https://www.itnotebooks.com/wp-content/uploads/2020/07/tu1.png