Python3.7调用API批量添加资产主机到Jumpserve
2022-06-29 本文已影响0人
一个小运维
用读取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.8.8'
# secret key
secret_key = '2vym+ky!997d5kkcc64mnz06y1mmui3lut#(^wd=%s_qj$1%x'
# DB
DB_HOST = '192.168.8.8'
DB_PORT = 3306
DB_USER = 'jumpserver'
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("/data/host.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()