AniNIX/Wiki#21 -- effecting renames for policy

This commit is contained in:
2024-04-01 00:44:23 -05:00
parent 323b4dd306
commit 6f36d515e3
46 changed files with 509 additions and 368 deletions

View File

@@ -11,6 +11,7 @@
import os
import subprocess
import sys
import re
import yaml
rolepath='../roles/Sharingan/files'

View File

@@ -1,51 +1,46 @@
#!/usr/bin/env python3
# File: generate-pihole-dns-dhcp.py
#
#
# Description: This file generates the DNS and DHCP files for pihole.
#
# It expects that the inventory has two levels of grouping.
#
# Package: AniNIX/Ubiqtorate
# Copyright: WTFPL
#
#
# Author: DarkFeather <darkfeather@aninix.net>
import os
import re
import subprocess
import sys
import yaml
from kapisi_lib import *
rolepath='../roles/Nazara/files'
rolepath='../roles/Chappaai/files'
dnsfilepath=rolepath+"/dns"
dhcpfilepath=rolepath+"/dhcp"
entryset={}
def WriteDHCPEntry(content,hosttype,hostclass):
def WriteDHCPEntries(replica_domain,dhcpfile):
### Create the DHCP entry
# param content: the yaml content to parse
# param hosttype: managed or unmanaged
# param hostclass: the type of host as classified in the yaml
global dhcpfile
global entryset
for host in entryset:
# Entries should be:
# dhcp-host=mac,ip,fqdn
dhcpfile.write('dhcp-host=' + entryset[host][1] + ',' + entryset[host][0] + ',' + host + '.' + replica_domain + '\n')
with open(dhcpfilepath,'a') as dhcpfile:
for host in content['all']['children'][hosttype]['children'][hostclass]['hosts']:
try:
dhcpfile.write('dhcp-host=' + content['all']['children'][hosttype]['children'][hostclass]['hosts'][host]['mac'] + ',' + content['all']['children'][hosttype]['children'][hostclass]['hosts'][host]['ip'] + ',' + host + '.' + content['all']['vars']['replica_domain'] + '\n')
except:
print(host + ' is not complete for DHCP.')
def WriteDNSEntry(content,hosttype,hostclass):
def WriteDNSEntries(replica_domain,dnsfile):
### Create the DNS entry
# param content: the yaml content to parse
# param hosttype: managed or unmanaged
# param hostclass: the type of host as classified in the yaml
global dnsfile
with open(dnsfilepath,'a') as dnsfile:
# Write host entries
for host in content['all']['children'][hosttype]['children'][hostclass]['hosts']:
try:
dnsfile.write(content['all']['children'][hosttype]['children'][hostclass]['hosts'][host]['ip'] + ' ' + host + '.' + content['all']['vars']['replica_domain'] + ' ' + host + '\n')
except:
print(host + ' is not complete for DNS.')
global entryset
for host in entryset:
# Entries should be:
# ip host fqdn
dnsfile.write(entryset[host][0] + ' ' + host + '.' + replica_domain + ' ' + host + '\n')
def GenerateFiles(file):
### Open the file and parse it
@@ -58,29 +53,30 @@ def GenerateFiles(file):
# Parse the yaml
with open(file, 'r') as stream:
content = yaml.safe_load(stream)
replica_domain = content['all']['vars']['replica_domain']
external_domain = content['all']['vars']['external_domain']
# Clear the DNS file
with open(dhcpfilepath,'w') as dhcpfile:
dhcpfile.write('dhcp-range='+content['all']['vars']['dhcprange']+'\n')
dhcpfile.write('dhcp-option=option:dns-server,'+content['all']['vars']['dns']+'\n\n')
dhcpfile.write('dhcp-range='+content['all']['vars']['staticrange']+'\n')
WriteDHCPEntries(replica_domain,dhcpfile)
with open(dnsfilepath,'w') as dnsfile:
vips=subprocess.run(["/bin/bash", "-c", "echo | openssl s_client -connect "+content['all']['vars']['external_domain']+":443 | openssl x509 -text -noout | grep DNS: | tr ',' '\n' | sed 's/\s\+DNS://' | grep -ivE ^"+content['all']['vars']['external_domain']+" | tr '\n' ' '"], capture_output=True).stdout.decode("utf-8")
dnsfile.write(content['all']['vars']['webfront']+' '+content['all']['vars']['external_domain']+' '+vips+"\n")
# Add DNS entries for each host
hosttype = 'managed'
for hostclass in ['physical','virtual','geth_hubs']:
WriteDNSEntry(content,hosttype,hostclass)
WriteDHCPEntry(content,hosttype,hostclass)
hosttype = 'unmanaged'
for hostclass in ['ovas','test_ovas','appliances','adhoc_appliances','iot']:
WriteDNSEntry(content,hosttype,hostclass)
WriteDHCPEntry(content,hosttype,hostclass)
dnsfile.write(content['all']['vars']['webfront']+' '+external_domain+' '+content['all']['vars']['external_subdomains'].replace(' ','.'+external_domain+' ')+'.'+external_domain+' '+content['all']['vars']['hosted_domains']+"\n")
WriteDNSEntries(replica_domain,dnsfile)
print('Files should be in '+rolepath);
### Main function
# param sys.argv: Input arguments
if __name__ == '__main__':
if len(sys.argv) != 2:
if len(sys.argv) < 2:
print("You need to supply an inventory file.")
sys.exit(1)
if len(sys.argv) == 3:
entryset = TrackIPEntries(sys.argv[1],sys.argv[2])
else:
entryset = TrackIPEntries(sys.argv[1])
GenerateFiles(sys.argv[1])
#dumper.dump(entryset)
sys.exit(0)

View File

@@ -1,6 +1,6 @@
#!/bin/bash
# File: gen-ssh-keyscan
# File: ./generate-ssh-keyscan
#
# Description: This file generates a known_host block for the inventory.
#

63
bin/kapisi_lib.py Normal file
View File

@@ -0,0 +1,63 @@
import re
import yaml
from types import SimpleNamespace
from yamlpath.common import Parsers
from yamlpath.wrappers import ConsolePrinter
from yamlpath import Processor
from yamlpath import YAMLPath
from yamlpath.exceptions import YAMLPathException
def TrackIPEntries(yaml_file,searchstring='all.children.**.ip'):
### Try to parse an Ansible inventory for hosts with the 'ip' attribute.
# param file: the file to parse
# return: a populated entry set in form [{Host,[ip,mac]},...]
# Borrowing from upstream author's example at https://pypi.org/project/yamlpath/
entryset = {}
# The various classes of this library must be able to write messages somewhere
# when things go bad.
#logging_args = SimpleNamespace(quiet=True, verbose=False, debug=False)
logging_args = SimpleNamespace(quiet=True, verbose=True, debug=True)
log = ConsolePrinter(logging_args)
# Prep the YAML parser
yaml = Parsers.get_yaml_editor()
(yaml_data, doc_loaded) = Parsers.get_yaml_data(yaml, log, yaml_file)
if not doc_loaded:
exit(1)
processor = Processor(log, yaml_data)
yaml_path = YAMLPath(searchstring)
# Create a regex pattern to remove the end of the path
ippattern = re.compile('\.ip$')
try:
for node_coordinate in processor.get_nodes(yaml_path, mustexist=True):
# Strip the path to the host entry.
path = ippattern.sub("",str(node_coordinate.path))
# Pull the IP
ip = str(node_coordinate.node)
# Pull the hosname
splitpath = path.split('.')
hostname = splitpath[len(splitpath)-1]
#print("Got {} from '{}''.".format(ip,path))
# Path the MAC
mac_yaml_path = YAMLPath(path+".mac")
mac=""
try:
for node_coordinate in processor.get_nodes(mac_yaml_path, mustexist=True):
mac = str(node_coordinate.node)
except YAMLPathException as ex:
log.error(ex)
# Add the host to the entryset.
entryset.update({ hostname : [ip,mac] })
except YAMLPathException as ex:
log.error(ex)
finally:
return entryset

View File

@@ -17,11 +17,11 @@ group=all
offset=0
unset inventory
function usage() {
function usage() {
# Show helptext
# param retcode: what to exit
retcode="$1"
echo "Usage: $0 [ -o offset ] [-g group ] -i inventory.yml"
echo "Usage: $0 [ -o offset ] [-g group ] [-i inventory.yml]"
echo " $0 -h"
echo "Group is optional -- add it if you only want to look at a specific subset."
echo "Add -v for verbosity."
@@ -41,7 +41,7 @@ function tmuxHosts() {
name="$group-$offset"
# If no TMUX session started, then add one with four panes.
if [ -z "$TMUX" ]; then
if [ -z "$TMUX" ]; then
tmux new-session -s "$name" -d "/bin/bash -l -c ssh\\ $host1"
tmux select-window -t "$name":0
tmux split-window "/bin/bash -l -c ssh\\ $host2"
@@ -51,7 +51,7 @@ function tmuxHosts() {
tmux setw synchronize-panes
tmux a -d -t "$name"
# Otherwise, add a new window to the current session with all four sessions.
else
else
tmux new-window -n "$name" "/bin/bash -l -c ssh\\ $host1"
tmux select-window -t "$name"
tmux split-window "/bin/bash -l -c ssh\\ $host2"
@@ -76,12 +76,11 @@ if [ "$(basename $0)" == "tmux-hosts" ]; then
*) usage 1 ;;
esac
done
if [ -z "$inventory" ]; then
echo Need an inventory.
usage 2;
inventory=$(grep -E ^inventory ~/.ansible.cfg | cut -f 2 -d '=')
fi
tmuxHosts $(ansible -i "$inventory" --list-hosts "$group"\
| grep -v hosts\ \( \
| sed 's/\s\+//g' \