2023-02-19 17:59:18 +01:00
|
|
|
#!/usr/bin/python3
|
|
|
|
|
2023-03-10 00:09:04 +01:00
|
|
|
import re
|
|
|
|
import json
|
|
|
|
import urllib
|
|
|
|
from urllib.request import urlopen, Request
|
|
|
|
from urllib.parse import urljoin
|
|
|
|
from urllib.error import HTTPError
|
|
|
|
|
|
|
|
MIN_CIDR=32
|
|
|
|
CIDR_REGEX = re.compile(r"(.*)/(.*)")
|
|
|
|
POSTFIX_FORMAT = lambda ip: "[{}]/{}".format(CIDR_REGEX.findall(ip)[0][0],
|
|
|
|
CIDR_REGEX.findall(ip)[0][1])
|
|
|
|
|
|
|
|
def __virtual__():
|
|
|
|
return True
|
|
|
|
|
|
|
|
def get_public_ip(url="https://ipinfo.io"):
|
|
|
|
req = Request(url=url,)
|
|
|
|
req.add_header("Accept", "*/*")
|
|
|
|
|
|
|
|
res = urlopen(req)
|
|
|
|
|
|
|
|
ret = json.loads(res.read())
|
|
|
|
if res.status == 200:
|
|
|
|
return "{}/{}".format(ret["ip"],MIN_CIDR)
|
|
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def get_internal_networks(tgt="*", fmt="std"):
|
|
|
|
res = []
|
|
|
|
res.extend([net for k, net in __salt__["mine.get"](tgt=tgt, fun='public_ip', tgt_type='compound').items()])
|
|
|
|
res.extend([net for k, nets in __salt__["mine.get"](tgt=tgt, fun='ip_networks', tgt_type='compound').items() for net in nets if __salt__['network.is_private'](net.split("/")[0])])
|
|
|
|
if fmt == "std":
|
|
|
|
res.extend([net for k, nets in __salt__["mine.get"](tgt=tgt, fun='ip_networks6', tgt_type='compound').items() for net in nets])
|
|
|
|
elif fmt == "postfix":
|
|
|
|
res.extend([POSTFIX_FORMAT(net) for k, nets in __salt__["mine.get"](tgt=tgt, fun='ip_networks6', tgt_type='compound').items() for net in nets])
|
|
|
|
res = list(set(res))
|
|
|
|
res.sort()
|
|
|
|
return res
|
|
|
|
|
|
|
|
def get_nat_networks(tgt="*"):
|
|
|
|
res = []
|
|
|
|
res.extend([net for k, nets in __salt__["mine.get"](tgt=tgt, fun='ip_networks', tgt_type='compound').items() for net in nets if __salt__['network.is_private'](net.split("/")[0])])
|
|
|
|
res = list(set(res))
|
|
|
|
res.sort()
|
|
|
|
return res
|