惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Vulnerabilities – Threatpost
雷峰网
雷峰网
GbyAI
GbyAI
F
Fortinet All Blogs
MyScale Blog
MyScale Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 聂微东
V
V2EX
Jina AI
Jina AI
Apple Machine Learning Research
Apple Machine Learning Research
C
CXSECURITY Database RSS Feed - CXSecurity.com
美团技术团队
Engineering at Meta
Engineering at Meta
T
Tenable Blog
P
Privacy & Cybersecurity Law Blog
Project Zero
Project Zero
Cloudbric
Cloudbric
Help Net Security
Help Net Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
LINUX DO - 热门话题
J
Java Code Geeks
WordPress大学
WordPress大学
S
Securelist
F
Full Disclosure
N
News and Events Feed by Topic
B
Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
I
InfoQ
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
U
Unit 42
Google Online Security Blog
Google Online Security Blog
Spread Privacy
Spread Privacy
P
Proofpoint News Feed
宝玉的分享
宝玉的分享
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Schneier on Security
Schneier on Security
Google DeepMind News
Google DeepMind News
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
月光博客
月光博客
Martin Fowler
Martin Fowler
T
Threat Research - Cisco Blogs
小众软件
小众软件
V2EX - 技术
V2EX - 技术
Last Week in AI
Last Week in AI
Stack Overflow Blog
Stack Overflow Blog
The Last Watchdog
The Last Watchdog
D
DataBreaches.Net

博客园 - 一起走过的路

Nginx GeoIP2 模块编译安装与配置指南(附防国外访问实战) MySQL查询当前连接数的语句 物理机Jenkins接入K8s环境 ingress配置https报错certificate.lua:259: call(): failed to set DER private key: d2i_PrivateKey_bio() failed, context: ssl_certificate_by_lua* elk收集分析nginx日志,并绘制图形 Zabbix Scheduled reports中文乱码 kubernetes mysql-StatefulSet报错处理 Jenkins合并代码Git报错处理过程 nginx集群同步方案 zabbix密码复杂度有效期安全增强,符合三级等保要求。 archery关闭导出功能 自动同步bing壁纸 CentOS7更新OpenSSH8 elk监听Java日志发送微信报警 OPENVPN 同时连接多个VPN - 一起走过的路 nginx拒绝国外IP访问 keepalived健康检查及双主MySQL健康检查脚本 执迷不悟 splunk设置索引周期和索引大小
Apollo批量给新创建的用户授可编辑权限
一起走过的路 · 2023-06-13 · via 博客园 - 一起走过的路

背景:

  我们要在Apollo中批量给新创建的用户授可编辑权限

  apollo系统版本: java-2.1.0

  管理员账号:Apollo

  可编辑账号:guoyabin

过程:

  在没写这段代码的时候从网上搜了一些文章如下:
  apollo_adminservice、apollo_configservice改成自己的域名,在不知道用户密码的前提下可以获取cluster、app_ids、namespaces的脚本。

# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : apollo.py
# Time       :2023/6/6/006 11:01
# Author     :GuoYabin
# version    :python 3.8
# Description:利用apollo_adminservice的8090和apollo_configservice的8080
               获取所有Apollo环境/appid/cluster
"""
import json
import time
import requests
from urllib.parse import urlparse


def get_response(uri):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20200101 Firefox/60.0",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "close"
    }
    return requests.get(uri, headers=headers, timeout=20, allow_redirects=False)


def get_app_ids(uri):
    print(uri)
    app_ids = []
    response = get_response("{}/apps".format(uri))
    html = response.text
    print(html)
    if response.status_code == 200:
        for app in json.loads(html):
            app_ids.append(app.get("appId"))
    return app_ids


def get_clusters(uri, app_ids):
    clusters = {}
    for app_id in app_ids:
        clusters[app_id] = []
        response = get_response("{}/apps/{}/clusters".format(uri, app_id))
        html = response.text
        if response.status_code == 200:
            for app in json.loads(html):
                clusters[app_id].append(app.get("name"))
    return clusters


def get_namespaces(uri, app_ids, clusters):
    namespaces = {}
    for app_id in app_ids:
        namespaces[app_id] = []
        for cluster in clusters[app_id]:
            url = "{}/apps/{}/clusters/{}/namespaces".format(uri, app_id, cluster)
            response = get_response(url)
            html = response.text
            if response.status_code == 200:
                for app in json.loads(html):
                    namespaces[app_id].append(app.get("namespaceName"))
    return namespaces


def get_configurations(uri, app_ids, clusters, namespaces):
    configurations = []
    for app_id in app_ids:
        for cluster in clusters[app_id]:
            for namespace in namespaces[app_id]:
                key_name = "{}-{}-{}".format(app_id, cluster, namespace)
                url = "{}/configs/{}/{}/{}".format(uri, app_id, cluster, namespace)
                response = get_response(url)
                code = response.status_code
                html = response.text
                print("[+] get {} configs, status: {}".format(url, code))
                time.sleep(1)
                if code == 200:
                    configurations.append({key_name: json.loads(html)})
    return configurations


if __name__ == "__main__":
    apollo_adminservice = "http://192.168.40.185:8090"
    apollo_configservice = "http://192.168.40.185:8080"

    scheme0, netloc0, path0, params0, query0, fragment0 = urlparse(apollo_adminservice)
    host0 = "{}://{}".format(scheme0, netloc0)

    _ids = get_app_ids(host0)
    print("All appIds:")
    print(_ids)

    _clusters = get_clusters(host0, _ids)
    print("\nAll Clusters:")
    print(_clusters)

    _namespaces = get_namespaces(host0, _ids, _clusters)
    print("\nAll Namespaces:")
    print(_namespaces)
    print()

    scheme1, netloc1, path1, params1, query1, fragment1 = urlparse(apollo_configservice)
    host1 = "{}://{}".format(scheme1, netloc1)
    _configurations = get_configurations(host1, _ids, _clusters, _namespaces)
    print("\nresults:\n")
    print(_configurations)

解决方法:

  下面我们自己写一个批量授权的方法、使用管理员apollo给guoyabin账号授权,允许guoyabin账号可以编辑,但无法发布权限。

# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : apollo.py
# Time       :2023/6/6/006 11:01
# Author     :GuoYabin
# version    :python 3.8
# Description:模拟Apollo登陆,获取所有envs/appid添加guoyabin账号编辑权限
"""

import requests
import json

class apollo:
    def __init__(self):
        self.username = "apollo"
        self.password = "*********"
        self.apollourl = "http://**************"
        self.addauth = "guoyabin"
        self.session = requests.session()
        self.headers = self.setheaders()

    def login(self):
        url = '{}/signin'.format(self.apollourl)
        payload = {
            "username": self.username,
            "password": self.password,
            "login-submit": "登录"
        }
        self.session.post(url=url,data=payload)
        res = self.session.cookies
        return (res.get_dict()['SESSION'])

    def setheaders(self):
        session = self.login()
        myheaders = {
            "Accept": "application/json, text/plain, */*",
            "Cookie": "Hm_lvt_488a0e7e13b847119c47d080b3dc7272=1677469471; NG_TRANSLATE_LANG_KEY=zh-CN; SESSION={0}".format(session),
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"
        }
        return (myheaders)

    def getenvs(self):
        url = 'http://{}/envs'.format(self.apollourl)
        head = self.headers
        res = requests.get(url=url,headers=head)
        return (res.text)

    def getappid(self):
        url = 'http://{}/apps'.format(self.apollourl)
        params = {'page': 0}
        res = requests.get(url, params=params,headers=self.headers)
        date = json.loads(res.text)
        allapp = [d['appId'] for d in date]
        return (allapp)

    def addauth(self,appid):
        uri = 'http://{0}/apps/{1}/namespaces/application/roles/ModifyNamespace'.format(self.apollourl,appid)
        playload = self.addauth
        try:
            response = requests.post(url=uri,data=playload,headers=self.headers)
            response.raise_for_status()
        except requests.exceptions.HTTPError as error:
            json_data = error.response.json()
            error_message = json_data['message']
            print(appid,error_message)

if __name__ == '__main__':
    apollo_obj = apollo()
    for i in apollo_obj.getappid():
        apollo_obj.addauth(i)