paulbsd-salt/states/_modules/net.py

53 lines
1.8 KiB
Python
Raw Permalink Normal View History

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
2024-07-23 22:53:18 +02:00
## services
# https://api.ipapi.is/
# https://4.ident.me/json
# https://ip.paulbsd.com/json
def get_public_ip(url="https://4.ident.me/json"):
2024-05-21 16:00:09 +02:00
req = Request(url=url)
2023-03-10 00:09:04 +01:00
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()])
2024-07-23 11:58:28 +02:00
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]) or net.split("/")[0].startswith("100.64.0")])
2023-03-10 00:09:04 +01:00
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