跳至主要內容
python 实际工作中的实例

python 实际工作中的实例

让 windows 压测机 解析内网进行压测,避免占用外网带宽

1)生成 hosts 解析文件,将解析文件分成 N 份,解析到不同的 内网ip

cat sync_xxx_hosts.py

#!/usr/bin/env python3
import requests
import json

def get_hosts():
    # 调用 api 获取所有 nginx 主机 ip 地址
    try:
        response = requests.get(
            url="https://xxx/api/v1/appid/xxx/hosts",
            headers={
                "Authorization": "xxx",
                "Content-Type": "application/json; charset=utf-8",
            },
            data=json.dumps({}))
        result = response.json()['data']['assets']
        hosts = [host['ip'] for host in result]
        return hosts

    except requests.exceptions.RequestException:
        print('HTTP Request failed')

def send_request():
    # 调用 api 获取域名列表
    try:
        response = requests.get(
            url=
            "xxx",
            headers={
                "Authorization": "xxx",
                "Content-Type": "application/json; charset=utf-8",
            },
            data=json.dumps({}))
        result = response.json()['data']
        prod_domain_list = [
            domain['name'] for domain in result
            if domain['lbcluster']['id'] == 1
        ]
        ext_website_domain_list = [
            domain['name'] for domain in result
            if domain['lbcluster']['id'] == 9
        ]
        # 通过域名获取不到的 域名列表,和nginx地址
        xx_domain_list = [
            'xxx.xxx.xx'
        ]
        ext_website_hosts = get_hosts()
        for i in range(0, 8):
            filename = f'/etc/ansible/files/hosts{i}'
            with open(filename, 'w') as f:
                for xx_domain in xx_domain_list:
                    f.write('IP地址 ' + bi_domain + '\n')
                for domain in prod_domain_list:
                    f.write('IP地址 ' + domain + '\n')
                for domain in ext_website_domain_list:
                    host = ext_website_hosts[i]
                    f.write(host + ' ' + domain + '\n')
    except requests.exceptions.RequestException:
        print('HTTP Request failed')


if __name__ == '__main__':
    send_request()

Clay大约 14 分钟Python工作脚本