(20250218) ...

This commit is contained in:
2025-02-18 15:17:23 +05:30
parent 04fad8dc49
commit b7823f4c48
5 changed files with 1888 additions and 100 deletions
File diff suppressed because it is too large Load Diff
View File
+202
View File
@@ -0,0 +1,202 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Create: Saturday, 18th May, 2022
Update: Thursday, 22nd Aug. 2024
OBJECTIVE:
To provide an easy way to work with '.json' data and files.
REFERENCES:
1) https://www.w3schools.com/python/python_json.asp
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# System-level activities:
import io
# To work with the JSON standard:
import json
# To work with files:
from utils_v2.system import files
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
def from_string(json_data):
"""
Decodes a JSON string to a pythonic variable like a dict.
:param json_data: The JSON string to decode.
:return: The decoded pythonic variable.
"""
python_data = json.loads(json_data)
return python_data
# ---------------------------------------------------------------------------------------------------------------------
def to_string(
python_data,
indent = 4,
default = None,
separators = None,
no_space = False
):
"""
Converts the given pythonic data to a JSON string.
:param python_data: The input data like a dict.
:param indent: The tab-width for pretty presentation.
:param default: The function to use on something that cannot be directly parsed into a JSON string.
:param separators: Custom separators to use.
:param no_space: If you want a dense JSON string that saves memory by not using spaces or tabs or line-breaks. Not
good for human readability, very good for saving memory. WARNING: THIS OVERRIDES EVERY OTHER PARAMETER EXCEPT
'default'.
:return: The JSON string representation of the input pythonic data.
"""
if no_space:
json_data = json.dumps(
python_data,
default = default,
separators = (',', ':')
)
else:
json_data = json.dumps(
python_data,
indent = indent,
default = default,
separators = separators
)
return json_data
# ---------------------------------------------------------------------------------------------------------------------
def from_file(file):
"""
Reads a JSON file and returns it as a pythonic variable like a dict.
:param file: The path to the file on the disk or a file held in RAM as a BytesIO object.
:return: The decoded pythonic variable.
"""
if isinstance(file, io.BytesIO):
file.seek(0)
json_data = file.getvalue()
else: json_data = files.read_file(file)
python_data = from_string(json_data)
return python_data
# ---------------------------------------------------------------------------------------------------------------------
def to_file(
file,
python_data,
indent = 4,
default = None,
separators = None,
no_space = False
):
"""
:param file: Either a path to a file on disk, or a buffer in RAM in the form of a BytesIO object.
:param python_data: The pythonic data to be converted to the JSON string.
:param indent: The tab-width for pretty presentation.
:param default: The function to use on something that cannot be directly parsed into a JSON string.
:param separators: Custom separators to use.
:param no_space: If you want a dense JSON string that saves memory by not using spaces or tabs or line-breaks. Not
good for human readability, very good for saving memory. WARNING: THIS OVERRIDES EVERY OTHER PARAMETER EXCEPT
'default'.
:return: True/False if a path was given, else the same BytesIO object with the written JSON data.
"""
json_data = to_string(
python_data,
indent = indent,
default = default,
separators = separators,
no_space = no_space
)
if isinstance(file, io.BytesIO):
file.write(json_data.encode("utf-8"))
file.seek(0)
return file
else:
try:
files.write_file(file, json_data, mode = "w")
return True
except: return False
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
pass
+105
View File
@@ -0,0 +1,105 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Saturday, 15th Feb., 2025.
OBJECTIVE:
???
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# System-level activities:
import io
import os
# For SSH:
from paramiko import SSHClient, AutoAddPolicy
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
ssh_client = SSHClient()
# ssh_client.load_host_keys("~/.ssh/known_hosts")
ssh_client.load_system_host_keys()
ssh_client.set_missing_host_key_policy(AutoAddPolicy())
ssh_client.connect(
hostname = "x.x.x.x",
username = "user",
password = "pass"
)
std_in, std_out, std_err = ssh_client.exec_command("hostname")
print("IN :", std_in.read().decode("utf8"))
print("OUT:", std_out.read().decode("utf8"))
print("ERR:", std_err.read().decode("utf8"))
print("RET. CODE:", std_out.channel.recv_exit_status())
std_in.close()
std_out.close()
std_err.close()
ssh_client.close()
+117 -97
View File
@@ -2314,9 +2314,24 @@ if __name__ == "__main__":
api_response = await my_mikrotik.list_ppp_servers()
print(f"PPP SERVERS ({len(api_response.data)}):", json.to_string(api_response.data))
api_response = await my_mikrotik.list_hotspot_profiles()
print(f"HOTSPOT PROFILES ({len(api_response.data)}):", json.to_string(api_response.data))
api_response = await my_mikrotik.list_hotspot_servers()
print(f"HOTSPOT SERVERS ({len(api_response.data)}):", json.to_string(api_response.data))
api_response = await my_mikrotik.list_hotspot_walled_gardens()
print(f"HOTSPOT WALLED GARDENS ({len(api_response.data)}):", json.to_string(api_response.data))
api_response = await my_mikrotik.list_hotspot_walled_garden_ips()
print(f"HOTSPOT WALLED GARDEN IPS ({len(api_response.data)}):", json.to_string(api_response.data))
api_response = await my_mikrotik.list_radius_servers()
print(f"RADIUS SERVERS ({len(api_response.data)}):", json.to_string(api_response.data))
api_response = await my_mikrotik.list_firewall_nat()
print(f"FIREWALL NAT ({len(api_response.data)}):")
async def hotspot_steps():
HS_VLAN_ID = "2001"
@@ -2324,6 +2339,8 @@ if __name__ == "__main__":
HS_INTERFACE_NAME = "easyfi-hs-if"
HS_VLAN_NAME = "easyfi-hs-vlan-" + HS_VLAN_ID
HS_IP_POOL_NAME = "easyfi-hs-pool-" + HS_VLAN_ID
HS_PROFILE_NAME = "easyfi-hs-prf-" + HS_VLAN_ID
HS_SERVER_NAME = "easyfi-hs-srv-" + HS_VLAN_ID
HS_DHCP_SERVER_NAME = "easyfi-hs-dhcp-" + HS_VLAN_ID
HS_SNMP_COMMUNITY_NAME = "lkjhgfdsa1234567"
@@ -2354,7 +2371,7 @@ if __name__ == "__main__":
# print("MESSAGE:", api_response.message)
# print("JSON:", api_response.data)
# print("\n\n")
#
# # STEP 2:
# # Create the VLAN:
# api_response = await my_mikrotik.add_vlan(
@@ -2370,7 +2387,7 @@ if __name__ == "__main__":
# print("MESSAGE:", api_response.message)
# print("JSON:", api_response.data)
# print("\n\n")
#
# # STEP 3:
# # Bind a new IP address/network to the VLAN:
# api_response = await my_mikrotik.add_ip_address_binding(
@@ -2385,7 +2402,7 @@ if __name__ == "__main__":
# print("MESSAGE:", api_response.message)
# print("JSON:", api_response.data)
# print("\n\n")
#
# # STEP 4:
# # Add a new IP Pool for the Hotspot users:
# api_response = await my_mikrotik.add_ip_pool(
@@ -2399,58 +2416,61 @@ if __name__ == "__main__":
# print("MESSAGE:", api_response.message)
# print("JSON:", api_response.data)
# print("\n\n")
#
# # STEP 5:
# # Add a new Hotspot Profile:
# api_response = await my_mikrotik.add_hotspot_profile(
# json_payload = {
# "dns-name": "hs01.easyfi.net.in",
# "hotspot-address": HS_GATEWAY_PRIVATE_IP,
# "html-directory": "hotspot",
# "html-directory-override": "",
# "http-cookie-lifetime": "3d",
# "http-proxy": "0.0.0.0:0",
# "install-hotspot-queue": "false",
# "login-by": "cookie,http-chap",
# STEP 5:
# Add a new Hotspot Profile:
api_response = await my_mikrotik.add_hotspot_profile(
json_payload = {
"dns-name": "hs01.easyfi.net.in",
"hotspot-address": HS_GATEWAY_PRIVATE_IP,
"html-directory": "hotspot",
"html-directory-override": "",
"http-cookie-lifetime": "3d",
"http-proxy": "0.0.0.0:0",
"install-hotspot-queue": "false",
"login-by": "cookie,http-chap",
# "name": "hs01.easyfi.net.in",
# "split-user-domain": "false",
# "use-radius": "true",
# "nas-port-type": "wireless-802.11",
# "radius-accounting": "true",
# "radius-default-domain": "",
# "radius-interim-update": "received",
# "radius-location-id": "",
# "radius-location-name": "",
# "radius-mac-format": "XX:XX:XX:XX:XX:XX",
# # "comment": HS_COMMENT
# }
# )
# print("STEP 5:", api_response.success, f"({api_response.action})")
# print("MESSAGE:", api_response.message)
# print("JSON:", api_response.data)
# print("\n\n")
#
# # STEP 6:
# # Add a new Hotspot Server:
# api_response = await my_mikrotik.add_hotspot_server(
# json_payload = {
# "address-pool": HS_IP_POOL_NAME,
# "addresses-per-mac": "2",
# "idle-timeout": "5m",
# "interface": HS_VLAN_NAME,
# "keepalive-timeout": "none",
# "login-timeout": "none",
"name": HS_PROFILE_NAME,
"split-user-domain": "false",
"use-radius": "true",
"nas-port-type": "wireless-802.11",
"radius-accounting": "true",
"radius-default-domain": "",
"radius-interim-update": "received",
"radius-location-id": "",
"radius-location-name": "",
"radius-mac-format": "XX:XX:XX:XX:XX:XX",
# "comment": HS_COMMENT
}
)
print("STEP 5:", api_response.success, f"({api_response.action})")
print("MESSAGE:", api_response.message)
print("JSON:", api_response.data)
print("\n\n")
# STEP 6:
# Add a new Hotspot Server:
api_response = await my_mikrotik.add_hotspot_server(
json_payload = {
"address-pool": HS_IP_POOL_NAME,
"addresses-per-mac": "2",
"idle-timeout": "5m",
"interface": HS_VLAN_NAME,
"keepalive-timeout": "none",
"login-timeout": "none",
# "name": "hs01.easyfi.net.in",
"name": HS_SERVER_NAME,
# "profile": "hs01.easyfi.net.in",
# "disabled": "false",
# # "comment": HS_COMMENT
# }
# )
# print("STEP 6:", api_response.success, f"({api_response.action})")
# print("MESSAGE:", api_response.message)
# print("JSON:", api_response.data)
# print("\n\n")
#
"profile": HS_PROFILE_NAME,
"disabled": "false",
# "comment": HS_COMMENT
}
)
print("STEP 6:", api_response.success, f"({api_response.action})")
print("MESSAGE:", api_response.message)
print("JSON:", api_response.data)
print("\n\n")
# # STEP 7:
# # Add a new DHCP Server:
# api_response = await my_mikrotik.add_dhcp_server(
@@ -2469,23 +2489,23 @@ if __name__ == "__main__":
# print("MESSAGE:", api_response.message)
# print("JSON:", api_response.data)
# print("\n\n")
#
# # STEP 8:
# # Add a new DHCP Network:
# api_response = await my_mikrotik.add_dhcp_network(
# json_payload = {
# "address": HS_PRIVATE_IP_SUBNET,
# "gateway": HS_GATEWAY_PRIVATE_IP,
# "netmask": HS_PRIVATE_IP_SUBNET.split("/")[-1],
# "dns-server": HS_GATEWAY_PRIVATE_IP,
# "comment": HS_COMMENT
# }
# )
# print("STEP 8:", api_response.success, f"({api_response.action})")
# print("MESSAGE:", api_response.message)
# print("JSON:", api_response.data)
# print("\n\n")
#
# STEP 8:
# Add a new DHCP Network:
api_response = await my_mikrotik.add_dhcp_network(
json_payload = {
"address": HS_PRIVATE_IP_SUBNET,
"gateway": HS_GATEWAY_PRIVATE_IP,
"netmask": HS_PRIVATE_IP_SUBNET.split("/")[-1],
"dns-server": HS_GATEWAY_PRIVATE_IP,
"comment": HS_COMMENT
}
)
print("STEP 8:", api_response.success, f"({api_response.action})")
print("MESSAGE:", api_response.message)
print("JSON:", api_response.data)
print("\n\n")
# # STEP 9:
# # Set up the Walled-Garden IP:
# api_response = await my_mikrotik.add_hotspot_walled_garden_ip(
@@ -2547,33 +2567,33 @@ if __name__ == "__main__":
# print("MESSAGE:", api_response.message)
# print("JSON:", api_response.data)
# print("\n\n")
#
# STEP 13:
# Map the private IPs to the public IPs for NAT-ing:
private_ips = [
str(ipaddress.IPv4Address(_))
for _ in range(
int(ipaddress.IPv4Address(HS_FIRST_PRIVATE_IP)),
int(ipaddress.IPv4Address(HS_LAST_PRIVATE_IP)) + 1
)
]
public_ips = [
str(ipaddress.IPv4Address(_))
for _ in range(
int(ipaddress.IPv4Address(HS_FIRST_PUBLIC_IP)),
int(ipaddress.IPv4Address(HS_LAST_PUBLIC_IP)) + 1
)
]
nat_map = my_mikrotik.split_ipv4_range_in_powers_of_two(
start_ip = HS_FIRST_PRIVATE_IP,
end_ip = HS_LAST_PRIVATE_IP,
targets = public_ips,
consider_reserved_ips = False
)
print("NAT MAP:", json.to_string(nat_map, default=str))
print("PRIVATE IP COUNT:", len(private_ips))
print("PUBLIC IP COUNT:", len(public_ips))
print("RULE COUNT:", len(nat_map))
# # STEP 13:
# # Map the private IPs to the public IPs for NAT-ing:
# private_ips = [
# str(ipaddress.IPv4Address(_))
# for _ in range(
# int(ipaddress.IPv4Address(HS_FIRST_PRIVATE_IP)),
# int(ipaddress.IPv4Address(HS_LAST_PRIVATE_IP)) + 1
# )
# ]
# public_ips = [
# str(ipaddress.IPv4Address(_))
# for _ in range(
# int(ipaddress.IPv4Address(HS_FIRST_PUBLIC_IP)),
# int(ipaddress.IPv4Address(HS_LAST_PUBLIC_IP)) + 1
# )
# ]
# nat_map = my_mikrotik.split_ipv4_range_in_powers_of_two(
# start_ip = HS_FIRST_PRIVATE_IP,
# end_ip = HS_LAST_PRIVATE_IP,
# targets = public_ips,
# consider_reserved_ips = False
# )
# print("NAT MAP:", json.to_string(nat_map, default=str))
# print("PRIVATE IP COUNT:", len(private_ips))
# print("PUBLIC IP COUNT:", len(public_ips))
# print("RULE COUNT:", len(nat_map))
# for index, nat_rule in enumerate(nat_map):
# api_response = await my_mikrotik.add_firewall_nat(
# json_payload = {
@@ -2613,4 +2633,4 @@ if __name__ == "__main__":
# print("\n\n")
asyncio.run(hotspot_steps())
asyncio.run(main())