API 文档

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

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

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

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

    Session

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

    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

    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 -H 'Authorization: Token 937b38011acf499eb474e2fecb424ab3' \
    2. -H "Content-Type:application/json" http://demo.jumpserver.org/api/v1/users/users/
    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

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