项目地址
https://github.com/XWJR-Ops/Jumpserver-VerificationCode
项目截图

相信很多朋友也在使用Jumpserver,也在手工维护主机列表。我这边有4个Jumpsever的环境,4000余台主机,如果每天手动添加主机,那是很耗时,也很崩溃的事情。于是我开发了一系列的添加主机到Jumpserver的脚本,今天为大家带来的是:Zabbix自动添加主机到Jumpserver!
脚本介绍
本脚本主要有如下功能
获取zabbix的主机列表,以及对应的主机分组和监控项Operating system(识别操作系统是Linux 还是Windows)
获取Jumpserver的主机列表、节点列表(分组列表)
如果zabbix主机对应的分组在Jumpserver中不存在,就在Jumpserver创建节点(分组)
如果zabbix主机在Jumpserver中不存在,就在Jumpserver创建主机,并设置对应的节点(分组)
如果zabbix主机在Jumpserver中存在,就在Jumpserver更新主机
Jumpserver官方的示例
https://docs.jumpserver.org/zh/v4/dev/rest_api/#2-api
脚本开发环境
zabbix:7.0.21
Jumpserver:v4.10.8
python:3.10.7 (理论上兼容所有python3)
脚本使用
创建zabbix api 令牌

创建jumpserver AccessKeyID AccessKeySecret

完整脚本
# Python 示例# pip install requests drf-httpsigimport requests, datetime, jsonfrom httpsig.requests_auth import HTTPSignatureAuth# from zabbix import ZabbixDEBUG = Falseclass Zabbix(object):def __init__(self):self.base_url = 'http://192.168.3.243/zabbix/api_jsonrpc.php'self.token = 'ZABBIXTOKEN'self.headers = {'Authorization': f'Bearer {self.token}',}# 获取主机操作系统平台def get_platform_zabbix(self, items_list):platform = 'Other'for item in items_list:if item['name'] == 'Operating system':if 'Linux' in item['lastvalue'] or 'linux' in item['lastvalue']:platform = 'Linux'elif 'Windows' in item['lastvalue'] or 'windows' in item['lastvalue']:platform = 'Windows'else:platform = 'Other'return platform# 格式化主机信息def get_format_host_info(self, host_list):host_list_new = []for host in host_list:data = {}data['platform'] = self.get_platform_zabbix(host['items'])data['name'] = host['host']data['host_groups'] = [group['name'] for group in host['hostgroups']]data['ip'] = host['interfaces'][0]['ip']host_list_new.append(data)print(host_list_new)return host_list_new# 获取主机列表def get_host_list(self):payload = {'jsonrpc': '2.0','method': 'host.get','params': {'output': ['hostid', 'host'],'selectHostGroups': ['name'],'selectInterfaces': ['ip'],'selectItems': ['name', 'lastvalue'],'filter': {'type': 1}},'id': 1}response = requests.post(self.base_url, json=payload, headers=self.headers)host_list = self.get_format_host_info(response.json()['result'])return host_listclass Jumpserver(Zabbix):def __init__(self):super().__init__()self.jms_url = 'http://192.168.3.29'self.key_id = 'AccessKeyID'self.secret_id = 'AccessKeySecret'self.auth = self.get_auth()self.host_list_zabbix = self.get_host_list()self.host_dict_jumpserver = {}self.asset_nodes_dict = {}self.asset_nodes_list = []self.platform_dict = {}self.platform_list = []self.gmt_form = '%a, %d %b %Y %H:%M:%S GMT'self.headers = {'Accept': 'application/json','X-JMS-ORG': '00000000-0000-0000-0000-000000000002','Date': datetime.datetime.utcnow().strftime(self.gmt_form)}# 获取跳板机系统认证信息def get_auth(self):signature_headers = ['(request-target)', 'accept', 'date']auth = HTTPSignatureAuth(key_id=self.key_id, secret=self.secret_id, algorithm='hmac-sha256',headers=signature_headers)return auth# 获取跳板机系统用户信息def get_user_info(self):url = self.jms_url + '/api/v1/users/users/'response = requests.get(url, auth=self.auth, headers=self.headers)if DEBUG:print(response.status_code)print(response.text)# 获取跳板机系统平台和协议列表def get_platform_and_protocol(self):url = self.jms_url + '/api/v1/assets/platforms/'response = requests.get(url, auth=self.auth, headers=self.headers)self.platform_list = response.json()for platform in self.platform_list:self.platform_dict[platform['name']] = {'id': platform['id'],'pk': platform['id']}protocol_list = []for protocol in platform['protocols']:protocol_list.append({'name': protocol['name'],'port': protocol['port']})self.platform_dict[platform['name']]['protocols'] = protocol_listif DEBUG:print(response.status_code)print(response.text)# 获取跳板机系统主机列表def get_host_list_jumpserver(self):url = self.jms_url + '/api/v1/assets/hosts/'response = requests.get(url, auth=self.auth, headers=self.headers)host_info_list = response.json()for host_info in host_info_list:self.host_dict_jumpserver[host_info['name']] = host_info# 获取跳板机系统节点信息def get_asset_nodes(self):url = self.jms_url + '/api/v1/assets/nodes/'response = requests.get(url, auth=self.auth, headers=self.headers)for node_info in response.json():self.asset_nodes_dict[node_info['name']] = node_info['id']self.asset_nodes_list = response.json()if DEBUG:print(response.status_code)print(response.text)# 创建节点到跳板机系统def create_node(self, name):url = self.jms_url + '/api/v1/assets/nodes/'data = {'value': name,'full_value': name}response = requests.post(url, auth=self.auth, headers=self.headers, json=data)if DEBUG:print(response.status_code)print(response.text)return response.json()['id']# 创建主机到跳板机系统def create_host(self, host_info):url = self.jms_url + '/api/v1/assets/hosts/'response = requests.post(url, auth=self.auth, headers=self.headers, json=host_info)if DEBUG:print(response.status_code)print(response.text)# 更新主机信息到跳板机系统def update_host(self, host_info):host_id = self.host_dict_jumpserver[host_info['name']]['id']url = self.jms_url + f'/api/v1/assets/hosts/{host_id}/'response = requests.patch(url, auth=self.auth, headers=self.headers, json=host_info)if DEBUG:print(response.status_code)print(response.text)# 创建或更新主机到跳板机系统def create_or_update_host(self):for host_info in self.host_list_zabbix:data = {'labels': [],'is_active': True,'name': host_info['name'],'address': host_info['ip'],'accounts': []}if host_info['platform'] in self.platform_dict:platform_name = host_info['platform']data['platform'] = {'pk': self.platform_dict[platform_name]['pk']}data['protocols'] = self.platform_dict[platform_name]['protocols']nodes_list = []for group in host_info['host_groups']:if group in self.asset_nodes_dict:nodes_list.append({'pk': self.asset_nodes_dict[group]})else:nodes_list.append({'pk': self.create_node(group)})data['nodes'] = nodes_listif host_info['name'] not in self.host_dict_jumpserver:print(f"正在创建主机 {host_info['name']} 到跳板机系统中")self.create_host(host_info=data)else:print(f"正在更新主机 {host_info['name']} 到跳板机系统中")self.update_host(host_info=data)J = Jumpserver()J.get_platform_and_protocol()J.get_host_list_jumpserver()J.get_asset_nodes()J.create_or_update_host()
其他推荐设置
写在最后


往期文章 zabbix webhook 告警脚本合集 zabbix 7.0安装部署-批量部署zabbix agent 一个openresty的通用的企业微信、飞书、钉钉登陆对接模块 离了个大谱!zabbix居然能对接天猫精灵! zabbix 7.0安装部署-自动添加主机,并自动注册。 zabbix 7.0安装部署-0成本实现监控大屏,30秒装杯成功 30秒!给zabbix加上cmdb和报表功能!领导直夸我“牛×”! 我这有4000多个zabbix监控模板你信不信? 不是看不起你,这种安装操作系统的神器,你可能从未听过! zabbix 7.0安装教程-使用centos 7 进行部署 zabbix 7.0安装教程-Rocky Linux安装zabbix 7.0(看完不会建议转行) 无需入侵源码,0成本为web项目添加企业微信等三方登录! 你是不是吹捧prometheus诋毁zabbix的“井底之蛙”? 别再当“迷信”ansible的“傻子”了 zabbix7一键安装脚本,支持10多个操作系统哦 
文章转载自Zabbix开源社区,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




