API 文档

API 文档默认已经集成在代码里面,部署完成后可以通过下面的方式进行访问

API 访问

VersionAccess methodexample
< 2.0.0http://<url>/docshttp://192.168.244.144/docs
>=2.0.0http://<url>/api/docs/http://192.168.244.144/api/docs/
>=2.6.0http://<url>/api/docs/http://192.168.244.144/api/docs/

版本小于 v2.6 需要打开 debug 模式

  1. vi config.yml
  1. ...
  2. # 如果版本更低的话,配置文件是 config.py
  3. # Debug = true
  4. DEBUG: true

api_swagger

API 认证

JumpServer API 支持的认证有以下几种方式

  1. Session 登录后可以直接使用 session_id 作为认证方式
  2. Token 获取一次性 Token,该 Token 有有效期, 过期作废
  3. Private Token 永久 Token
  4. Access Key Http Header 进行签名

Session

用户通过页面后登录,cookie 中会存在 sessionid,请求时同样把 sessionid 放到 cookie 中

Token

  1. curl -X POST http://localhost/api/v1/authentication/auth/ \
  2. -H 'Content-Type: application/json' \
  3. -d '{"username": "admin", "password": "admin"}'

Python

  1. # Python 示例
  2. # pip install requests
  3. import requests, json
  4. def get_token(jms_url, username, password):
  5. url = jms_url + '/api/v1/authentication/auth/'
  6. query_args = {
  7. "username": username,
  8. "password": password
  9. }
  10. response = requests.post(url, data=query_args)
  11. return json.loads(response.text)['token']
  12. def get_user_info(jms_url, token):
  13. url = jms_url + '/api/v1/users/users/'
  14. headers = {
  15. "Authorization": 'Bearer ' + token,
  16. 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002'
  17. }
  18. response = requests.get(url, headers=headers)
  19. print(json.loads(response.text))
  20. if __name__ == '__main__':
  21. jms_url = 'https://demo.jumpserver.org'
  22. username = 'admin'
  23. password = 'admin'
  24. token = get_token(jms_url, username, password)
  25. get_user_info(jms_url, token)

Golang

  1. // Golang 示例
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "strings"
  10. )
  11. const (
  12. JmsServerURL = "https://demo.jumpserver.org"
  13. UserName = "admin"
  14. Password = "password"
  15. )
  16. func GetToken(jmsurl, username, password string) (string, error) {
  17. url := jmsurl + "/api/v1/authentication/auth/"
  18. query_args := strings.NewReader(`{
  19. "username": "`+username+`",
  20. "password": "`+password+`"
  21. }`)
  22. client := &http.Client{}
  23. req, err := http.NewRequest("POST", url, query_args)
  24. req.Header.Add("Content-Type", "application/json")
  25. resp, err := client.Do(req)
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. defer resp.Body.Close()
  30. body, err := ioutil.ReadAll(resp.Body)
  31. if err != nil {
  32. log.Fatal(err)
  33. }
  34. response := map[string]interface{}{}
  35. json.Unmarshal(body, &response)
  36. return response["token"].(string), nil
  37. }
  38. func GetUserInfo(jmsurl, token string) {
  39. url := jmsurl + "/api/v1/users/users/"
  40. client := &http.Client{}
  41. req, err := http.NewRequest("GET", url, nil)
  42. req.Header.Add("Authorization", "Bearer "+token)
  43. req.Header.Add("X-JMS-ORG", "00000000-0000-0000-0000-000000000002")
  44. resp, err := client.Do(req)
  45. if err != nil {
  46. log.Fatal(err)
  47. }
  48. defer resp.Body.Close()
  49. body, err := ioutil.ReadAll(resp.Body)
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. fmt.Println(string(body))
  54. }
  55. func main() {
  56. token, err := GetToken(JmsServerURL, UserName, Password)
  57. if err != nil {
  58. log.Fatal(err)
  59. }
  60. GetUserInfo(JmsServerURL, token)
  61. }

Private Token

  1. docker exec -it jms_core /bin/bash
  2. cd /opt/jumpserver/apps
  3. python manage.py shell
  4. from users.models import User
  5. u = User.objects.get(username='admin')
  6. u.create_private_token()

已经存在 private_token,可以直接获取即可

  1. u.private_token

以 PrivateToken: 937b38011acf499eb474e2fecb424ab3 为例:

  1. curl http://demo.jumpserver.org/api/v1/users/users/ \
  2. -H 'Authorization: Token 937b38011acf499eb474e2fecb424ab3' \
  3. -H 'Content-Type: application/json' \
  4. -H 'X-JMS-ORG: 00000000-0000-0000-0000-000000000002'

Python

  1. # Python 示例
  2. # pip install requests
  3. import requests, json
  4. def get_user_info(jms_url, token):
  5. url = jms_url + '/api/v1/users/users/'
  6. headers = {
  7. "Authorization": 'Token ' + token,
  8. 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002'
  9. }
  10. response = requests.get(url, headers=headers)
  11. print(json.loads(response.text))
  12. if __name__ == '__main__':
  13. jms_url = 'https://demo.jumpserver.org'
  14. token = '937b38011acf499eb474e2fecb424ab3'
  15. get_user_info(jms_url, token)

Golang

  1. // Golang 示例
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "strings"
  10. )
  11. const (
  12. JmsServerURL = "https://demo.jumpserver.org"
  13. JMSToken = "adminToken"
  14. )
  15. func GetUserInfo(jmsurl, token string) {
  16. url := jmsurl + "/api/v1/users/users/"
  17. client := &http.Client{}
  18. req, err := http.NewRequest("GET", url, nil)
  19. req.Header.Add("Authorization", "Token "+token)
  20. req.Header.Add("X-JMS-ORG", "00000000-0000-0000-0000-000000000002")
  21. resp, err := client.Do(req)
  22. if err != nil {
  23. log.Fatal(err)
  24. }
  25. defer resp.Body.Close()
  26. body, err := ioutil.ReadAll(resp.Body)
  27. if err != nil {
  28. log.Fatal(err)
  29. }
  30. fmt.Println(string(body))
  31. }
  32. func main() {
  33. GetUserInfo(JmsServerURL, JMSToken)
  34. }

Access Key

在 Web 页面 API Key 列表创建或获取 AccessKeyID AccessKeySecret

Python

  1. # Python 示例
  2. # pip install requests drf-httpsig
  3. import requests, datetime, json
  4. from httpsig.requests_auth import HTTPSignatureAuth
  5. def get_auth(KeyID, SecretID):
  6. signature_headers = ['(request-target)', 'accept', 'date']
  7. auth = HTTPSignatureAuth(key_id=KeyID, secret=SecretID, algorithm='hmac-sha256', headers=signature_headers)
  8. return auth
  9. def get_user_info(jms_url, auth):
  10. url = jms_url + '/api/v1/users/users/'
  11. gmt_form = '%a, %d %b %Y %H:%M:%S GMT'
  12. headers = {
  13. 'Accept': 'application/json',
  14. 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002',
  15. 'Date': datetime.datetime.utcnow().strftime(gmt_form)
  16. }
  17. response = requests.get(url, auth=auth, headers=headers)
  18. print(json.loads(response.text))
  19. if __name__ == '__main__':
  20. jms_url = 'https://demo.jumpserver.org'
  21. KeyID = 'AccessKeyID'
  22. SecretID = 'AccessKeySecret'
  23. auth = get_auth(KeyID, SecretID)
  24. get_user_info(jms_url, auth)

Golang

  1. // Golang 示例
  2. package main
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "time"
  9. "gopkg.in/twindagger/httpsig.v1"
  10. )
  11. const (
  12. JmsServerURL = "https://demo.jumpserver.org"
  13. AccessKeyID = "f7373851-ea61-47bb-8357-xxxxxxxxxxx"
  14. AccessKeySecret = "d6ed1a06-66f7-4584-af18-xxxxxxxxxxxx"
  15. )
  16. type SigAuth struct {
  17. KeyID string
  18. SecretID string
  19. }
  20. func (auth *SigAuth) Sign(r *http.Request) error {
  21. headers := []string{"(request-target)", "date"}
  22. signer, err := httpsig.NewRequestSigner(auth.KeyID, auth.SecretID, "hmac-sha256")
  23. if err != nil {
  24. return err
  25. }
  26. return signer.SignRequest(r, headers, nil)
  27. }
  28. func GetUserInfo(jmsurl string, auth *SigAuth) {
  29. url := jmsurl + "/api/v1/users/users/"
  30. gmtFmt := "Mon, 02 Jan 2006 15:04:05 GMT"
  31. client := &http.Client{}
  32. req, err := http.NewRequest("GET", url, nil)
  33. req.Header.Add("Date", time.Now().Format(gmtFmt))
  34. req.Header.Add("Accept", "application/json")
  35. req.Header.Add("X-JMS-ORG", "00000000-0000-0000-0000-000000000002")
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. if err := auth.Sign(req); err != nil {
  40. log.Fatal(err)
  41. }
  42. resp, err := client.Do(req)
  43. if err != nil {
  44. log.Fatal(err)
  45. }
  46. defer resp.Body.Close()
  47. body, err := ioutil.ReadAll(resp.Body)
  48. if err != nil {
  49. log.Fatal(err)
  50. }
  51. json.MarshalIndent(body, "", " ")
  52. fmt.Println(string(body))
  53. }
  54. func main() {
  55. auth := SigAuth{
  56. KeyID: AccessKeyID,
  57. SecretID: AccessKeySecret,
  58. }
  59. GetUserInfo(JmsServerURL, &auth)
  60. }

示例

Token

  1. #!/usr/bin/env python3
  2. # -*- coding:utf-8 -*-
  3. import sys, requests, time
  4. class HTTP:
  5. server = None
  6. token = None
  7. @classmethod
  8. def get_token(cls, username, password):
  9. data = {'username': username, 'password': password}
  10. url = "/api/v1/authentication/auth/"
  11. res = requests.post(cls.server + url, data)
  12. res_data = res.json()
  13. if res.status_code in [200, 201] and res_data:
  14. token = res_data.get('token')
  15. cls.token = token
  16. else:
  17. print("获取 token 错误, 请检查输入项是否正确")
  18. sys.exit()
  19. @classmethod
  20. def get(cls, url, params=None, **kwargs):
  21. url = cls.server + url
  22. headers = {
  23. 'Authorization': "Bearer {}".format(cls.token),
  24. 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002'
  25. }
  26. kwargs['headers'] = headers
  27. res = requests.get(url, params, **kwargs)
  28. return res
  29. @classmethod
  30. def post(cls, url, data=None, json=None, **kwargs):
  31. url = cls.server + url
  32. headers = {
  33. 'Authorization': "Bearer {}".format(cls.token),
  34. 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002'
  35. }
  36. kwargs['headers'] = headers
  37. res = requests.post(url, data, json, **kwargs)
  38. return res
  39. class User(object):
  40. def __init__(self):
  41. self.id = None
  42. self.name = user_name
  43. self.username = user_username
  44. self.email = user_email
  45. def exist(self):
  46. url = '/api/v1/users/users/'
  47. params = {'username': self.username}
  48. res = HTTP.get(url, params=params)
  49. res_data = res.json()
  50. if res.status_code in [200, 201] and res_data:
  51. self.id = res_data[0].get('id')
  52. else:
  53. self.create()
  54. def create(self):
  55. print("创建用户 {}".format(self.username))
  56. url = '/api/v1/users/users/'
  57. data = {
  58. 'name': self.name,
  59. 'username': self.username,
  60. 'email': self.email,
  61. 'is_active': True
  62. }
  63. res = HTTP.post(url, json=data)
  64. self.id = res.json().get('id')
  65. def perform(self):
  66. self.exist()
  67. class Node(object):
  68. def __init__(self):
  69. self.id = None
  70. self.name = asset_node_name
  71. def exist(self):
  72. url = '/api/v1/assets/nodes/'
  73. params = {'value': self.name}
  74. res = HTTP.get(url, params=params)
  75. res_data = res.json()
  76. if res.status_code in [200, 201] and res_data:
  77. self.id = res_data[0].get('id')
  78. else:
  79. self.create()
  80. def create(self):
  81. print("创建资产节点 {}".format(self.name))
  82. url = '/api/v1/assets/nodes/'
  83. data = {
  84. 'value': self.name
  85. }
  86. res = HTTP.post(url, json=data)
  87. self.id = res.json().get('id')
  88. def perform(self):
  89. self.exist()
  90. class AdminUser(object):
  91. def __init__(self):
  92. self.id = None
  93. self.name = assets_admin_name
  94. self.username = assets_admin_username
  95. self.password = assets_admin_password
  96. def exist(self):
  97. url = '/api/v1/assets/admin-user/'
  98. params = {'username': self.name}
  99. res = HTTP.get(url, params=params)
  100. res_data = res.json()
  101. if res.status_code in [200, 201] and res_data:
  102. self.id = res_data[0].get('id')
  103. else:
  104. self.create()
  105. def create(self):
  106. print("创建管理用户 {}".format(self.name))
  107. url = '/api/v1/assets/admin-users/'
  108. data = {
  109. 'name': self.name,
  110. 'username': self.username,
  111. 'password': self.password
  112. }
  113. res = HTTP.post(url, json=data)
  114. self.id = res.json().get('id')
  115. def perform(self):
  116. self.exist()
  117. class Asset(object):
  118. def __init__(self):
  119. self.id = None
  120. self.name = asset_name
  121. self.ip = asset_ip
  122. self.platform = asset_platform
  123. self.protocols = asset_protocols
  124. self.admin_user = AdminUser()
  125. self.node = Node()
  126. def exist(self):
  127. url = '/api/v1/assets/assets/'
  128. params = {
  129. 'hostname': self.name
  130. }
  131. res = HTTP.get(url, params)
  132. res_data = res.json()
  133. if res.status_code in [200, 201] and res_data:
  134. self.id = res_data[0].get('id')
  135. else:
  136. self.create()
  137. def create(self):
  138. print("创建资产 {}".format(self.ip))
  139. self.admin_user.perform()
  140. self.node.perform()
  141. url = '/api/v1/assets/assets/'
  142. data = {
  143. 'hostname': self.ip,
  144. 'ip': self.ip,
  145. 'platform': self.platform,
  146. 'protocols': self.protocols,
  147. 'admin_user': self.admin_user.id,
  148. 'nodes': [self.node.id],
  149. 'is_active': True
  150. }
  151. res = HTTP.post(url, json=data)
  152. self.id = res.json().get('id')
  153. def perform(self):
  154. self.exist()
  155. class SystemUser(object):
  156. def __init__(self):
  157. self.id = None
  158. self.name = assets_system_name
  159. self.username = assets_system_username
  160. def exist(self):
  161. url = '/api/v1/assets/system-users/'
  162. params = {'name': self.name}
  163. res = HTTP.get(url, params)
  164. res_data = res.json()
  165. if res.status_code in [200, 201] and res_data:
  166. self.id = res_data[0].get('id')
  167. else:
  168. self.create()
  169. def create(self):
  170. print("创建系统用户 {}".format(self.name))
  171. url = '/api/v1/assets/system-users/'
  172. data = {
  173. 'name': self.name,
  174. 'username': self.username,
  175. 'login_mode': 'auto',
  176. 'protocol': 'ssh',
  177. 'auto_push': True,
  178. 'sudo': 'All',
  179. 'shell': '/bin/bash',
  180. 'auto_generate_key': True,
  181. 'is_active': True
  182. }
  183. res = HTTP.post(url, json=data)
  184. self.id = res.json().get('id')
  185. def perform(self):
  186. self.exist()
  187. class AssetPermission(object):
  188. def __init__(self):
  189. self.name = perm_name
  190. self.user = User()
  191. self.asset = Asset()
  192. self.system_user = SystemUser()
  193. def create(self):
  194. print("创建资产授权名称 {}".format(self.name))
  195. url = '/api/v1/perms/asset-permissions/'
  196. data = {
  197. 'name': self.name,
  198. 'users': [self.user.id],
  199. 'assets': [self.asset.id],
  200. 'system_users': [self.system_user.id],
  201. 'actions': ['all'],
  202. 'is_active': True,
  203. 'date_start': perm_date_start,
  204. 'date_expired': perm_date_expired
  205. }
  206. res = HTTP.post(url, json=data)
  207. res_data = res.json()
  208. if res.status_code in [200, 201] and res_data:
  209. print("创建资产授权规则成功: ", res_data)
  210. else:
  211. print("创建授权规则失败: ", res_data)
  212. def perform(self):
  213. self.user.perform()
  214. self.asset.perform()
  215. self.system_user.perform()
  216. self.create()
  217. class APICreateAssetPermission(object):
  218. def __init__(self):
  219. self.jms_url = jms_url
  220. self.username = jms_username
  221. self.password = jms_password
  222. self.token = None
  223. self.server = None
  224. def init_http(self):
  225. HTTP.server = self.jms_url
  226. HTTP.get_token(self.username, self.password)
  227. def perform(self):
  228. self.init_http()
  229. self.perm = AssetPermission()
  230. self.perm.perform()
  231. if __name__ == '__main__':
  232. # jumpserver url 地址
  233. jms_url = 'http://192.168.100.244'
  234. # 管理员账户
  235. jms_username = 'admin'
  236. jms_password = 'admin'
  237. # 资产节点
  238. asset_node_name = 'test'
  239. # 资产信息
  240. asset_name = '192.168.100.1'
  241. asset_ip = '192.168.100.1'
  242. asset_platform = 'Linux'
  243. asset_protocols = ['ssh/22']
  244. # 资产管理用户
  245. assets_admin_name = 'test_root'
  246. assets_admin_username = 'root'
  247. assets_admin_password = 'test123456'
  248. # 资产系统用户
  249. assets_system_name = 'test'
  250. assets_system_username = 'test'
  251. # 用户用户名
  252. user_name = '测试用户'
  253. user_username = 'test'
  254. user_email = 'test@jumpserver.org'
  255. # 资产授权
  256. perm_name = 'AutoPerm' +'_'+ (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
  257. perm_date_start = '2021-05-01 14:25:47 +0800'
  258. perm_date_expired = '2021-06-01 14:25:47 +0800'
  259. api = APICreateAssetPermission()
  260. api.perform()

Access Key

  1. #!/usr/bin/env python3
  2. # -*- coding:utf-8 -*-
  3. import sys, requests, time, datetime
  4. from httpsig.requests_auth import HTTPSignatureAuth
  5. class HTTP:
  6. server = None
  7. auth = None
  8. @classmethod
  9. def get_auth(cls, accesskeyid, accesskeysecret):
  10. signature_headers = ['(request-target)', 'accept', 'date']
  11. auth = HTTPSignatureAuth(key_id=accesskeyid, secret=accesskeysecret, algorithm='hmac-sha256', headers=signature_headers)
  12. cls.auth = auth
  13. @classmethod
  14. def get(cls, url, params=None, **kwargs):
  15. url = cls.server + url
  16. GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
  17. headers = {
  18. 'Accept': 'application/json',
  19. 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002',
  20. 'Date': datetime.datetime.utcnow().strftime(GMT_FORMAT)
  21. }
  22. kwargs['auth'] = cls.auth
  23. kwargs['headers'] = headers
  24. res = requests.get(url, params, **kwargs)
  25. return res
  26. @classmethod
  27. def post(cls, url, data=None, json=None, **kwargs):
  28. url = cls.server + url
  29. GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
  30. headers = {
  31. 'Accept': 'application/json',
  32. 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002',
  33. 'Date': datetime.datetime.utcnow().strftime(GMT_FORMAT)
  34. }
  35. kwargs['auth'] = cls.auth
  36. kwargs['headers'] = headers
  37. res = requests.post(url, data, json, **kwargs)
  38. return res
  39. class User(object):
  40. def __init__(self):
  41. self.id = None
  42. self.name = user_name
  43. self.username = user_username
  44. self.email = user_email
  45. def exist(self):
  46. url = '/api/v1/users/users/'
  47. params = {'username': self.username}
  48. res = HTTP.get(url, params=params)
  49. res_data = res.json()
  50. if res.status_code in [200, 201] and res_data:
  51. self.id = res_data[0].get('id')
  52. else:
  53. self.create()
  54. def create(self):
  55. print("创建用户 {}".format(self.username))
  56. url = '/api/v1/users/users/'
  57. data = {
  58. 'name': self.name,
  59. 'username': self.username,
  60. 'email': self.email,
  61. 'is_active': True
  62. }
  63. res = HTTP.post(url, json=data)
  64. self.id = res.json().get('id')
  65. def perform(self):
  66. self.exist()
  67. class Node(object):
  68. def __init__(self):
  69. self.id = None
  70. self.name = asset_node_name
  71. def exist(self):
  72. url = '/api/v1/assets/nodes/'
  73. params = {'value': self.name}
  74. res = HTTP.get(url, params=params)
  75. res_data = res.json()
  76. if res.status_code in [200, 201] and res_data:
  77. self.id = res_data[0].get('id')
  78. else:
  79. self.create()
  80. def create(self):
  81. print("创建资产节点 {}".format(self.name))
  82. url = '/api/v1/assets/nodes/'
  83. data = {
  84. 'value': self.name
  85. }
  86. res = HTTP.post(url, json=data)
  87. self.id = res.json().get('id')
  88. def perform(self):
  89. self.exist()
  90. class AdminUser(object):
  91. def __init__(self):
  92. self.id = None
  93. self.name = assets_admin_name
  94. self.username = assets_admin_username
  95. self.password = assets_admin_password
  96. def exist(self):
  97. url = '/api/v1/assets/admin-user/'
  98. params = {'username': self.name}
  99. res = HTTP.get(url, params=params)
  100. res_data = res.json()
  101. if res.status_code in [200, 201] and res_data:
  102. self.id = res_data[0].get('id')
  103. else:
  104. self.create()
  105. def create(self):
  106. print("创建管理用户 {}".format(self.name))
  107. url = '/api/v1/assets/admin-users/'
  108. data = {
  109. 'name': self.name,
  110. 'username': self.username,
  111. 'password': self.password
  112. }
  113. res = HTTP.post(url, json=data)
  114. self.id = res.json().get('id')
  115. def perform(self):
  116. self.exist()
  117. class Asset(object):
  118. def __init__(self):
  119. self.id = None
  120. self.name = asset_name
  121. self.ip = asset_ip
  122. self.platform = asset_platform
  123. self.protocols = asset_protocols
  124. self.admin_user = AdminUser()
  125. self.node = Node()
  126. def exist(self):
  127. url = '/api/v1/assets/assets/'
  128. params = {
  129. 'hostname': self.name
  130. }
  131. res = HTTP.get(url, params)
  132. res_data = res.json()
  133. if res.status_code in [200, 201] and res_data:
  134. self.id = res_data[0].get('id')
  135. else:
  136. self.create()
  137. def create(self):
  138. print("创建资产 {}".format(self.ip))
  139. self.admin_user.perform()
  140. self.node.perform()
  141. url = '/api/v1/assets/assets/'
  142. data = {
  143. 'hostname': self.ip,
  144. 'ip': self.ip,
  145. 'platform': self.platform,
  146. 'protocols': self.protocols,
  147. 'admin_user': self.admin_user.id,
  148. 'nodes': [self.node.id],
  149. 'is_active': True
  150. }
  151. res = HTTP.post(url, json=data)
  152. self.id = res.json().get('id')
  153. def perform(self):
  154. self.exist()
  155. class SystemUser(object):
  156. def __init__(self):
  157. self.id = None
  158. self.name = assets_system_name
  159. self.username = assets_system_username
  160. def exist(self):
  161. url = '/api/v1/assets/system-users/'
  162. params = {'name': self.name}
  163. res = HTTP.get(url, params)
  164. res_data = res.json()
  165. if res.status_code in [200, 201] and res_data:
  166. self.id = res_data[0].get('id')
  167. else:
  168. self.create()
  169. def create(self):
  170. print("创建系统用户 {}".format(self.name))
  171. url = '/api/v1/assets/system-users/'
  172. data = {
  173. 'name': self.name,
  174. 'username': self.username,
  175. 'login_mode': 'auto',
  176. 'protocol': 'ssh',
  177. 'auto_push': True,
  178. 'sudo': 'All',
  179. 'shell': '/bin/bash',
  180. 'auto_generate_key': True,
  181. 'is_active': True
  182. }
  183. res = HTTP.post(url, json=data)
  184. self.id = res.json().get('id')
  185. def perform(self):
  186. self.exist()
  187. class AssetPermission(object):
  188. def __init__(self):
  189. self.name = perm_name
  190. self.user = User()
  191. self.asset = Asset()
  192. self.system_user = SystemUser()
  193. def create(self):
  194. print("创建资产授权名称 {}".format(self.name))
  195. url = '/api/v1/perms/asset-permissions/'
  196. data = {
  197. 'name': self.name,
  198. 'users': [self.user.id],
  199. 'assets': [self.asset.id],
  200. 'system_users': [self.system_user.id],
  201. 'actions': ['all'],
  202. 'is_active': True,
  203. 'date_start': perm_date_start,
  204. 'date_expired': perm_date_expired
  205. }
  206. res = HTTP.post(url, json=data)
  207. res_data = res.json()
  208. if res.status_code in [200, 201] and res_data:
  209. print("创建资产授权规则成功: ", res_data)
  210. else:
  211. print("创建授权规则失败: ", res_data)
  212. def perform(self):
  213. self.user.perform()
  214. self.asset.perform()
  215. self.system_user.perform()
  216. self.create()
  217. class APICreateAssetPermission(object):
  218. def __init__(self):
  219. self.jms_url = jms_url
  220. self.accesskeyid = jms_accesskeyid
  221. self.accesskeysecret = jms_accesskeysecret
  222. self.auth = None
  223. self.server = None
  224. def init_http(self):
  225. HTTP.server = self.jms_url
  226. HTTP.get_auth(self.accesskeyid, self.accesskeysecret)
  227. def perform(self):
  228. self.init_http()
  229. self.perm = AssetPermission()
  230. self.perm.perform()
  231. if __name__ == '__main__':
  232. # jumpserver url 地址
  233. jms_url = 'http://192.168.100.244'
  234. # 管理员 AK SK
  235. jms_accesskeyid = ''
  236. jms_accesskeysecret = ''
  237. # 资产节点
  238. asset_node_name = 'test'
  239. # 资产信息
  240. asset_name = '192.168.100.1'
  241. asset_ip = '192.168.100.1'
  242. asset_platform = 'Linux'
  243. asset_protocols = ['ssh/22']
  244. # 资产管理用户
  245. assets_admin_name = 'test_root'
  246. assets_admin_username = 'root'
  247. assets_admin_password = 'test123456'
  248. # 资产系统用户
  249. assets_system_name = 'test'
  250. assets_system_username = 'test'
  251. # 用户用户名
  252. user_name = '测试用户'
  253. user_username = 'test'
  254. user_email = 'test@jumpserver.org'
  255. # 资产授权
  256. perm_name = 'AutoPerm' +'_'+ (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
  257. perm_date_start = '2021-05-01 14:25:47 +0800'
  258. perm_date_expired = '2021-06-01 14:25:47 +0800'
  259. api = APICreateAssetPermission()
  260. api.perform()