#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#
# generated by wxGlade 1.0.5+repack on Tue Jul  4 15:11:36 2023
#

import wx

# begin wxGlade: dependencies
import wx.grid
# end wxGlade

# begin wxGlade: extracode
import json, os, platform, stat, sqlite3, wx

def paramiko_pmopen(dhost,dport,duser,dpwd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
      ssh.connect(hostname=dhost,port=dport,username=duser,password=dpwd,allow_agent=True,timeout=10)
      return ssh
    except:
      print('Failed to connect')
def paramiko_pxopen(phost,puser,dhost,dport,duser,dpwd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
      psock=paramiko.ProxyCommand('ssh -o VisualHostKey=no -W'+dhost+':'+str(dport)+' '+puser+'@'+phost)
      ssh.connect(hostname=dhost,port=dport,username=duser,password=dpwd,allow_agent=True,timeout=10,sock=psock)
      return ssh
    except:
      print('Failed to connect to '+dhost+':'+str(dport))
def paramiko_pcmd(sshc,cmd,show):
    try:
      stdin,stdout,stderr = sshc.exec_command(cmd)
      response=stdout.read().decode()
      if show:
         print(response)
    except:
      print('Command '+cmd+' failed')

shelly=[""]*50
if platform.system()=="Windows":
  dbdir=".\\kali-autopilot\\"
else:
  dbdir=os.path.expanduser("~")+"/kali-autopilot/"
db=dbdir+"kali-autopilot.db"

def create_mutexfile(mutexfile):
    f=open(mutexfile,"w")
    f.write("0")
    f.close()

def create_api_file(chalname, apifile):
## Create Mutex API script
    f=open(apifile,"w")
    f.write("#!/usr/bin/env python3\n")
    f.write("# Kali Autopilot Generated\n")
    f.write("# -------------------------\n")
    f.write("\n")
    f.write("import cherrypy, random, re, string, os\n")
    f.write("fmutex='./mutex.txt'\n")
    f.write("ip='0.0.0.0'\n")
    f.write("port=80\n")
    f.write("users = {'offsec': 'offsec'}\n")
    f.write("attack_script= './" + chalname + ".py'\n")
    f.write("attack_service = 'kali-autopilot_attack_" + chalname + "'\n")
    f.write("# Let's generate a new key on every start.\n")
    f.write("# This will invalidate old authentications\n")
    f.write("# and users must re-authenticate.\n")
    f.write("characters = string.ascii_letters + string.digits + string.punctuation\n")
    f.write("session_key = ''.join(random.choice(characters) for i in range(16))\n")
    f.write("\n")
    f.write("def get_max_stage():\n")
    f.write("    stages = []\n")
    f.write("    with open (attack_script, 'rt') as script:\n")
    f.write("        for line in script:\n")
    f.write("            pattern = re.search(r'(?<=if index==)[\d]+', line)\n")
    f.write("            if pattern:\n")
    f.write("                stages.append(int(pattern.group()))\n")
    f.write("        stages.sort()\n")
    f.write("    return stages[-1]\n")
    f.write("\n")
    f.write("conf = {\n")
    f.write("   '/': {\n")
    f.write("        'tools.auth_digest.on': True,\n")
    f.write("        'tools.auth_digest.realm': 'localhost',\n")
    f.write("        'tools.auth_digest.get_ha1': cherrypy.lib.auth_digest.get_ha1_dict_plain(users),\n")
    f.write("        'tools.auth_digest.key': session_key,\n")
    f.write("        'tools.auth_digest.accept_charset': 'UTF-8',\n")
    f.write("   }\n")
    f.write("}\n")
    f.write("\n")
    f.write("class SetMutex:\n")
    f.write("   @cherrypy.expose\n")
    f.write("   def index(self):\n")
    f.write("     return \"<h2>Kali Autopilot mutex interface</h2><br><br><h3>Example usage:</h3>http://127.0.0.1/check<br>http://127.0.0.1/set?mutex=1\"\n")
    f.write("   @cherrypy.expose\n")
    f.write("   def check(self):\n")
    f.write("     with open(fmutex,'r') as f:\n")
    f.write("        mutex=f.read()\n")
    f.write("        f.close()\n")
    f.write("     return \"Attack is at Stage \"+ mutex +\" of \" + str(get_max_stage())\n")
    f.write("\n")
    f.write("   @cherrypy.expose\n")
    f.write("   def set(self,mutex=''):\n")
    f.write("     with open(fmutex,'w') as f:\n")
    f.write("        if mutex.isdigit():\n")
    f.write("            f.write(mutex)\n")
    f.write("            f.close()\n")
    f.write("        else:\n")
    f.write("            return \"mutex<b><i> \"+mutex+\"</i></b> is invalid<br>mutex must be an integer, e.g. <i>/set?mutex=1</i>\"\n")
    f.write("\n")
    f.write("     if mutex=='0':\n")
    f.write("       status = os.system('systemctl is-active --quiet ' + attack_service)\n")
    f.write("       if status == 0:\n")
    f.write("         os.system('systemctl restart ' + attack_service)\n")
    f.write("       return 'Attack reset'\n")
    f.write("     else:\n")
    f.write("       return 'Attack Stage '+mutex+' initiated'\n")
    f.write("\n")
    f.write("cherrypy.config.update({'server.socket_host':ip,'server.socket_port':port})\n")
    f.write("cherrypy.quickstart(SetMutex(), '/', conf)\n")
    f.close()

def create_service_script(chalname, chaldir, chalfile, servicescript):
## Create service script script
    f=open(servicescript,"w")
    f.write("#!/bin/bash\n")
    f.write("CHALNAME=\"" + chalname + "\"\n")
    f.write("CHALDIR=\"" + chaldir + "\"\n")
    f.write("ABASENAME=\"kali-autopilot_attack_\"\n")
    f.write("WBASENAME=\"kali-autopilot_webapi_\"\n")
    f.write("MUTEXAPI=\"mutex-api.py\"\n")
    f.write("ASERVICE=$ABASENAME$CHALNAME\n")
    f.write("WSERVICE=$WBASENAME$CHALNAME\n")
    f.write("AEXECSTART=\"" + chalfile + "\"\n")
    f.write("WEXECSTART=$CHALDIR$MUTEXAPI\n")
    f.write("function check_root(){\n")
    f.write("    if [[ $EUID -ne 0 ]]; then\n")
    f.write("        printf \"\\n$(basename $0) must be run as root.\\ntry: sudo ./$(basename $0)\\n\\n\"\n")
    f.write("        exit 1\n")
    f.write("    fi\n")
    f.write("}\n")
    f.write("function print_usage() {\n")
    f.write("    cat << EOF\n")
    f.write("\n")
    f.write("usage: sudo ./services.sh <option>\n")
    f.write(" This will set up Kali-Autopilot services\n")
    f.write(" OPTIONS:\n")
    f.write("    -h        Show this message\n")
    f.write("    -a        Install and start all services\n")
    f.write("    -s        Install and start attack service\n")
    f.write("    -w        Install and start web API service\n")
    f.write("    -i        Show service info\n")
    f.write("    -r        Stop and remove all services\n")
    f.write("EOF\n")
    f.write("}\n")
    f.write("function show_info() {\n")
    f.write("    systemctl status $ASERVICE\n")
    f.write("    systemctl status $WSERVICE\n")
    f.write("}\n")
    f.write("function remove_services() {\n")
    f.write("    systemctl disable $ASERVICE --now >/dev/null 2>&1\n")
    f.write("    rm -f /etc/systemd/system/$ASERVICE.service >/dev/null 2>&1\n")
    f.write("    systemctl disable $WSERVICE --now >/dev/null 2>&1\n")
    f.write("    rm -r /etc/systemd/system/$WSERVICE.service >/dev/null 2>&1\n")
    f.write("        printf \"\\nServices removed\\n\\n\"\n")
    f.write("}\n")
    f.write("function install_attack_service {\n")
    f.write("    cat << EOF >> /etc/systemd/system/$ASERVICE.service\n")
    f.write("[Unit]\n")
    f.write("Description=This service executes Kali-Autopilot attack scripts\n")
    f.write("ConditionPathExists=$AEXECSTART\n")
    f.write("\n")
    f.write("\n")
    f.write("[Service]\n")
    f.write("ExecStart=/usr/bin/env python3 $AEXECSTART\n")
    f.write("WorkingDirectory=$CHALDIR\n")
    f.write("Restart=always\n")
    f.write("RestartSec=30\n")
    f.write("\n")
    f.write("\n")
    f.write("[Install]\n")
    f.write("WantedBy=multi-user.target\n")
    f.write("EOF\n")
    f.write("\n")
    f.write("systemctl enable $ASERVICE --now\n")
    f.write("printf \"\\nService $ASERVICE installed\\n\\n\"\n")
    f.write("}\n")
    f.write("function install_web_api_service {\n")
    f.write("    cat << EOF >> /etc/systemd/system/$WSERVICE.service\n")
    f.write("[Unit]\n")
    f.write("Description=Mutex API provides a webAPI to set the mutex for Kali-Autopilot attack scripts\n")
    f.write("ConditionPathExists=$WEXECSTART\n")
    f.write("\n")
    f.write("\n")
    f.write("[Service]\n")
    f.write("ExecStart=/usr/bin/env python3 $WEXECSTART\n")
    f.write("WorkingDirectory=$CHALDIR\n")
    f.write("Restart=always\n")
    f.write("RestartSec=30\n")
    f.write("\n")
    f.write("\n")
    f.write("[Install]\n")
    f.write("WantedBy=multi-user.target\n")
    f.write("EOF\n")
    f.write("\n")
    f.write("systemctl enable $WSERVICE --now\n")
    f.write("printf \"\\nService $WSERVICE installed\\n\\n\"\n")
    f.write("}\n")
    f.write("check_root\n")
    f.write("\n")
    f.write("while getopts \"ahirsw\" opt; do\n")
    f.write("  case \"$opt\" in\n")
    f.write("  h)  print_usage\n")
    f.write("      exit 0\n")
    f.write("      ;;\n")
    f.write("  a)  install_attack_service\n")
    f.write("      install_web_api_service\n")
    f.write("     exit 0\n")
    f.write("      ;;\n")
    f.write("  s)  install_attack_service\n")
    f.write("      exit 0\n")
    f.write("      ;;\n")
    f.write("  w)  install_web_api_service\n")
    f.write("      exit 0\n")
    f.write("      ;;\n")
    f.write("  i)  show_info\n")
    f.write("      exit 0\n")
    f.write("      ;;\n")
    f.write("  r)  remove_services\n")
    f.write("      exit 0\n")
    f.write("      ;;\n")
    f.write("  \?) print_usage\n")
    f.write("      exit 1\n")
    f.write("      ;;\n")
    f.write("  esac\n")
    f.write("done\n")
    f.write("\n")
    f.write("print_usage\n")
    f.close()
    st = os.stat(servicescript)
    os.chmod(servicescript, st.st_mode | stat.S_IEXEC | stat.S_IXGRP)
# end wxGlade


class Autopilot(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: Autopilot.__init__
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((905, 697))
        self.SetTitle("Kali Autopilot - Automated Attack Generator")

        sizer_frame = wx.BoxSizer(wx.VERTICAL)

        sizer_frame_top = wx.BoxSizer(wx.HORIZONTAL)
        sizer_frame.Add(sizer_frame_top, 1, wx.EXPAND, 0)

        self.pannel_scripts = wx.Panel(self, wx.ID_ANY, style=wx.BORDER_SIMPLE)
        self.pannel_scripts.SetMinSize((300, 283))
        sizer_frame_top.Add(self.pannel_scripts, 1, wx.ALL | wx.EXPAND, 9)

        sizer_scripts = wx.BoxSizer(wx.VERTICAL)

        label_scripts = wx.StaticText(self.pannel_scripts, wx.ID_ANY, "Attack Scripts")
        label_scripts.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
        sizer_scripts.Add(label_scripts, 0, wx.ALL, 3)

        self.lb_scripts = wx.ListBox(self.pannel_scripts, wx.ID_ANY, choices=[])
        self.lb_scripts.SetMinSize((299, 100))
        sizer_scripts.Add(self.lb_scripts, 1, wx.LEFT | wx.RIGHT, 3)

        sizer_scripts_text = wx.BoxSizer(wx.HORIZONTAL)
        sizer_scripts.Add(sizer_scripts_text, 0, wx.BOTTOM | wx.EXPAND | wx.TOP, 3)

        label_script = wx.StaticText(self.pannel_scripts, wx.ID_ANY, "Script")
        sizer_scripts_text.Add(label_script, 0, wx.LEFT, 5)

        self.text_script = wx.TextCtrl(self.pannel_scripts, wx.ID_ANY, "")
        self.text_script.SetMinSize((244, 20))
        sizer_scripts_text.Add(self.text_script, 0, wx.LEFT | wx.RIGHT, 4)

        sizer_scripts_buttons = wx.BoxSizer(wx.HORIZONTAL)
        sizer_scripts.Add(sizer_scripts_buttons, 0, wx.EXPAND, 0)

        self.button_script_add = wx.Button(self.pannel_scripts, wx.ID_ANY, "Add")
        self.button_script_add.SetMinSize((40, 20))
        self.button_script_add.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_scripts_buttons.Add(self.button_script_add, 0, wx.ALL, 3)

        self.button_script_copy = wx.Button(self.pannel_scripts, wx.ID_ANY, "Copy")
        self.button_script_copy.SetMinSize((40, 20))
        self.button_script_copy.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_scripts_buttons.Add(self.button_script_copy, 0, wx.ALL, 3)

        self.button_script_delete = wx.Button(self.pannel_scripts, wx.ID_ANY, "Delete")
        self.button_script_delete.SetMinSize((45, 20))
        self.button_script_delete.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_scripts_buttons.Add(self.button_script_delete, 0, wx.ALL, 3)

        self.button_script_import = wx.Button(self.pannel_scripts, wx.ID_ANY, "Import")
        self.button_script_import.SetMinSize((50, 20))
        self.button_script_import.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_scripts_buttons.Add(self.button_script_import, 0, wx.ALL, 3)

        self.button_script_export = wx.Button(self.pannel_scripts, wx.ID_ANY, "Export")
        self.button_script_export.SetMinSize((42, 20))
        self.button_script_export.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_scripts_buttons.Add(self.button_script_export, 0, wx.ALL, 3)

        self.button_save = wx.Button(self.pannel_scripts, wx.ID_ANY, "Save")
        self.button_save.SetMinSize((48, 20))
        self.button_save.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_scripts_buttons.Add(self.button_save, 0, wx.LEFT | wx.RIGHT | wx.TOP, 3)

        self.panel_ip = wx.Panel(self, wx.ID_ANY, style=wx.BORDER_SIMPLE)
        self.panel_ip.SetMinSize((300, 283))
        sizer_frame_top.Add(self.panel_ip, 2, wx.ALL | wx.EXPAND, 9)

        sizer_ip = wx.BoxSizer(wx.VERTICAL)

        sizer_ip_title = wx.BoxSizer(wx.HORIZONTAL)
        sizer_ip.Add(sizer_ip_title, 0, wx.ALL | wx.EXPAND, 0)

        label_ip_title = wx.StaticText(self.panel_ip, wx.ID_ANY, "Variables for:")
        label_ip_title.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
        sizer_ip_title.Add(label_ip_title, 0, wx.ALL, 3)

        self.label_ip_title_script_name = wx.StaticText(self.panel_ip, wx.ID_ANY, "Script Name")
        self.label_ip_title_script_name.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_ITALIC, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_ip_title.Add(self.label_ip_title_script_name, 0, wx.ALL, 3)

        self.grid_ip_list = wx.grid.Grid(self.panel_ip, wx.ID_ANY, size=(1, 1))
        self.grid_ip_list.CreateGrid(20, 2)
        self.grid_ip_list.SetRowLabelSize(30)
        self.grid_ip_list.SetColLabelSize(30)
        self.grid_ip_list.SetColLabelValue(0, "Name")
        self.grid_ip_list.SetColSize(0, 150)
        self.grid_ip_list.SetColLabelValue(1, "Value")
        self.grid_ip_list.SetColSize(1, 150)
        self.grid_ip_list.SetMinSize((280, 100))
        sizer_ip.Add(self.grid_ip_list, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 3)

        sizer_ip_buttons = wx.BoxSizer(wx.HORIZONTAL)
        sizer_ip.Add(sizer_ip_buttons, 0, wx.EXPAND, 0)

        self.button_ip_clear = wx.Button(self.panel_ip, wx.ID_ANY, "Clear")
        self.button_ip_clear.SetMinSize((40, 20))
        self.button_ip_clear.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_ip_buttons.Add(self.button_ip_clear, 0, wx.ALL, 3)

        self.button_ip_insert = wx.Button(self.panel_ip, wx.ID_ANY, "Insert")
        self.button_ip_insert.SetMinSize((40, 20))
        self.button_ip_insert.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_ip_buttons.Add(self.button_ip_insert, 0, wx.ALL, 3)

        self.button_ip_remove = wx.Button(self.panel_ip, wx.ID_ANY, "Remove")
        self.button_ip_remove.SetMinSize((50, 20))
        self.button_ip_remove.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_ip_buttons.Add(self.button_ip_remove, 0, wx.ALL, 3)

        self.panel_settings = wx.Panel(self, wx.ID_ANY, style=wx.BORDER_SIMPLE)
        self.panel_settings.SetMinSize((195, 283))
        sizer_frame_top.Add(self.panel_settings, 1, wx.ALL | wx.EXPAND, 9)

        sizer_settings = wx.WrapSizer(wx.VERTICAL)

        label_settings = wx.StaticText(self.panel_settings, wx.ID_ANY, "Settings")
        label_settings.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
        sizer_settings.Add(label_settings, 0, wx.ALL, 3)

        sizer_settings.Add((20, 20), 0, wx.EXPAND, 0)

        sizer_time = wx.BoxSizer(wx.HORIZONTAL)
        sizer_settings.Add(sizer_time, 0, wx.EXPAND, 0)

        label_time = wx.StaticText(self.panel_settings, wx.ID_ANY, "Delay:")
        label_time.SetMinSize((70, 20))
        sizer_time.Add(label_time, 0, wx.LEFT, 3)

        self.text_time_min = wx.TextCtrl(self.panel_settings, wx.ID_ANY, "5")
        self.text_time_min.SetMinSize((40, 20))
        sizer_time.Add(self.text_time_min, 0, wx.EXPAND, 0)

        label_time_dash = wx.StaticText(self.panel_settings, wx.ID_ANY, "--")
        sizer_time.Add(label_time_dash, 0, 0, 0)

        self.text_time_max = wx.TextCtrl(self.panel_settings, wx.ID_ANY, "20")
        self.text_time_max.SetMinSize((40, 20))
        sizer_time.Add(self.text_time_max, 0, wx.RIGHT, 3)

        sizer_interface = wx.BoxSizer(wx.HORIZONTAL)
        sizer_settings.Add(sizer_interface, 0, wx.EXPAND, 0)

        label_interface = wx.StaticText(self.panel_settings, wx.ID_ANY, "Interface:")
        label_interface.SetMinSize((70, 20))
        sizer_interface.Add(label_interface, 0, wx.LEFT, 3)

        self.text_interface = wx.TextCtrl(self.panel_settings, wx.ID_ANY, "eth0")
        self.text_interface.SetMinSize((92, 20))
        sizer_interface.Add(self.text_interface, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 3)

        sizer_settings.Add((20, 20), 0, wx.EXPAND, 0)

        sizer_delay_all = wx.BoxSizer(wx.HORIZONTAL)
        sizer_settings.Add(sizer_delay_all, 0, wx.EXPAND, 0)

        self.checkbox_delay_all = wx.CheckBox(self.panel_settings, wx.ID_ANY, "Always insert delay")
        sizer_delay_all.Add(self.checkbox_delay_all, 0, 0, 0)

        sizer_debug = wx.BoxSizer(wx.HORIZONTAL)
        sizer_settings.Add(sizer_debug, 0, wx.EXPAND, 0)

        self.checkbox_debug = wx.CheckBox(self.panel_settings, wx.ID_ANY, "Debug")
        sizer_debug.Add(self.checkbox_debug, 0, 0, 0)

        sizer_set_ip = wx.BoxSizer(wx.HORIZONTAL)
        sizer_settings.Add(sizer_set_ip, 0, wx.EXPAND, 0)

        self.checkbox_ips = wx.CheckBox(self.panel_settings, wx.ID_ANY, "Set IP Addresses")
        sizer_set_ip.Add(self.checkbox_ips, 0, 0, 0)

        sizer_loop = wx.BoxSizer(wx.HORIZONTAL)
        sizer_settings.Add(sizer_loop, 0, wx.EXPAND, 0)

        self.checkbox_loop = wx.CheckBox(self.panel_settings, wx.ID_ANY, "Loop")
        sizer_loop.Add(self.checkbox_loop, 0, 0, 0)

        self.panel_frame_bottom = wx.Panel(self, wx.ID_ANY, style=wx.BORDER_SIMPLE)
        sizer_frame.Add(self.panel_frame_bottom, 2, wx.ALL | wx.EXPAND, 9)

        sizer_sequence = wx.BoxSizer(wx.VERTICAL)

        label_sequence = wx.StaticText(self.panel_frame_bottom, wx.ID_ANY, "Scripted Attack Sequence")
        label_sequence.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
        sizer_sequence.Add(label_sequence, 0, wx.ALL, 3)

        self.grid_sequence = wx.grid.Grid(self.panel_frame_bottom, wx.ID_ANY, size=(1, 1))
        self.grid_sequence.CreateGrid(120, 4)
        self.grid_sequence.SetRowLabelSize(30)
        self.grid_sequence.SetColLabelSize(30)
        self.grid_sequence.SetColLabelValue(0, "Action")
        self.grid_sequence.SetColSize(0, 64)
        self.grid_sequence.SetColLabelValue(1, "Refer")
        self.grid_sequence.SetColSize(1, 68)
        self.grid_sequence.SetColLabelValue(2, "Prompt")
        self.grid_sequence.SetColSize(2, 160)
        self.grid_sequence.SetColLabelValue(3, "Command")
        self.grid_sequence.SetColSize(3, 550)
        self.grid_sequence.SetMinSize((900, 200))
        sizer_sequence.Add(self.grid_sequence, 1, wx.EXPAND, 0)

        sizer_sequence_buttons = wx.BoxSizer(wx.HORIZONTAL)
        sizer_sequence.Add(sizer_sequence_buttons, 0, wx.EXPAND, 0)

        self.button_sequence_clear = wx.Button(self.panel_frame_bottom, wx.ID_ANY, "Clear")
        self.button_sequence_clear.SetMinSize((40, 20))
        self.button_sequence_clear.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_sequence_buttons.Add(self.button_sequence_clear, 0, wx.ALL, 3)

        self.button_sequence_insert = wx.Button(self.panel_frame_bottom, wx.ID_ANY, "Insert")
        self.button_sequence_insert.SetMinSize((50, 20))
        self.button_sequence_insert.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_sequence_buttons.Add(self.button_sequence_insert, 0, wx.ALL, 3)

        self.button_sequence_remove = wx.Button(self.panel_frame_bottom, wx.ID_ANY, "Remove")
        self.button_sequence_remove.SetMinSize((60, 20))
        self.button_sequence_remove.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_sequence_buttons.Add(self.button_sequence_remove, 0, wx.ALL, 3)

        self.button_sequence_generate = wx.Button(self.panel_frame_bottom, wx.ID_ANY, "Generate")
        self.button_sequence_generate.SetMinSize((65, 20))
        self.button_sequence_generate.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
        sizer_sequence_buttons.Add(self.button_sequence_generate, 0, wx.ALL, 3)

        self.panel_frame_bottom.SetSizer(sizer_sequence)

        self.panel_settings.SetSizer(sizer_settings)

        self.panel_ip.SetSizer(sizer_ip)

        self.pannel_scripts.SetSizer(sizer_scripts)

        self.SetSizer(sizer_frame)

        self.Layout()

        self.Bind(wx.EVT_LISTBOX, self.on_script, self.lb_scripts)
        self.Bind(wx.EVT_BUTTON, self.on_add, self.button_script_add)
        self.Bind(wx.EVT_BUTTON, self.on_copy, self.button_script_copy)
        self.Bind(wx.EVT_BUTTON, self.on_del, self.button_script_delete)
        self.Bind(wx.EVT_BUTTON, self.on_imp, self.button_script_import)
        self.Bind(wx.EVT_BUTTON, self.on_exp, self.button_script_export)
        self.Bind(wx.EVT_BUTTON, self.on_save, self.button_save)
        self.Bind(wx.EVT_BUTTON, self.on_ip_clear, self.button_ip_clear)
        self.Bind(wx.EVT_BUTTON, self.on_ip_insert, self.button_ip_insert)
        self.Bind(wx.EVT_BUTTON, self.on_ip_remove, self.button_ip_remove)
        self.Bind(wx.EVT_BUTTON, self.on_seq_clear, self.button_sequence_clear)
        self.Bind(wx.EVT_BUTTON, self.on_seq_insert, self.button_sequence_insert)
        self.Bind(wx.EVT_BUTTON, self.on_seq_remove, self.button_sequence_remove)
        self.Bind(wx.EVT_BUTTON, self.on_seq_generate, self.button_sequence_generate)
        # end wxGlade
        self.load_sdb()

#--------------------------------------------
# Read and display the current script
#--------------------------------------------
    def show_script(self,script):
        self.label_ip_title_script_name.SetLabel(script)
        conn=sqlite3.connect(db)
        curse = conn.cursor()
        self.grid_ip_list.ClearGrid()
        curse.execute("SELECT * FROM ip WHERE script=?",[script]) 
        rows=curse.fetchall()
        x=0    
        for row in rows:
           self.grid_ip_list.SetCellValue(x,0,row[2])
           self.grid_ip_list.SetCellValue(x,1,row[3])         
           x=x+1           
        self.grid_sequence.ClearGrid()    
        curse.execute("SELECT * FROM attack WHERE script=?",[script]) 
        rows=curse.fetchall()
        x=0    
        for row in rows:
           self.grid_sequence.SetCellValue(x,0,row[2])         
           if row[3]!=0:
               self.grid_sequence.SetCellValue(x,1,str(row[3]))
           self.grid_sequence.SetCellValue(x,2,row[4])
           self.grid_sequence.SetCellValue(x,3,row[5])
           x=x+1           
        curse.execute("SELECT * FROM settings WHERE script=?",[script]) 
        rows=curse.fetchall()
        if len(rows):
            self.text_time_min.SetValue(str(rows[0][1]))
            self.text_time_max.SetValue(str(rows[0][2]))
            self.text_interface.SetValue(str(rows[0][3]))
            if rows[0][4]:
                self.checkbox_delay_all.SetValue(True)
            else:
                self.checkbox_delay_all.SetValue(False)
            if rows[0][5]:
                self.checkbox_debug.SetValue(True)
            else:
                self.checkbox_debug.SetValue(False)
            if rows[0][6]:
                self.checkbox_ips.SetValue(True)
            else:
                self.checkbox_ips.SetValue(False)
            if rows[0][7]:
                self.checkbox_loop.SetValue(True)
            else:
                self.checkbox_loop.SetValue(False)
        conn.close()            
        return
 
#--------------------------------------------
# Open and read the target database
#--------------------------------------------
    def load_sdb(self):
        if not os.path.exists(dbdir):
            os.makedirs(dbdir)
        conn=None
        self.lb_scripts.Clear()
        try:
            conn=sqlite3.connect(db)
            print("Using SQLite "+sqlite3.version)
            curse=conn.cursor() 
            sqstr="CREATE TABLE IF NOT EXISTS scripts (script text PRIMARY KEY)"
            curse.execute(sqstr)
            sqstr="CREATE TABLE IF NOT EXISTS ip (pkey text PRIMARY KEY, script text, name text, ip text)"
            curse.execute(sqstr)
            sqstr="CREATE TABLE IF NOT EXISTS attack (pkey text PRIMARY KEY, script text, action text, shell integer, prompt text, command text)"
            curse.execute(sqstr)
            sqstr="CREATE TABLE IF NOT EXISTS settings (script text PRIMARY KEY, time_min integer, time_max integer, interface text, delay_all int, debug int, ips int, loop int)"
            curse.execute(sqstr)
            curse.execute("SELECT * FROM scripts")            
            tlist=curse.fetchall()
            for row in tlist:
                self.lb_scripts.Append(row[0])
            curse.close()
            if self.lb_scripts.GetCount()>0:
                self.lb_scripts.SetSelection(0)
                scriptname=self.lb_scripts.GetString(0)
                self.show_script(scriptname)   
        except Error as e:
            print(e)
        finally:
            if conn:
                conn.close()
        return
        

    def on_script(self, event):  # wxGlade: Autopilot.<event_handler>
        listno=self.lb_scripts.GetSelection()
        scriptname=self.lb_scripts.GetString(listno)
        self.show_script(scriptname)  
        event.Skip()

#--------------------------------------
# Add a new script
#--------------------------------------
    def on_add(self, event):  # wxGlade: Autopilot.<event_handler>
        scriptname=self.text_script.GetValue()
        self.lb_scripts.Append(scriptname)
        self.lb_scripts.SetStringSelection(scriptname)
        self.label_ip_title_script_name.SetLabel(scriptname)
        conn=sqlite3.connect(db)
        curse = conn.cursor()
        curse.execute("INSERT INTO scripts(script) VALUES('"+scriptname+"')")
        conn.commit()
        conn.close()    
        self.show_script(scriptname)
        self.text_script.SetValue("")
        event.Skip()

    def on_copy(self, event):  # wxGlade: Autopilot.<event_handler>
        listno=self.lb_scripts.GetSelection()
        listname=self.lb_scripts.GetString(listno)
        scriptname=self.text_script.GetValue()
        if scriptname=="":
           wx.MessageBox("Please enter a new script name","",wx_OK,self)
        else:   
            self.lb_scripts.Append(scriptname)
            self.lb_scripts.SetStringSelection(scriptname)
            self.label_ip_title_script_name.SetLabel(scriptname)
            conn=sqlite3.connect(db)
            curse = conn.cursor()
            curse.execute("INSERT INTO scripts(script) VALUES('"+scriptname+"')")
            conn.commit()
            curse.execute("SELECT * FROM ip WHERE script=?",[listname]) 
            rows=curse.fetchall()
            x=0    
            for row in rows:
               self.grid_ip_list.SetCellValue(x,0,row[2])
               self.grid_ip_list.SetCellValue(x,1,row[3])         
               x=x+1           
            conn.commit()
            curse.execute("SELECT * FROM attack WHERE script=?",[listname]) 
            rows=curse.fetchall()
            x=0    
            for row in rows:
               self.grid_sequence.SetCellValue(x,0,row[2])         
               if row[3]!=0:
                   self.grid_sequence.SetCellValue(x,1,str(row[3]))
               self.grid_sequence.SetCellValue(x,2,row[4])
               self.grid_sequence.SetCellValue(x,3,row[5])
               x=x+1           
            conn.commit()
            curse.execute("SELECT * FROM settings WHERE script=?",[listname])
        rows=curse.fetchall()
        self.text_time_min.SetValue(str(rows[0][1]))
        self.text_time_max.SetValue(str(rows[0][2]))
        self.text_interface.SetValue(str(rows[0][3]))
        if rows[0][4]:
            self.checkbox_delay_all.SetValue(True)
        else:
            self.checkbox_delay_all.SetValue(False)
        if rows[0][5]:
            self.checkbox_debug.SetValue(True)
        else:
            self.checkbox_debug.SetValue(False)
        if rows[0][6]:
            self.checkbox_ips.SetValue(True)
        else:
            self.checkbox_ips.SetValue(False)
        if rows[0][7]:
            self.checkbox_loop.SetValue(True)
        else:
            self.checkbox_loop.SetValue(False)
        conn.commit()
        conn.close()    
        self.text_script.SetValue("")
        self.on_save(event)
        self.lb_scripts.SetSelection(self.lb_scripts.FindString(scriptname))
        self.show_script(scriptname)
        event.Skip()

    def on_del(self, event):  # wxGlade: Autopilot.<event_handler>
        listno=self.lb_scripts.GetSelection()
        listname=self.lb_scripts.GetString(listno)
        dlg=wx.MessageDialog(None,"Do you want to delete "+listname+"?","Confirm",wx.YES_NO)
        if dlg.ShowModal()==wx.ID_YES:
            self.lb_scripts.Delete(listno)
            conn=sqlite3.connect(db)
            curse = conn.cursor()
            curse.execute("DELETE FROM scripts WHERE script='"+listname+"'")   
            curse.execute("DELETE FROM ip WHERE script='"+listname+"'")   
            curse.execute("DELETE FROM attack WHERE script='"+listname+"'")
            curse.execute("DELETE FROM settings WHERE script='"+listname+"'")
            conn.commit()
            conn.close()            
            if self.lb_scripts.GetCount()>0:
               if listno>0:
                  listno=listno-1
               self.lb_scripts.SetSelection(listno)
               scriptname=self.lb_scripts.GetString(listno)
               self.label_ip_title_script_name.SetLabel(scriptname)            
        self.label_ip_title_script_name.SetLabel("Script Name")
        event.Skip()

    def on_imp(self, event):  # wxGlade: Autopilot.<event_handler>
        ofd=wx.FileDialog(self, "Open", "", "","*.json",wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
        ofd.ShowModal()
        jfile=ofd.GetPath()
        f=open(jfile,"r")
        js=json.load(f)
        f.close()   
        scriptname=js["script"]
        dlg=wx.MessageDialog(None,"Import "+scriptname+"?","Confirm",wx.YES_NO)
        if dlg.ShowModal()==wx.ID_YES:
            conn=sqlite3.connect(db)
            curse = conn.cursor()
            curse.execute("DELETE FROM ip WHERE script=?",[scriptname])   
            jip=js["ips"]
            x=1
            for jipd in jip:
                pkey=scriptname+str(x)
                pdata=(pkey,scriptname,jipd["name"],jipd["ip"])
                curse.execute("INSERT INTO ip(pkey,script,name,ip) VALUES(?,?,?,?)",pdata)
                x=x+1                    
            conn.commit()
            curse.execute("DELETE FROM attack WHERE script=?",[scriptname])
            jcfg=js['cfg']
            for jcfgd in jcfg:
                try:
                    pdata=(scriptname,jcfgd["time_min"],jcfgd["time_max"],jcfgd["interface"],jcfgd["delay_all"],jcfgd["debug"],jcfgd["ips"],jcfgd["loop"])
                except:
                    pdata=(scriptname,"1","2","eth0","0","0","0","0")
            conn.commit()
            curse.execute("INSERT OR REPLACE INTO settings(script,time_min,time_max,interface,delay_all,debug,ips,loop) VALUES(?,?,?,?,?,?,?,?)",pdata)
            jcm=js["cmds"]
            x=1
            for jcmd in jcm:
                pkey=scriptname+str(x)
                pdata=(pkey,scriptname,jcmd["action"],jcmd["shell"],jcmd["prompt"],jcmd["command"])
                curse.execute("INSERT INTO attack(pkey,script,action,shell,prompt,command) VALUES(?,?,?,?,?,?)",pdata)
                x=x+1                    
            conn.commit() 
            curse.execute("DELETE FROM scripts WHERE script=?",[scriptname])
            curse.execute("INSERT INTO scripts(script) VALUES('"+scriptname+"')")
            conn.commit() 
            self.lb_scripts.Clear()
            curse.execute("SELECT * FROM scripts")            
            tlist=curse.fetchall()
            for row in tlist:
                self.lb_scripts.Append(row[0])
            conn.close()                       
        self.lb_scripts.SetSelection(self.lb_scripts.FindString(scriptname))
        self.show_script(scriptname)
        event.Skip()

    def on_exp(self, event):  # wxGlade: Autopilot.<event_handler>
        scriptname=self.label_ip_title_script_name.GetLabel()
        ofd=wx.FileDialog(self, "Save", "", "","*.json",wx.FD_SAVE)
        ofd.ShowModal()
        jfile=ofd.GetPath()
        js={}
        js["script"]=scriptname
        jip=[]
        for x in range(self.grid_ip_list.GetNumberRows()):
            if self.grid_ip_list.GetCellValue(x,0)!='':  
                jipd={}
                jipd["name"]=self.grid_ip_list.GetCellValue(x,0)
                jipd["ip"]=self.grid_ip_list.GetCellValue(x,1)
                jip.append(jipd)            
        js["ips"]=jip
        jcfg=[]
        jcfgd={}
        jcfgd["time_min"]=self.text_time_min.GetValue()
        jcfgd["time_max"]=self.text_time_max.GetValue()
        jcfgd["interface"]=self.text_interface.GetValue()
        if self.checkbox_delay_all.IsChecked():
            jcfgd["delay_all"]="1"
        else:
            jcfgd["delay_all"]="0"
        if self.checkbox_debug.IsChecked():
            jcfgd["debug"]="1"
        else:
            jcfgd["debug"]="0"
        if self.checkbox_ips.IsChecked():
            jcfgd["ips"]="1"
        else:
            jcfgd["ips"]="0"
        if self.checkbox_loop.IsChecked():
            jcfgd["loop"]="1"
        else:
            jcfgd["loop"]="0"
        jcfg.append(jcfgd)
        js["cfg"]=jcfg
        jcm=[]
        for x in range(self.grid_sequence.GetNumberRows()):
            if self.grid_sequence.GetCellValue(x,0)!='': 
                jcmd={}
                jcmd["action"]=self.grid_sequence.GetCellValue(x,0)
                jcmd["shell"]=self.grid_sequence.GetCellValue(x,1)
                jcmd["prompt"]=self.grid_sequence.GetCellValue(x,2)
                jcmd["command"]=self.grid_sequence.GetCellValue(x,3)
                jcm.append(jcmd)
        js["cmds"]=jcm
        with open(jfile,"w") as f:
            json.dump(js,f)  
        f.close()
        event.Skip()

    def on_save(self, event):  # wxGlade: Autopilot.<event_handler>
        conn=sqlite3.connect(db)
        curse = conn.cursor()
        scriptname=self.label_ip_title_script_name.GetLabel()
        curse.execute("DELETE FROM attack WHERE script=?",[scriptname])
        for x in range(self.grid_sequence.GetNumberRows()):
            if self.grid_sequence.GetCellValue(x,0)!="":
               pkey=scriptname+str(x).zfill(4)
               action=self.grid_sequence.GetCellValue(x,0)
               if self.grid_sequence.GetCellValue(x,1)=="":
                   shell=0
               else:
                   shell=int(self.grid_sequence.GetCellValue(x,1))
               prompt=self.grid_sequence.GetCellValue(x,2)
               command=self.grid_sequence.GetCellValue(x,3)
               pdata=(pkey,scriptname,action,shell,prompt,command)
               curse.execute("INSERT INTO attack(pkey,script,action,shell,prompt,command) VALUES(?,?,?,?,?,?)",pdata)
        conn.commit()
        curse.execute("DELETE FROM ip WHERE script=?",[scriptname])
        for x in range(self.grid_ip_list.GetNumberRows()):
            if self.grid_ip_list.GetCellValue(x,0)!="":
               pkey=scriptname+self.grid_ip_list.GetCellValue(x,0)
               pdata=(pkey,scriptname,self.grid_ip_list.GetCellValue(x,0),self.grid_ip_list.GetCellValue(x,1))
               curse.execute("INSERT INTO ip(pkey,script,name,ip) VALUES(?,?,?,?)",pdata)
        conn.commit()
        curse.execute("DELETE FROM settings WHERE script=?",[scriptname])
        if self.checkbox_delay_all.IsChecked():
            delay_all=1
        else:
            delay_all=0
        if self.checkbox_debug.IsChecked():
            debug=1
        else:
            debug=0
        if self.checkbox_ips.IsChecked():
            ips=1
        else:
            ips=0
        if self.checkbox_loop.IsChecked():
            loop=1
        else:
            loop=0
        pdata=(scriptname,self.text_time_min.GetValue(),self.text_time_max.GetValue(),self.text_interface.GetValue(),delay_all,debug,ips,loop)
        curse.execute("INSERT INTO settings(script,time_min,time_max,interface,delay_all,debug,ips,loop) VALUES(?,?,?,?,?,?,?,?)",pdata)
        conn.commit()
        conn.close()
        event.Skip()

    def on_ip_clear(self, event):  # wxGlade: Autopilot.<event_handler>
        self.grid_ip_list.ClearGrid()
        event.Skip()

    def on_ip_insert(self, event):  # wxGlade: Autopilot.<event_handler>
        grx=self.grid_ip_list.GetGridCursorRow()
        self.grid_ip_list.InsertRows(grx,1)
        event.Skip()

    def on_ip_remove(self, event):  # wxGlade: Autopilot.<event_handler>
        grx=self.grid_ip_list.GetGridCursorRow()
        self.grid_ip_list.DeleteRows(grx,1)
        event.Skip()

    def on_seq_clear(self, event):  # wxGlade: Autopilot.<event_handler>
        self.grid_sequence.ClearGrid()
        event.Skip()

    def on_seq_insert(self, event):  # wxGlade: Autopilot.<event_handler>
        grx=self.grid_sequence.GetGridCursorRow()
        self.grid_sequence.InsertRows(grx,1)
        event.Skip()

    def on_seq_remove(self, event):  # wxGlade: Autopilot.<event_handler>
        grx=self.grid_sequence.GetGridCursorRow()
        self.grid_sequence.DeleteRows(grx,1)
        event.Skip()

    def on_seq_generate(self, event):  # wxGlade: Autopilot.<event_handler>
        if platform.system()=="Windows":
           chaldir=dbdir+self.label_ip_title_script_name.GetLabel()+"\\"    
        else:   
           chaldir=dbdir+self.label_ip_title_script_name.GetLabel()+"/"    
        chalfile=chaldir+self.label_ip_title_script_name.GetLabel()+".py" 
        mutexfile=chaldir+"mutex.txt"
        apifile=chaldir+"mutex-api.py"
        if not os.path.exists(chaldir):
            os.makedirs(chaldir)
        if not os.path.exists(mutexfile):
            create_mutexfile(mutexfile)
        scriptname=self.label_ip_title_script_name.GetLabel()
        iface=self.text_interface.GetValue()
        delay1=0  
        if self.text_time_min.GetValue()!="":
           delay1=int(self.text_time_min.GetValue())
        delay2=delay1
        if self.text_time_max.GetValue()!="":
           delay2=int(self.text_time_max.GetValue())        
        f=open(chalfile,"w")
        f.write("#!/usr/bin/env python3\n")
        f.write("#Kali Autopilot Generated\n")
        f.write("#----------------\n")
        f.write("import paramiko\n")
        f.write("import netifaces as ni\n")
        f.write("import os, sys, time, subprocess, threading, re\n")
        f.write("import pexpect, sarge\n")   
        f.write("from random import seed, randint\n")
        f.write("from functools import wraps\n")
        exploit=False
        for x in range(self.grid_sequence.GetNumberRows()):
            action=self.grid_sequence.GetCellValue(x,0).upper()
            if action=="EXPLOIT":
                exploit=True
        if exploit:
            f.write("from pymetasploit3.msfrpc import MsfRpcClient\n")
        f.write("temple=False\n")
        f.write("fmutex='"+mutexfile+"'\n") 
        f.write("iffy=[True]*50\n")
        if self.checkbox_loop.GetValue():
            f.write("loop=True\n")
        else:
            f.write("loop=False\n")
        f.write("#************************************\n")
        f.write("# Shell main routines               *\n")
        f.write("#************************************\n")
        f.write("class Shell:\n")
        f.write("    meterpreter_prompt = 'meterpreter.* > '\n")
        f.write("    powershell_prompt = 'PS .+> '\n")
        f.write("    @classmethod\n")
        f.write("    def spawn(cls, command, cwd=None, env_mods=None):\n")
        f.write("        pexpect_object = pexpect_spawn(command, cwd, env_mods)\n")
        f.write("        return cls(pexpect_object, shell_received=False, prompt=None)\n")
        f.write("    @classmethod\n")
        f.write("    def spawn_and_receive(cls, command, prompt, timeout=-1, cwd=None, env_mods=None):\n")
        f.write("        s = cls.spawn(command, cwd, env_mods)\n")
        f.write("        s.receive(prompt, timeout=timeout)\n")
        f.write("        return s\n")
        f.write("    def __init__(self, pexpect_object, shell_received, prompt):\n")
        f.write("        self.pexpect_object = pexpect_object\n")
        f.write("        self.shell_received = shell_received\n")
        f.write("        self.prompt = prompt\n")
        f.write("    def send_line(self, line=''):\n")
        f.write("        print('<' + line + '>', end='')\n")
        f.write("        self.pexpect_object.sendline(line)\n")
        f.write("    def expect(self, pattern, timeout=-1):\n")
        f.write("        try:\n")
        f.write("            return self.pexpect_object.expect(pattern, timeout=timeout)\n")
        f.write("        except pexpect.TIMEOUT as e:\n")
        f.write("            if self.shell_received:\n")
        f.write("                raise e\n")
        f.write("            else:\n")
        f.write("                raise FailedToGetShell from None\n")
        f.write("    def receive(self, prompt, timeout=-1):\n")
        f.write("        self.expect(prompt, timeout=timeout)\n")
        f.write("        self.mark_received(prompt)\n")
        f.write("    def mark_received(self, prompt):\n")
        f.write("        self.shell_received = True\n")
        f.write("        self.prompt = prompt\n")
        f.write("    def send_command(self, command, expect=None, new_prompt=None, timeout=-1):\n")
        f.write("        self.send_line(command)\n")
        f.write("        if new_prompt:\n")
        f.write("            self.prompt = new_prompt\n")
        f.write("        self.expect(expect or self.prompt, timeout=timeout)\n")
        f.write("        return self.output\n")
        f.write("    @property\n")
        f.write("    def output(self):\n")
        f.write("        return self.pexpect_object.before\n")
        f.write("    def interact(self):\n")
        f.write("        print('[+] Interacting...')\n")
        f.write("        self.pexpect_object.logfile_read = None  # Disable logging because it bugs out with interact()\n")
        f.write("        self.pexpect_object.sendline()\n")
        f.write("        self.pexpect_object.interact()\n")
        f.write("    def ctrl_c(self):\n")
        f.write("        self.pexpect_object.sendcontrol('c')\n")
        f.write("        self.expect(self.prompt)\n")
        f.write("    def terminate(self):\n")
        f.write("        self.pexpect_object.terminate(force=True)\n")
        f.write("def pexpect_spawn(command, cwd=None, env_mods=None):\n")
        f.write("    _print_command(command)\n")
        f.write("    if env_mods:\n")
        f.write("        env = os.environ.copy()\n")
        f.write("        env.update(env_mods)\n")
        f.write("    else:\n")
        f.write("        env = None\n")
        f.write("    p = pexpect.spawn(command, cwd=cwd, encoding='utf-8', env=env, timeout=60)\n")
        f.write("    p.logfile_read = sys.stdout\n")
        f.write("    p.ignorecase = True\n")
        f.write("    return p\n")
        f.write("def exec_command(command, timeout=None, with_exit_status=False, cwd=None, log=True):\n")
        f.write("    if log:\n")
        f.write("        _print_command(command)\n")
        f.write("        logfile = sys.stdout\n")
        f.write("    else:\n")
        f.write("        logfile = None\n")
        f.write("    return pexpect.run(command, withexitstatus=with_exit_status, cwd=cwd, encoding='utf-8', logfile=logfile, timeout=timeout)\n")
        f.write("def async_exec_command(command, **kwargs):\n")
        f.write("    t = threading.Thread(target=exec_command, args=(command,), kwargs=kwargs, daemon=True)\n")
        f.write("    t.start()\n")
        f.write("def exec_command_with_bash(command, timeout=-1, with_exit_status=False, log=True):\n")
        f.write("    if log:\n")
        f.write("        _print_command(command)\n")
        f.write("        logfile = sys.stdout\n")
        f.write("    else:\n")
        f.write("        logfile = None\n")
        f.write("    p = pexpect.spawn('/bin/bash', ['-c', command], encoding='utf-8', logfile=logfile)\n")
        f.write("    p.expect(pexpect.EOF, timeout)\n")
        f.write("    output = p.before\n")
        f.write("    if with_exit_status:\n")
        f.write("        p.close()\n")
        f.write("        return output, p.exitstatus\n")
        f.write("    else:\n")
        f.write("        return output\n")
        f.write("def async_exec_command_with_bash(command, **kwargs):\n")
        f.write("    t = threading.Thread(target=exec_command_with_bash, args=(command,), kwargs=kwargs, daemon=True)\n")
        f.write("    t.start()\n")
        f.write("def _print_command(command):\n")
        f.write("    combined_whitespace = re.sub(r' +', ' ', command).strip()\n")
        f.write("    print('[*] Running command:', combined_whitespace)\n")
        f.write("#************************************\n")
        f.write("# SOC200 Challenge Addressing       *\n")
        f.write("#************************************\n")
        f.write("def check_deployment():\n")
        f.write("    global x_subnet\n")
        f.write("    try:\n")
        f.write("       ni.ifaddresses('"+iface+"')\n")
        f.write("       ip=ni.ifaddresses('"+iface+"')[ni.AF_INET][0]['addr']\n")
        f.write("    except:\n")
        f.write("       return False\n")
        f.write("    ip_array=ip.split('.')\n")       
        f.write("    x_subnet=ip_array[2]\n")
        f.write("    if x_subnet=='50':\n")
        f.write("       if not temple:\n")
        f.write("          return False\n")
        f.write("    return True\n")
        f.write("def setup_ip(addr):\n")
        f.write("    addr_array=addr.split('.')\n")
        f.write("    addr_array[2]=x_subnet\n")
        f.write("    final_addr=\".\".join(addr_array)\n")
        f.write("    return final_addr\n")
        f.write("#****************************************\n")
        f.write("# Paramiko SSH Routines                 *\n")
        f.write("#****************************************\n")
        f.write("def paramiko_pmopen(dhost,dport,duser,dpwd):\n")
        f.write("    ssh = paramiko.SSHClient()\n")
        f.write("    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n")
        f.write("    try:\n")
        f.write("      ssh.connect(hostname=dhost,port=dport,username=duser,password=dpwd,allow_agent=True,timeout=10)\n")
        f.write("      return ssh\n")
        f.write("    except:\n")
        f.write("      print('Failed to connect')\n")
        f.write("\ndef paramiko_pxopen(phost,puser,dhost,dport,duser,dpwd):\n")
        f.write("    ssh = paramiko.SSHClient()\n")
        f.write("    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n")
        f.write("    try:\n")
        f.write("      psock=paramiko.ProxyCommand('ssh -o VisualHostKey=no -W'+dhost+':'+str(dport)+' '+puser+'@'+phost)\n")
        f.write("      ssh.connect(hostname=dhost,port=dport,username=duser,password=dpwd,allow_agent=True,timeout=10,sock=psock)\n")
        f.write("      return ssh\n")
        f.write("    except:\n")
        f.write("      print('Failed to connect to '+dhost+':'+str(dport))\n")
        f.write("def paramiko_pcmd(sshc,cmd):\n")
        f.write("    try:\n")
        f.write("      stdin,stdout,stderr = sshc.exec_command(cmd) \n")
        f.write("      response=stdout.read().decode()\n")
        f.write("      return(response)\n")
        f.write("    except:\n")
        f.write("      return('Command '+cmd+' failed')\n")
        f.write("#****************************************\n")
        f.write("# Attack Script Proper                  *\n")
        f.write("#****************************************\n")       
        f.write("\n\ndef main():\n")
        if self.checkbox_ips.GetValue(): 
            f.write("    while not check_deployment():\n")
            f.write("        time.sleep(10)\n")
        if exploit:
            f.write("    os.system(\"msfrpcd -P 'offsec' -S\")\n")
            f.write("    client=MsfRpcClient('offsec',port=55553)\n")
            payload='cmd/unix/interact' 
        f.write("    seed(1)\n")
        for x in range(self.grid_ip_list.GetNumberRows()):
            if self.grid_ip_list.GetCellValue(x,0)!="":   
               if self.checkbox_ips.GetValue():
                  f.write("    "+self.grid_ip_list.GetCellValue(x,0)+"=setup_ip('"+self.grid_ip_list.GetCellValue(x,1)+"')\n")
               else:
                  f.write("    "+self.grid_ip_list.GetCellValue(x,0)+"='"+self.grid_ip_list.GetCellValue(x,1)+"'\n")                 
        f.write("    delay_min=" + str(delay1) + "\n")
        f.write("    delay_max=" + str(delay2) + "\n")
        if self.checkbox_delay_all.GetValue():
            f.write("    delay_all=True\n")
        else:
            f.write("    delay_all=False\n")
        if self.checkbox_debug.GetValue():
            f.write("    debug=True\n")
        else:
            f.write("    debug=False\n")
        mutex=0
        f.write("    f=open(fmutex,'r')\n")
        f.write("    index=int(f.read())\n")
        f.write("    f.close()\n\n")
        for x in range(self.grid_sequence.GetNumberRows()):
            action=self.grid_sequence.GetCellValue(x,0).upper()
            refer=self.grid_sequence.GetCellValue(x,1)
            prompt=self.grid_sequence.GetCellValue(x,2) 
            command=self.grid_sequence.GetCellValue(x,3)
            if len(action)==0:
               continue
            if action=="STAGE":
               f.write("    while index=="+str(mutex)+":\n")
               f.write("       time.sleep(5)\n")
               f.write("       f=open(fmutex,'r')\n")
               f.write("       index=int(f.read())\n")
               f.write("       f.close()\n")
               f.write("    if debug:\n")
               f.write("       print('Debug:>', \""+action+" "+refer+" "+prompt+" "+command+"\")\n")            
               mutex=mutex+1
               continue
            if action=="WAIT":
               if int(refer)>0:
                  f.write("    time.sleep("+refer+")\n") 
               continue               
            if delay1>0:
               f.write("\n    if index=="+str(mutex)+" or delay_all:\n")
               f.write("       time.sleep(randint(delay_min,delay_max))\n")
               f.write("    if debug:\n")
               f.write("       print('Debug:>', \""+action+" "+refer+" "+prompt+" "+command+"\")\n")            
            if action=="OS":
               f.write("    x_response=exec_command(f\""+command+"\")\n")
            if action=="OSB":
               f.write("    x_response=exec_command_with_bash(f\""+command+"\")\n")
            if action=="TEST":
               f.write("    iffy["+refer+"]="+prompt+" in x_response")
            if action=="SSH":
               f.write("    ssh"+refer+"=paramiko_pmopen("+command+")\n")
               shelly[int(refer)]="SSH"
            if action=="SHELL":
               f.write("    sh"+refer+"=Shell.spawn_and_receive(f\""+command+"\", prompt=r'"+prompt+"')\n")
               shelly[int(refer)]="Shell"
            if action=="COMMAND":
               if shelly[int(refer)]=="SSH":
                  f.write("    if ssh"+refer+"!=None:\n")
                  f.write("       x_response=paramiko_pcmd(ssh"+refer+",'"+command+"')\n")
               elif shelly[int(refer)]=="Shell":
                  f.write("    if sh"+refer+"!=None:\n")
                  f.write("       sh"+refer+".send_command(f\""+command+"\")\n")            
               elif shelly[int(refer)]=="Metasploit":
                  f.write("    shellm.write('"+command+"')\n")                  
                  f.write("    print(shellm.read())\n")
            if action=="M3SET":
               if prompt.upper()=="EXPLOIT":
                  f.write("    exploit=client.modules.use('exploit','"+command+"')\n")
                  f.write("    shellm=client.sessions.session('1')\n")
               elif prompt.upper()=="PAYLOAD":   
                  payload=command                    
               else:             
                  f.write("    exploit['"+prompt+"']="+command+"\n")
            if action=="EXPLOIT":
               f.write("    exploit.execute(payload='"+payload+"')\n")            
               shelly[int(refer)]="Metasploit"
        f.write("    if debug:\n")
        f.write("\n       print('Attack Complete')\n")            
        f.write("    if not loop:\n")
        f.write("        while True:\n")
        f.write("            time.sleep(100)\n")
        f.write("\n\nif __name__=='__main__':\n")
        f.write("    if loop:\n")
        f.write("        while True:\n")
        f.write("            main()\n")
        f.write("    else:\n")
        f.write("        main()\n")
        f.write("# Script complete\n")
        f.close()
        st = os.stat(chalfile)
        os.chmod(chalfile, st.st_mode | stat.S_IEXEC | stat.S_IXGRP)

        # Create web API to control attack mutex
        create_api_file(self.label_ip_title_script_name.GetLabel(), apifile)

        # Create script to control attack and api services
        create_service_script(self.label_ip_title_script_name.GetLabel(), chaldir, chalfile, chaldir + "service.sh")

        wx.MessageBox("Script "+chalfile+" generated", "",wx.OK,self)
        event.Skip()

# end of class Autopilot

class AutoPilot(wx.App):
    def OnInit(self):
        self.frame = Autopilot(None, wx.ID_ANY, "")
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True

# end of class AutoPilot

if __name__ == "__main__":
    app = AutoPilot(0)
    app.MainLoop()
