Python脚本正则表达式获取Linux防火墙ip、ip、解析json、输出文件

三年前写的,这个是Linux版本的 还有个windows版,具体场景不记得了,但可以做参考
获取ip、解析json、输出文件

# -*- coding: UTF-8 -*-
import requests
import os
import socket
import re

'''
获取ip
'''


def get_ip():
    with os.popen('ifconfig') as cmd:
        str = cmd.readlines()
        data = str[1].strip()
    if not data.__contains__("inet 10.10"):
        raise ValueError("没有符合规则的ip  inet 10.10")

    return re.search('inet (10.10.[\d]{1,3}.[\d]{1,3})', data).group(1)


'''
  接口调用---解析json
'''


def get_json():
    # 调获取本机名方法
    # 请求地址,主机名不可写死
    url = "https://tws.com/r/global//v1/hosting/machine?computerName=%s" %(socket.gethostname())
    # 发送get请求获取返回的json数据
    r = str(requests.get(url).json())
    if not r.__contains__("firewallIp"):
        raise ValueError("未获取到防火墙IP")
    return r


'''
输出为custom_data.prom文件
'''


def make_file(ip, firewallip, port):
    with open('/home//node_exporter/textfile/custom_data.prom', 'w', encoding="utf-8") as f:  # 覆盖显示
        f.write('textfile_windows_meta { ip="%s", firewall="%s", machinetype="宿主机", cabinet="%s" } 1\n' % (ip, firewallip, port))
        print("ok")


def main():
    try:
        # ip = get_ip()
        firewallip = re.search('firewallIp\': \'([\d]{1,3}.[\d]{1,3}.[\d]{1,3}.[\d]{1,3})', get_json()).group(1)
        port = re.search('rackNumber\': (\'A[\d]{1,3})', get_json()).group(1)
        make_file(get_ip(), firewallip, port)
    except Exception as e:
        print(e)



main()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值