暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

从zabbix添加主机到jumpserver!

Zabbix开源社区 2025-12-23
170
    请看视频
   Jumpserver就不多介绍了,国内知名的开源跳板机软件,我从16年开始就在使用Jumpserver,后来还进行了二开,为它添加企业微信验证码功能。可能有小伙伴要说了,Jumpserver早就支持企业微信登录了,但是我说的可是17年,当时Jumpserver官方并不支持企业微信登录。
    当然,说这些不是想让大家去使用这个项目,因为它已经过时了,只是想跟大家分享Jumpserver的新思路。

项目地址

https://github.com/XWJR-Ops/Jumpserver-VerificationCode

项目截图

    相信很多朋友也在使用Jumpserver,也在手工维护主机列表。我这边有4个Jumpsever的环境,4000余台主机,如果每天手动添加主机,那是很耗时,也很崩溃的事情。于是我开发了一系列的添加主机到Jumpserver的脚本,今天为大家带来的是:Zabbix自动添加主机到Jumpserver!

脚本介绍

    本脚本主要有如下功能

  1. 获取zabbix的主机列表,以及对应的主机分组和监控项Operating system(识别操作系统是Linux 还是Windows)

  2. 获取Jumpserver的主机列表、节点列表(分组列表)

  3. 如果zabbix主机对应的分组在Jumpserver中不存在,就在Jumpserver创建节点(分组)

  4. 如果zabbix主机在Jumpserver中不存在,就在Jumpserver创建主机,并设置对应的节点(分组)

  5. 如果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-httpsig
    import requests, datetime, json
    from httpsig.requests_auth import HTTPSignatureAuth
    # from zabbix import Zabbix
    DEBUG = False


    class 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_list




    class 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_list
            if 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_list
                if 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开发了cmdb和报表插件,强烈推荐你在如下文章中获取:
    30秒!给zabbix加上cmdb和报表功能!领导直夸我“牛×”!
    又双叒叕更新了!这次是zabbix cmdb功能!
    zabbix 7.0安装部署-0成本实现监控大屏,30秒装杯成功
         同时,笔者也为zabbix开发了企业微信机器人、钉钉机器人、飞书机器人告警脚本,你可以如下文章中获取:
    又短又快!?zabbix 企业微信机器人webhook告警脚本
    还有谁?!zabbix 钉钉机器人webhook告警脚本!
    还有我!zabbix 飞书机器人webhook告警脚本!
         AI装杯神器:
    报告老板!我们的zabbix已经对接deepseek!
    • 写在最后

        下一章节,你想学习什么?关注本公众号告诉我。
        添加作者微信好友,加入微信交流群(时不时有红包哦)!
        如果你认为这篇文章帮助到了你,请点击“喜欢作者,”请我喝杯牛马咖啡。点亮👍🏻与❤️,并转发到朋友圈。
        点击阅读全网,会有惊喜哦。


    文章转载自Zabbix开源社区,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

    评论