iptables-deploy/deploy.py

82 lines
2.8 KiB
Python

import paramiko # this sounds like an anime
import json
import os
import time # i need time to get this done
import requests # for getting the commands to run on client
# import modules
with open("conf.json", "r") as file:
cfg = json.load(file)
# open the config file and make it accessible via "cfg"
sshc = paramiko.client.SSHClient()
healthstatus = "" # possible values: "ok", "err"
healthpassing = True
shcommands = []
# set our variables
def healthcheck():
global healthstatus
response = ""
if cfg["os"] == "win":
response = os.system("ping -n 2 " + cfg["server"])
else:
response = os.system("ping -c 2 " + cfg["server"] + ">> /dev/null")
if response != 0:
healthstatus = "err"
else:
healthstatus = "ok"
def downloadLatestCommands():
r = requests.get(cfg['srcurl'])
open(cfg["filepath"], 'wb').write(r.content)
def commandList():
global shcommands
cmdtxt = open(cfg["filepath"], "r")
cmddata = cmdtxt.read()
shcommands = cmddata.split("\n")
cmdtxt.close()
def deploy():
downloadLatestCommands()
sshc.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # so we don't get whined at and crash over a unrecognized host-key
sshc.connect(cfg["server"],port=cfg["port"],username=cfg["ssh-user"],password=cfg["ssh-pw"])
time.sleep(3) # Sleep 3 seconds, so that the ONT is initialized enough
for command in shcommands:
sshc.exec_command(command)
print(f'{command} was executed on the ONT')
print("All commands were executed, now disconnecting...")
sshc.close # close the connection.
# sshc.exec_command("chmod +x $HOME/payload.sh") # make it executable
# sshc.exec_command("./payload.sh") # and finally, run the payload.
while True:
downloadLatestCommands() # Do this at first run
commandList() # Break all the commands into a list
healthcheck() # Run the health check for the first time
if healthstatus != "ok":
print("ONT is not responding!! Did we lose network connection, or is the ONT rebooting? waiting for ONT to respond, then deploying payload!")
healthpassing = False
while healthpassing == False:
print("Checking for a response...")
healthcheck()
if healthstatus == "ok":
print("ONT responded after a fail, deploying payload!")
healthpassing == True
time.sleep(10) # Wait 10 seconds for the ONT to fully boot up and start sshd.
deploy()
break
else:
print("Got a response! health status is ok.")
print("Trying again in " + cfg["chkinterval"] + " seconds.")
time.sleep(int(cfg["chkinterval"])) # we will run this loop every X seconds, defined by checkinterval