示例#1
0
def add_user(_authorization_file, bot_name, group, user_id, bot_oauth_token):
    try:
        with open(_authorization_file) as file:
            authorized_ids = json.load(file)

    except:
        script_name = path.basename(__file__)
        text = '`Authorization file not found`'
        log_ops.log_msg(bot_name=bot_name,
                        script_name=script_name,
                        cmd='Delete userID',
                        status='Failed',
                        result=text,
                        auth='Denied')

    else:
        if group in authorized_ids.keys():
            if user_id not in authorized_ids[group]['user_ids']:
                user = auth_ops.slack_valid_user(bot_oauth_token, user_id,
                                                 bot_name)
                if user:
                    authorized_ids[group]['user_ids'].append(user_id)
                    file = open(_authorization_file, "w")
                    json.dump(authorized_ids, file)
                    file.close()
                    return "```User \"{}\" added to group \"{}\"```".format(
                        user, group)
                else:
                    return "`userID does not exist in Slack`"
            else:
                return "`userID already in group`"
        else:
            return "`Invalid group`"
示例#2
0
def send_file(slack_client, channel, filename, bot_name, title,
              initial_comment):
    # Sends the response back to the channel
    script_name = os.path.basename(__file__)
    # noinspection PyBroadException
    text = 'test'
    try:
        slack_client.api_call("files.upload",
                              channel=channel,
                              title='Automated Inventory Collection',
                              file=filename)
        #slack_client.api_call("chat.postMessage", channel=channel, text=text)
        with open(filename, 'rb') as f:
            slack_client.api_call("files.upload",
                                  channels=channel,
                                  filename=filename,
                                  title=title,
                                  initial_comment=initial_comment,
                                  file=io.BytesIO(f.read()))

    except Exception:
        trace_string = traceback.format_exc()
        log_ops.log_msg(bot_name=bot_name,
                        script_name=script_name,
                        cmd='Send message to Slack',
                        status='Failed',
                        result="Failed\n" + trace_string + "\n")
示例#3
0
def delete_user(_authorization_file, bot_name, user_id):
    found = False
    try:
        with open(_authorization_file) as file:
            authorized_ids = json.load(file)

    except:
        script_name = path.basename(__file__)
        text = '`Authorization file not found`'
        log_ops.log_msg(bot_name=bot_name,
                        script_name=script_name,
                        cmd='Delete userID',
                        status='Failed',
                        result=text,
                        auth='Denied')

    else:
        for group_id in authorized_ids.keys():
            if user_id in authorized_ids[group_id]['user_ids']:
                authorized_ids[group_id]['user_ids'].remove(user_id)
                found = True

    if found:
        file = open(_authorization_file, "w")
        json.dump(authorized_ids, file)
        file.close()
        return "```User deleted```"
    else:
        return "`User not found`"
示例#4
0
def list_users(_authorization_file, bot_name, bot_oauth_token):
    text = ""
    try:
        with open(_authorization_file) as file:
            authorized_ids = json.load(file)

    except:
        script_name = path.basename(__file__)
        text = '`Authorization file not found`'
        log_ops.log_msg(bot_name=bot_name,
                        script_name=script_name,
                        cmd='List userIDs',
                        status='Failed',
                        result=text,
                        auth='Denied')

    else:
        for group_id in authorized_ids.keys():
            text += "* Group name: {}\n".format(group_id)
            text += "Commands: {}\n".format(
                str(authorized_ids[group_id]['cmds']))
            if group_id != 'free':
                text += "Users:\n"
                for item in authorized_ids[group_id]['user_ids']:
                    username, user_email = auth_ops.get_slack_user_info(
                        bot_oauth_token, item, bot_name)
                    text += f"{item} - {username} - {user_email}\n"
                text += "\n"
            else:
                text += "Users: all\n"
        text = "```" + text + "```"

    return text
示例#5
0
def get_slack_user_name(bot_oauth_token, slack_user_id, bot_name):
    script_name = path.basename(__file__)
    payload = {'token': bot_oauth_token, 'user': slack_user_id}
    response = requests.get('https://slack.com/api/users.info', params=payload)
    response_to_dict = json.loads(response.text)
    # noinspection PyBroadException
    try:
        return response_to_dict['user']['real_name']
    except Exception:
        trace_string = traceback.format_exc()
        log_ops.log_msg(bot_name=bot_name,
                        script_name=script_name,
                        cmd='Query username',
                        status='Failed',
                        result=trace_string,
                        auth='Approved')
def run(**kwargs):
    script_name = path.basename(__file__)
    command_splited = kwargs['command_splited']
    slack_client = kwargs['slack_client']
    channel = kwargs['channel']

    log_ops.log_msg(bot_name=kwargs['bot_name'],
                    script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                    channel=channel,
                    username=kwargs['username'],
                    cmd=kwargs['command'],
                    auth='Approved',
                    status='Ok',
                    result='Starting')

    if len(command_splited) == 1:
        string_filter = ''
        validate_hosts_ops.list_inventory(slack_client, channel, string_filter,
                                          kwargs['bot_cmd_log_file'],
                                          kwargs['username'],
                                          kwargs['command'],
                                          kwargs['bot_name'])

    elif len(command_splited) == 2:
        string_filter = command_splited[1]
        string_filter = string_filter.replace('*', '.*')
        validate_hosts_ops.list_inventory(slack_client, channel, string_filter,
                                          kwargs['bot_cmd_log_file'],
                                          kwargs['username'],
                                          kwargs['command'],
                                          kwargs['bot_name'])

    else:
        slack_ops.send_msg(slack_client, channel, "`Invalid Syntax`",
                           kwargs['bot_name'])
        log_ops.log_msg(bot_name=kwargs['bot_name'],
                        script_name=script_name,
                        bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                        channel=channel,
                        username=kwargs['username'],
                        cmd=kwargs['command'],
                        auth='Approved',
                        status='Failed',
                        result='Invalid Syntax')
示例#7
0
def authorize_json(_authorization_file, user_id, bot_name):
    try:
        with open(_authorization_file) as file:
            authorized_ids = json.load(file)
    except:
        script_name = path.basename(__file__)
        log_ops.log_msg(bot_name=bot_name,
                        script_name=script_name,
                        cmd='Authorize userID',
                        status='Failed',
                        result='Authorization file not found',
                        auth='Denied')
        return False, []
    else:
        for group_id in authorized_ids.keys():
            if user_id in authorized_ids[group_id]['user_ids']:
                return group_id, authorized_ids[group_id]['cmds']
        return 'free', authorized_ids['free']['cmds']
示例#8
0
def run(**kwargs):
    script_name = path.basename(__file__)
    command_splited = kwargs['command_splited']
    slack_client = kwargs['slack_client']
    channel = kwargs['channel']

    log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel, username=kwargs['username'],
                    cmd=kwargs['command'], auth='Approved', status='Ok', result='Starting')

    if len(command_splited) >= 3 and str(command_splited[-1]).endswith("\"") and\
            str(command_splited[2]).startswith("\""):
        source = command_splited[1]
        valid_source = validate_hosts_ops.verify_source_in_inventory(source)

        if valid_source:
            join_cmd = command_splited[2:]
            pre_cmd = ""
            for item in join_cmd:
                pre_cmd += item + " "
            final_cmd = pre_cmd[1:-2]

            if len(final_cmd) < 51:
                if final_cmd.startswith("sh"):
                    playbook = "net-ios-show-msg-slack.yml"

                    bot_playbooks_directory = kwargs['bot_playbooks_directory']
                    playbook_full_path = bot_playbooks_directory + playbook
                    ansible_common_inventory_full_path_name = kwargs['ansible_common_inventory_full_path_name']

                    json = True

                    ansible_ops.ansible_cmd(json, playbook_full_path, ansible_common_inventory_full_path_name, channel,
                                            slack_client, kwargs['username'], kwargs['bot_name'],
                                            kwargs['bot_cmd_log_file'],
                                            source=source, cmd=final_cmd)
            else:
                slack_ops.send_msg(slack_client, channel, "`Command too long, max. 50 characters`", kwargs['bot_name'])
                log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                                bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel,
                                username=kwargs['username'],
                                cmd=kwargs['command'], auth='Approved', status='Failed',
                                result='Command too long, max. 50 characters')
        else:
            slack_ops.send_msg(slack_client, channel, "`Invalid Device`", kwargs['bot_name'])
            log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                            bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel, username=kwargs['username'],
                            cmd=kwargs['command'], auth='Approved', status='Failed', result='Invalid Device')

    else:
        slack_ops.send_msg(slack_client, channel, "`Invalid Syntax`", kwargs['bot_name'])
        log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                        bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel, username=kwargs['username'],
                        cmd=kwargs['command'], auth='Approved', status='Failed', result='Invalid Syntax')
示例#9
0
def run(**kwargs):
    script_name = path.basename(__file__)
    command_splited = kwargs['command_splited']
    slack_client = kwargs['slack_client']
    channel = kwargs['channel']
    text = ''
    log_ops.log_msg(bot_name=kwargs['bot_name'],
                    script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                    channel=channel,
                    username=kwargs['username'],
                    cmd=kwargs['command'],
                    auth='Approved',
                    status='Ok',
                    result='Starting')

    if len(command_splited) == 2 and command_splited[1] == 'list':
        text = list_users(kwargs['bot_authorized_users_file'],
                          kwargs['bot_name'], kwargs['bot_oauth_token'])
        status = 'OK'
    elif len(command_splited) == 3 and command_splited[1] == 'delete':
        text = delete_user(kwargs['bot_authorized_users_file'],
                           kwargs['bot_name'], command_splited[2])
        status = 'OK'
    elif len(command_splited) == 4 and command_splited[1] == 'add':
        text = add_user(kwargs['bot_authorized_users_file'],
                        kwargs['bot_name'], command_splited[2],
                        command_splited[3], kwargs['bot_oauth_token'])
        status = 'OK'
    else:
        text = "`Invalid Syntax`"
        status = 'Failed'

    slack_ops.send_msg(slack_client, channel, text, kwargs['bot_name'])
    log_ops.log_msg(bot_name=kwargs['bot_name'],
                    script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                    channel=channel,
                    username=kwargs['username'],
                    cmd=kwargs['command'],
                    auth='Approved',
                    status=status,
                    result=text)
示例#10
0
def authorize_txt(_authorization_file, item_id, bot_name):
    try:
        file = open(_authorization_file, 'r')
        authorized_ids = file.read()
        file.close()
    except:
        script_name = path.basename(__file__)
        log_ops.log_msg(bot_name=bot_name,
                        script_name=script_name,
                        cmd='Authorize userID',
                        status='Failed',
                        result='Authorization file not found',
                        auth='Denied')
        return False, []
    else:
        if item_id in authorized_ids:
            return "neteng", []
        else:
            return False, []
示例#11
0
def send_msg(slack_client, channel, response, bot_name):
    # Sends the response back to the channel
    script_name = os.path.basename(__file__)
    # noinspection PyBroadException

    if len(response) <= 3800:
        try:
            slack_client.api_call("chat.postMessage",
                                  channel=channel,
                                  text=response)
        except Exception:
            trace_string = traceback.format_exc()
            log_ops.log_msg(bot_name=bot_name,
                            script_name=script_name,
                            cmd='Send message to Slack',
                            status='Failed',
                            result="Failed\n" + trace_string + "\n")
    else:
        if response.startswith('```'):
            response = response[3:-3]
            is_error = False
        else:
            response = response[1:-1]
            is_error = True

        step = 3800
        response_list = []
        for i in range(0, len(response), 3800):
            response_list.append(response[i:step])
            step += 3800

        for i in range(0, len(response_list)):
            if is_error:
                text = '`' + response_list[i] + '`'
            else:
                text = '```' + response_list[i] + '```'

            slack_client.api_call("chat.postMessage",
                                  channel=channel,
                                  text=text)

            time.sleep(1)
示例#12
0
def run(**kwargs):
    script_name = path.basename(__file__)
    command_splited = kwargs['command_splited']
    slack_client = kwargs['slack_client']
    channel = kwargs['channel']

    log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel, username=kwargs['username'],
                    cmd=kwargs['command'], auth='Approved', status='Ok', result='Starting')

    if len(command_splited) == 3:
        source = command_splited[1]
        valid_source = validate_hosts_ops.verify_source_in_inventory(source)

        if valid_source:
            destination = command_splited[2]
            valid_destination = validate_hosts_ops.verify_host_address(destination)

            if valid_destination:

                playbook = "net-trace-msg-slack.yml"

                bot_playbooks_directory = kwargs['bot_playbooks_directory']
                playbook_full_path = bot_playbooks_directory + playbook
                ansible_common_inventory_full_path_name = kwargs['ansible_common_inventory_full_path_name']

                json = True

                ansible_ops.ansible_cmd(json, playbook_full_path, ansible_common_inventory_full_path_name, channel,
                                        slack_client, kwargs['username'], kwargs['bot_name'],
                                        kwargs['bot_cmd_log_file'],
                                        source=source, destination=valid_destination)

            else:
                slack_ops.send_msg(slack_client, channel, "`Invalid Destination`", kwargs['bot_name'])
                log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                                bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel,
                                username=kwargs['username'],
                                cmd=kwargs['command'], auth='Approved', status='Failed', result='Invalid Destination')
        else:
            slack_ops.send_msg(slack_client, channel, "`Invalid Device`", kwargs['bot_name'])
            log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                            bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel, username=kwargs['username'],
                            cmd=kwargs['command'], auth='Approved', status='Failed', result='Invalid Device')

    else:
        slack_ops.send_msg(slack_client, channel, "`Invalid Syntax`", kwargs['bot_name'])
        log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                        bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel, username=kwargs['username'],
                        cmd=kwargs['command'], auth='Approved', status='Failed', result='Invalid Syntax')
示例#13
0
    def run(self):
        script_name = path.basename(__file__)
        proc = subprocess.Popen(self.cmd,
                                shell=True,
                                stdout=sys.stdout,
                                stderr=sys.stdout,
                                universal_newlines=True)
        # pid = proc.pid

        slack_ops.send_msg(
            self.slack_client, self.channel,
            "```Executing command - TaskID={}```".format(str(self.task_id)),
            self.bot_name)

        log_ops.log_msg(bot_cmd_log_file=self.bot_cmd_log_file,
                        script_name=script_name,
                        bot_name=self.bot_name,
                        username=self.username,
                        channel=self.channel,
                        cmd=self.cmd,
                        task_id=self.task_id,
                        status="Ok",
                        result="Running")

        while proc.poll() is None:
            time.sleep(2)

        msg = "Command finished - TaskID={}".format(str(self.task_id))
        slack_ops.send_msg(self.slack_client, self.channel,
                           "```{}```".format(msg), self.bot_name)
        log_ops.log_msg(bot_cmd_log_file=self.bot_cmd_log_file,
                        script_name=script_name,
                        bot_name=self.bot_name,
                        username=self.username,
                        channel=self.channel,
                        cmd=self.cmd,
                        task_id=self.task_id,
                        status="Ok",
                        result="Finished")
示例#14
0
def ansible_cmd(json, playbook_full_path_name,
                ansible_common_inventory_full_path_name, channel, slack_client,
                username, bot_name, bot_cmd_log_file, **kwargs):
    script_name = path.basename(__file__)
    cmd = "ansible-playbook " + playbook_full_path_name + \
          " -i " + ansible_common_inventory_full_path_name + " --extra-vars \""

    task_id = randint(0, 999999)

    if json:
        extra_vars_json = {key: value for key, value in kwargs.items()}
        extra_vars_json["channel"] = channel
        extra_vars_json["username"] = username
        extra_vars_json["bot_name"] = bot_name
        extra_vars_json["task_id"] = task_id
        cmd += str(extra_vars_json) + "\" -vvvv"
    else:
        for key, value in kwargs.items():
            cmd += key + "=" + str(value) + " "
        cmd += "channel=" + channel + " username="******" bot_name=" + bot_name + " task_id=" + str(
            task_id) + "\" -vvvv"

    process_name = "ansible-playbook"

    if scheduler.go(process_name):
        thread = AnsibleExecThread(slack_client, channel, cmd, username,
                                   bot_name, bot_cmd_log_file, task_id)
        thread.start()
    else:
        msg = "Scheduler: Can't launch task, too many running, wait a couple of minutes and try again"
        slack_ops.send_msg(slack_client, channel, "```{}```".format(msg),
                           bot_name)
        log_ops.log_msg(bot_name=bot_name,
                        script_name=script_name,
                        username=username,
                        channel=channel,
                        status="Failed",
                        result='Scheduler: Too many tasks running')
示例#15
0
def python3_cmd(cmd, channel, slack_client, username, bot_name,
                bot_cmd_log_file, **kwargs):
    script_name = path.basename(__file__)

    task_id = randint(0, 999999)

    cmd += " {} {} {} {}".format(channel, username, bot_name, task_id)

    process_name = "python3"

    if scheduler.go(process_name):
        thread = Python3ExecThread(slack_client, channel, cmd, username,
                                   bot_name, bot_cmd_log_file, task_id)
        thread.start()
    else:
        msg = "Scheduler: Can't launch task, too many running, wait a couple of minutes and try again"
        slack_ops.send_msg(slack_client, channel, "```{}```".format(msg),
                           bot_name)
        log_ops.log_msg(bot_name=bot_name,
                        script_name=script_name,
                        username=username,
                        channel=channel,
                        status="Failed",
                        result='Scheduler: Too many tasks running')
示例#16
0
def run(**kwargs):
    script_name = path.basename(__file__)
    discovered_plugins = kwargs['discovered_plugins']
    command_splited = kwargs['command_splited']
    slack_client = kwargs['slack_client']
    channel = kwargs['channel']

    log_ops.log_msg(bot_name=kwargs['bot_name'],
                    script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                    channel=channel,
                    username=kwargs['username'],
                    cmd=kwargs['command'],
                    auth='Approved',
                    status='Ok',
                    result='Starting')

    log_ops.log_msg(bot_name=kwargs['bot_name'],
                    script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                    channel=channel,
                    username=kwargs['username'],
                    cmd=kwargs['command'],
                    auth='Approved',
                    status='Ok',
                    result='Running')

    if len(command_splited) == 1:
        response = "```This is the available list of commands:\n"
        for cmd, value in discovered_plugins.items():
            if kwargs['user_group'] == 'neteng':
                response += "- " + value.command_syntax() + "\n"
            elif cmd in kwargs['auth_cmds']:
                response += "- " + value.command_syntax() + "\n"
        response += "```"

    elif command_splited[1].replace(".", "_") not in discovered_plugins.keys():
        response = "`The command \"{}\" don't exists. Try \"@botnet help\" to view available commands`".format(
            command_splited[1])
        slack_ops.send_msg(slack_client, channel, response, kwargs['bot_name'])
        log_ops.log_msg(bot_name=kwargs['bot_name'],
                        script_name=script_name,
                        bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                        channel=channel,
                        username=kwargs['username'],
                        cmd=kwargs['command'],
                        auth='Approved',
                        status='Failed',
                        result=response)
        return

    else:
        response = "```" + discovered_plugins[command_splited[1].replace(
            '.', '_')].command_help() + "```"

    slack_ops.send_msg(slack_client, channel, response, kwargs['bot_name'])
    log_ops.log_msg(bot_name=kwargs['bot_name'],
                    script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                    channel=channel,
                    username=kwargs['username'],
                    cmd=kwargs['command'],
                    auth='Approved',
                    status='Ok',
                    result='Finished')
示例#17
0
        print('no')
    else:
        text = "Device \"{}\"".format(source)
        ip_host_mask = ip_address.split()[1] + " 255.255.255.255"
        if ip_address in output.lower() or ip_host_mask in output.lower():
            print('yes')
            text = "Removing from object group"
            status = 'Ok'
            result = 'Parsed'
        else:
            print('no')
            status = 'Not Found'
            result = 'Parsed'
            text += " - IP " + ip_address + " not in group \"" + object_group + "\""
            text = "`" + text + "`"

if status == 'Failed' or status == 'Not Found':
    slack_ops.send_msg(slack_client, channel, text, bot_name)

print("Text= " + text)
log_ops.log_msg(bot_name=bot_name,
                script_name=script_name,
                bot_cmd_log_file=bot_cmd_log_file,
                channel=channel,
                username=username,
                cmd=sys.argv[0],
                auth='Approved',
                status=status,
                result=result,
                task_id=task_id)
示例#18
0
def run(**kwargs):
    script_name = path.basename(__file__)
    command_splited = kwargs['command_splited']
    slack_client = kwargs['slack_client']
    channel = kwargs['channel']

    log_ops.log_msg(bot_name=kwargs['bot_name'],
                    script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                    channel=channel,
                    username=kwargs['username'],
                    cmd=kwargs['command'],
                    auth='Approved',
                    status='Ok',
                    result='Starting')

    if len(command_splited) >= 3 and str(command_splited[-1]).endswith("\"") and\
            str(command_splited[2]).startswith("\""):
        sources = re.search(r'src=(.*)', command_splited[1])
        destinations = "dummy"

        if sources and destinations:
            list_sources, sources_count, list_destinations, destinations_count =\
                validate_hosts_ops.identify_elements(sources[1], destinations[1])

            if sources_count != 0:

                if sources_count <= int(kwargs['max_devices']):
                    join_cmd = command_splited[2:]
                    pre_cmd = ""
                    for item in join_cmd:
                        pre_cmd += item + " "
                    final_cmd = pre_cmd[1:-2]

                    if len(final_cmd) < 51:
                        if final_cmd.startswith("show"):
                            playbook = "net-ios-show-msg-slack.yml"

                            bot_playbooks_directory = kwargs[
                                'bot_playbooks_directory']
                            playbook_full_path = bot_playbooks_directory + playbook
                            ansible_common_inventory_full_path_name = kwargs[
                                'ansible_common_inventory_full_path_name']

                            json = True

                            ansible_ops.ansible_cmd(
                                json,
                                playbook_full_path,
                                ansible_common_inventory_full_path_name,
                                channel,
                                slack_client,
                                kwargs['username'],
                                kwargs['bot_name'],
                                kwargs['bot_cmd_log_file'],
                                source=list(list_sources),
                                cmd=final_cmd)

                    else:
                        slack_ops.send_msg(
                            slack_client, channel,
                            "`Command too long, max. 50 characters`",
                            kwargs['bot_name'])
                        log_ops.log_msg(
                            bot_name=kwargs['bot_name'],
                            script_name=script_name,
                            bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                            channel=channel,
                            username=kwargs['username'],
                            cmd=kwargs['command'],
                            auth='Approved',
                            status='Failed',
                            result='Command too long, max. 50 characters')

                else:
                    slack_ops.send_msg(
                        slack_client, channel,
                        "`Too many devices. Max {}`".format(
                            kwargs['max_devices']), kwargs['bot_name'])
                    log_ops.log_msg(
                        bot_name=kwargs['bot_name'],
                        script_name=script_name,
                        bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                        channel=channel,
                        username=kwargs['username'],
                        cmd=kwargs['command'],
                        auth='Approved',
                        status='Failed',
                        result='Too many devices. Max {}'.format(
                            kwargs['max_devices']))

            else:
                slack_ops.send_msg(slack_client, channel, "`Invalid Sources`",
                                   kwargs['bot_name'])
                log_ops.log_msg(bot_name=kwargs['bot_name'],
                                script_name=script_name,
                                bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                                channel=channel,
                                username=kwargs['username'],
                                cmd=kwargs['command'],
                                auth='Approved',
                                status='Failed',
                                result='Invalid Sources')

        else:
            slack_ops.send_msg(slack_client, channel, "`Invalid Devices`",
                               kwargs['bot_name'])
            log_ops.log_msg(bot_name=kwargs['bot_name'],
                            script_name=script_name,
                            bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                            channel=channel,
                            username=kwargs['username'],
                            cmd=kwargs['command'],
                            auth='Approved',
                            status='Failed',
                            result='Invalid Devices')

    else:
        slack_ops.send_msg(slack_client, channel, "`Invalid Syntax`",
                           kwargs['bot_name'])
        log_ops.log_msg(bot_name=kwargs['bot_name'],
                        script_name=script_name,
                        bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                        channel=channel,
                        username=kwargs['username'],
                        cmd=kwargs['command'],
                        auth='Approved',
                        status='Failed',
                        result='Invalid Syntax')
示例#19
0
def list_inventory(slack_client, channel, string_filter, bot_cmd_log_file,
                   username, cmd, bot_name):
    text = ""
    is_first = True
    script_name = os.path.basename(__file__)

    log_ops.log_msg(bot_name=bot_name,
                    script_name=script_name,
                    bot_cmd_log_file=bot_cmd_log_file,
                    channel=channel,
                    username=username,
                    cmd=cmd,
                    auth='Approved',
                    status='Ok',
                    result='Running')

    if string_filter == '':
        text = "```"
        with open(_PYCHATOPS_HOME_DIRECTORY + "devices/hosts", "r") as file:
            for line in file:

                if '[' in line:
                    match = re.search(r'\[(.*)\]', line)
                    if match:
                        if is_first:
                            text += "\n=========================================================\n" + \
                                    "| {:<53} |".format(match.group(1).lower()) \
                                    + "\n=========================================================\n"
                            is_first = False

                        else:
                            text += "=========================================================\n" + \
                                    "\n=========================================================\n" + \
                                    "| {:<53} |".format(match.group(1).lower()) \
                                    + "\n=========================================================\n"
                match = re.search(
                    r'(.*) ansible_host=([^\s]+)(.*)platform=([^\s]+)', line)

                if match:
                    text += '| {:<20}  | {:<18} | {:<8} |\n'.format(
                        match[1], match[2], match[4])

        text += "=========================================================```"

    else:
        with open(_PYCHATOPS_HOME_DIRECTORY + "devices/hosts", "r") as file:
            for line in file:

                if '[' in line:
                    continue

                match_line = re.search(string_filter, line)

                if match_line:
                    match_capture_detail = re.search(
                        r'(.*) ansible_host=([^\s]+)(.*)platform=([^\s]+)',
                        line)

                    if match_capture_detail:
                        text += '| {:<20}  | {:<18} | {:<8} |\n'.format(
                            match_capture_detail[1], match_capture_detail[2],
                            match_capture_detail[4])

        text += ""

        if len(text) == 0:
            text = "`No matching devices`"
        else:
            text = "```" + text + "```"

    slack_ops.send_msg(slack_client, channel, text, bot_name)

    log_ops.log_msg(bot_name=bot_name,
                    script_name=script_name,
                    bot_cmd_log_file=bot_cmd_log_file,
                    channel=channel,
                    username=username,
                    cmd=cmd,
                    auth='Approved',
                    status='Ok',
                    result='Finished')
示例#20
0
def run(**kwargs):
    script_name = path.basename(__file__)
    command_splited = kwargs['command_splited']
    slack_client = kwargs['slack_client']
    channel = kwargs['channel']

    log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel, username=kwargs['username'],
                    cmd=kwargs['command'], auth='Approved', status='Ok', result='Starting')

    if 2 <= len(command_splited) <= 3:

        ip = command_splited[1]
        valid_ip = validate_hosts_ops.verify_host_address(ip)
        ip_text = ''

        if valid_ip:
            if len(command_splited) == 3:
                if command_splited[2].isnumeric():
                    if 24 <= int(command_splited[2]) <= 31:
                        ip_data = ipaddress.ip_network(valid_ip + "/" + command_splited[2], strict=False)
                        ip_data = ip_data.with_netmask
                        ip_data = str(ip_data)
                        ip_data = ip_data.split('/')
                        valid_subnet = True
                        ip_text = ip_data[0] + " " + ip_data[1]

                    else:
                        valid_subnet = False

                else:
                    valid_subnet = False

            else:
                ip_text = "host " + valid_ip
                valid_subnet = True

            if valid_ip and valid_subnet:

                playbook = "net-asa-no-obj-grp-msg-slack.yml"

                bot_playbooks_directory = kwargs['bot_playbooks_directory']
                playbook_full_path = bot_playbooks_directory + playbook
                json = True

                source = 'all'
                ip_address = ip_text
                object_group = "blacklist"

                ansible_common_inventory_full_path_name = kwargs['ansible_common_inventory_full_path_name']

                ansible_ops.ansible_cmd(json, playbook_full_path, ansible_common_inventory_full_path_name, channel,
                                        slack_client, kwargs['username'], kwargs['bot_name'], kwargs['bot_cmd_log_file'],
                                        ip_address=ip_address, object_group=object_group, source=source, function='remove')

            else:
                slack_ops.send_msg(slack_client, channel, "`Invalid Subnet`", kwargs['bot_name'])
                log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                                bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel, username=kwargs['username'],
                                cmd=kwargs['command'], auth='Approved', status='Failed', result='Invalid Subnet')

        else:
            slack_ops.send_msg(slack_client, channel, "`Invalid IP address`", kwargs['bot_name'])
            log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                            bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel, username=kwargs['username'],
                            cmd=kwargs['command'], auth='Approved', status='Failed', result='Invalid IP address')
    else:
        slack_ops.send_msg(slack_client, channel, "`Invalid Syntax. Try \"@botnet help block.ip\"`", kwargs['bot_name'])
        log_ops.log_msg(bot_name=kwargs['bot_name'], script_name=script_name,
                        bot_cmd_log_file=kwargs['bot_cmd_log_file'], channel=channel, username=kwargs['username'],
                        cmd=kwargs['command'], auth='Approved', status='Failed', result='Invalid Syntax')
示例#21
0
def start(**kwargs):
    script_name = path.basename(__file__)
    bot_name = kwargs['bot_name'].lower()
    if bot_name == 'net':
        _RTM_READ_DELAY = 0.1
    else:
        _RTM_READ_DELAY = rtm_read_delay
    bot_log_file = _PYCHATOPS_HOME_DIRECTORY + config['Slack']['bot_' +
                                                               bot_name +
                                                               '_log_file']
    bot_cmd_log_file = config['Slack']['bot_' + bot_name + '_cmd_log']
    bot_oauth_token = config['Slack']['bot_' + bot_name + '_oauth']
    bot_playbooks_directory = _PYCHATOPS_HOME_DIRECTORY + config['Slack'][
        'bot_' + bot_name + '_ansible_playbooks_full_path_name']
    bot_authorized_users_file = _PYCHATOPS_HOME_DIRECTORY + config['Slack'][
        'bot_' + bot_name + '_authorized_users_file']
    extra_data_file = _PYCHATOPS_HOME_DIRECTORY + config['Slack'][
        'bot_' + bot_name + '_extra_data_file']

    # sys.stdout = open(bot_log_file, 'a+')

    plugins_path = bots_directory + bot_name.lower() + "/"

    if plugins_path not in sys.path:
        sys.path.insert(0, plugins_path)

    discovered_plugins = {
        name: importlib.import_module(name)
        for finder, name, ispkg in pkgutil.iter_modules([plugins_path])
        # if name.startswith('user_') or name.startswith('help')
    }

    log_ops.log_msg(bot_cmd_log_file=bot_cmd_log_file,
                    status='Ok',
                    username='******',
                    bot_name=bot_name,
                    script_name=script_name,
                    cmd='Start Bot',
                    result="Started")

    slack_client = SlackClient(bot_oauth_token)

    if slack_client.rtm_connect(with_team_state=False):
        log_ops.log_msg(bot_cmd_log_file=bot_cmd_log_file,
                        status='Ok',
                        bot_name=bot_name,
                        script_name=script_name,
                        username='******',
                        cmd='Connect to Slack',
                        result="Bot Started and Running!")
        # Read bot's user ID by calling Web API method `auth.test`
        starterbot_id = slack_client.api_call("auth.test")["user_id"]

        while True:
            try:
                command, channel, slack_userid = slack_ops.parse_bot_commands(
                    starterbot_id, slack_client.rtm_read())
            except Exception:
                trace_string = traceback.format_exc()
                log_ops.log_msg(bot_name=bot_name,
                                script_name=script_name,
                                cmd='Connect to Slack',
                                status='Failed',
                                username='******',
                                result="Can't connect\n" + trace_string +
                                "\nRetrying")
                time.sleep(5)
                slack_client.rtm_connect(with_team_state=False)

            else:
                if command:
                    command_splited = command.split()
                    command_splited[0] = command_splited[0].replace('.', '_')
                    username = auth_ops.get_slack_user_name(
                        bot_oauth_token, slack_userid, bot_name)

                    if command_splited[0] in discovered_plugins.keys():
                        if bot_authorized_users_file.endswith('all'):
                            user_group, auth_cmds = 'neteng', []
                        elif bot_authorized_users_file.endswith('txt'):
                            user_group, auth_cmds = auth_ops.authorize_txt(
                                bot_authorized_users_file, slack_userid,
                                bot_name)
                        else:
                            user_group, auth_cmds = auth_ops.authorize_json(
                                bot_authorized_users_file, slack_userid,
                                bot_name)

                        auth = 'Approved' if user_group else 'Denied'

                        log_ops.log_msg(bot_name=bot_name,
                                        script_name=script_name,
                                        bot_cmd_log_file=bot_cmd_log_file,
                                        channel=channel,
                                        username=username,
                                        cmd=command,
                                        auth=auth,
                                        status='Ok',
                                        result='Command recognized')

                        if (user_group is not False) and (
                            (user_group == "neteng") or
                            (command_splited[0] in auth_cmds)):
                            discovered_plugins[command_splited[0]].run(
                                discovered_plugins=discovered_plugins,
                                command_splited=command_splited,
                                slack_client=slack_client,
                                channel=channel,
                                bot_playbooks_directory=bot_playbooks_directory,
                                ansible_common_inventory_full_path_name=
                                ansible_common_inventory_full_path_name,
                                bots_directory=bots_directory,
                                netor_home_directory=_PYCHATOPS_HOME_DIRECTORY,
                                bot_directory=bots_directory + bot_name,
                                extra_data_file=extra_data_file,
                                username=username,
                                user_group=user_group,
                                bot_cmd_log_file=bot_cmd_log_file,
                                command=command,
                                bot_name=bot_name,
                                multiple_src_dst=multiple_src_dst,
                                max_devices=max_devices,
                                auth_cmds=auth_cmds,
                                bot_authorized_users_file=
                                bot_authorized_users_file,
                                bot_oauth_token=bot_oauth_token)

                        else:
                            slack_ops.send_msg(
                                slack_client, channel,
                                "`User \"{}\" not authorized`".format(
                                    username), bot_name)
                            log_ops.log_msg(bot_name=bot_name,
                                            script_name=script_name,
                                            bot_cmd_log_file=bot_cmd_log_file,
                                            channel=channel,
                                            username=username,
                                            auth=auth,
                                            cmd=command,
                                            status='Failed',
                                            result='User not authorized')

                    else:
                        response = "`Command unknown. Try \"@Bot-" + bot_name.upper() + \
                                   " help\" to view available commands.`"

                        slack_ops.send_msg(slack_client, channel, response,
                                           bot_name)
                        log_ops.log_msg(bot_name=bot_name,
                                        script_name=script_name,
                                        bot_cmd_log_file=bot_cmd_log_file,
                                        channel=channel,
                                        username=username,
                                        cmd=command,
                                        status='Failed',
                                        result='Invalid command')

            time.sleep(_RTM_READ_DELAY)

    else:
        log_ops.log_msg(bot_name=bot_name,
                        script_name=script_name,
                        username='******',
                        bot_cmd_log_file=bot_cmd_log_file,
                        cmd='Connect to Slack',
                        status='Failed',
                        result="Bot restart required")
示例#22
0
def run(**kwargs):
    script_name = path.basename(__file__)
    command_splited = kwargs['command_splited']
    slack_client = kwargs['slack_client']
    channel = kwargs['channel']

    log_ops.log_msg(bot_name=kwargs['bot_name'],
                    script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                    channel=channel,
                    username=kwargs['username'],
                    cmd=kwargs['command'],
                    auth='Approved',
                    status='Ok',
                    result='Starting')

    if 3 <= len(command_splited) <= 4:
        source = validate_hosts_ops.verify_source_in_inventory(
            command_splited[1])

        if source:
            destination = validate_hosts_ops.verify_host_address(
                command_splited[2])
            if not destination:
                _, destination = validate_hosts_ops.verify_destination_ip_in_inventory(
                    command_splited[2])
                if len(destination) != 0:
                    destination = list(destination)[0]

            if destination:
                count = 4
                if len(command_splited) == 4 and command_splited[3] <= 100:
                    count = command_splited[3]

                playbook = "net-ping-msg-slack.yml"

                bot_playbooks_directory = kwargs['bot_playbooks_directory']
                playbook_full_path = bot_playbooks_directory + playbook
                json = False

                ansible_common_inventory_full_path_name = kwargs[
                    'ansible_common_inventory_full_path_name']

                ansible_ops.ansible_cmd(
                    json,
                    playbook_full_path,
                    ansible_common_inventory_full_path_name,
                    channel,
                    slack_client,
                    kwargs['username'],
                    kwargs['bot_name'],
                    kwargs['bot_cmd_log_file'],
                    source=source,
                    destination=destination,
                    count=count)

            else:
                slack_ops.send_msg(slack_client, channel,
                                   "`Invalid Destination`", kwargs['bot_name'])
                log_ops.log_msg(bot_name=kwargs['bot_name'],
                                script_name=script_name,
                                bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                                channel=channel,
                                username=kwargs['username'],
                                cmd=kwargs['command'],
                                auth='Approved',
                                status='Failed',
                                result='Invalid Destination')

        else:
            slack_ops.send_msg(slack_client, channel, "`Invalid Source`",
                               kwargs['bot_name'])
            log_ops.log_msg(bot_name=kwargs['bot_name'],
                            script_name=script_name,
                            bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                            channel=channel,
                            username=kwargs['username'],
                            cmd=kwargs['command'],
                            auth='Approved',
                            status='Failed',
                            result='Invalid Source')

    else:
        slack_ops.send_msg(slack_client, channel, "`Invalid Syntax`",
                           kwargs['bot_name'])
        log_ops.log_msg(bot_name=kwargs['bot_name'],
                        script_name=script_name,
                        bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                        channel=channel,
                        username=kwargs['username'],
                        cmd=kwargs['command'],
                        auth='Approved',
                        status='Failed',
                        result='Invalid Syntax')
def main():
    text = "Device \"{}\"".format(source)
    status = 'Ok'
    result = 'Executed'

    if function == 'list':
        with fmcapi.FMC(host=host,
                        username=secrets['ansible_user'],
                        password=secrets['ansible_password'],
                        autodeploy=True) as fmc:
            obj1 = fmcapi.NetworkGroups(fmc=fmc, name=network_group)
            response = obj1.get()
            if 'id' not in response.keys():
                print('Failed Object Group \"{}\" does not exist'.format(
                    network_group))
            else:
                print('Object Group \"{}\" Found'.format(network_group))
                print(json.dumps(response))

    elif function == 'add':
        with fmcapi.FMC(host=host,
                        username=secrets['ansible_user'],
                        password=secrets['ansible_password'],
                        autodeploy=False) as fmc:
            obj1 = fmcapi.NetworkGroups(fmc=fmc, name=network_group)
            response = obj1.get()
            #print(json.dumps(obj1.format_data()))

            if 'id' not in response.keys():
                text += ' - Object Group \"{}\" not found'.format(
                    network_group)
                text = "`" + text + "`"

            else:
                present = search(response, ip_address)
                if not present:
                    obj1.unnamed_networks(action='add', value=ip_address)
                    print('Adding IP \"{}\" to object group \"{}\"'.format(
                        ip_address, network_group))
                    response = obj1.put()
                    #print(response)
                    if response:
                        print('Verifying add IP \"{}\" to object group \"{}\"'.
                              format(ip_address, network_group))
                        response = obj1.get()
                        present = search(response, ip_address)

                        if present:
                            text += ' - IP \"{}\" added to \"{}\"'.format(
                                ip_address, network_group)
                            text = "```" + text + "```"

                        else:
                            text += ' Failed to add IP \"{}\" to \"{}\"'.format(
                                ip_address, network_group)
                            text = "`" + text + "`"

                    else:
                        text += ' Failed to add IP \"{}\" to \"{}\"'.format(
                            ip_address, network_group)
                        text = "`" + text + "`"

                else:
                    text += ' - IP \"{}\" already exist in \"{}\"'.format(
                        ip_address, network_group)
                    text = "`" + text + "`"

    elif function == 'remove':
        with fmcapi.FMC(host=host,
                        username=secrets['ansible_user'],
                        password=secrets['ansible_password'],
                        autodeploy=True) as fmc:
            obj1 = fmcapi.NetworkGroups(fmc=fmc, name=network_group)
            response = obj1.get()
            #print(json.dumps(obj1.format_data()))

            if 'id' not in response.keys():
                text += ' - Object Group \"{}\" not found'.format(
                    network_group)
                text = "`" + text + "`"

            else:
                present = search(response, ip_address)

                if not present:
                    text += ' - IP \"{}\" not in \"{}\"'.format(
                        ip_address, network_group)
                    text = "`" + text + "`"

                else:
                    obj1.unnamed_networks(action='remove', value=ip_address)
                    print('Removing IP \"{}\" to object group \"{}\"'.format(
                        ip_address, network_group))
                    response = obj1.put()
                    #print(response)

                    if response:
                        #print(json.dumps(obj1.format_data()))
                        print(
                            'Verifying removal IP \"{}\" to object group \"{}\"'
                            .format(ip_address, network_group))
                        response = obj1.get()
                        present = search(response, ip_address)

                        if not present:
                            text += ' - IP \"{}\" removed from \"{}\"'.format(
                                ip_address, network_group)
                            text = "```" + text + "```"

                        else:
                            text += ' - Failed to remove IP \"{}\" from \"{}\"'.format(
                                ip_address, network_group)
                            text = "`" + text + "`"

                    else:
                        text += ' - Failed to remove IP \"{}\" from \"{}\"'.format(
                            ip_address, network_group)
                        text = "`" + text + "`"

    else:
        print('Invalid option')

    slack_ops.send_msg(slack_client, channel, text, bot_name)
    print("Text= " + text)
    log_ops.log_msg(bot_name=bot_name,
                    script_name=script_name,
                    bot_cmd_log_file=bot_cmd_log_file,
                    channel=channel,
                    username=username,
                    cmd=sys.argv[0],
                    auth='Approved',
                    status=status,
                    result=result,
                    task_id=task_id)
示例#24
0
def run(**kwargs):
    script_name = path.basename(__file__)
    command_splited = kwargs['command_splited']
    slack_client = kwargs['slack_client']
    channel = kwargs['channel']

    log_ops.log_msg(bot_name=kwargs['bot_name'],
                    script_name=script_name,
                    bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                    channel=channel,
                    username=kwargs['username'],
                    cmd=kwargs['command'],
                    auth='Approved',
                    status='Ok',
                    result='Starting')

    if len(command_splited) >= 3:
        sources = re.search(r'src=(.*)', command_splited[1])
        destinations = re.search(r'dst=(.*)', command_splited[2])

        if sources and destinations:
            list_sources, sources_count, list_destinations, destinations_count =\
                validate_hosts_ops.identify_elements(sources[1], destinations[1])

            total = sources_count * destinations_count

            if sources_count != 0 and destinations_count != 0:

                if total <= int(kwargs['multiple_src_dst']):

                    playbook = "net-mtrace-msg-slack.yml"

                    bot_playbooks_directory = kwargs['bot_playbooks_directory']
                    playbook_full_path = bot_playbooks_directory + playbook
                    ansible_common_inventory_full_path_name = kwargs[
                        'ansible_common_inventory_full_path_name']

                    json = True

                    if destinations_count == 1:

                        ansible_ops.ansible_cmd(
                            json,
                            playbook_full_path,
                            ansible_common_inventory_full_path_name,
                            channel,
                            slack_client,
                            kwargs['username'],
                            kwargs['bot_name'],
                            kwargs['bot_cmd_log_file'],
                            source=list(list_sources),
                            destination=list(list_destinations)[0])

                    else:
                        for item in list_destinations:
                            ansible_ops.ansible_cmd(
                                json,
                                playbook_full_path,
                                ansible_common_inventory_full_path_name,
                                channel,
                                slack_client,
                                kwargs['username'],
                                kwargs['bot_name'],
                                kwargs['bot_cmd_log_file'],
                                source=list(list_sources),
                                destination=item)

                else:
                    slack_ops.send_msg(
                        slack_client, channel,
                        "`Too many operations. Max {}`".format(
                            kwargs['multiple_src_dst']), kwargs['bot_name'])
                    log_ops.log_msg(
                        bot_name=kwargs['bot_name'],
                        script_name=script_name,
                        bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                        channel=channel,
                        username=kwargs['username'],
                        cmd=kwargs['command'],
                        auth='Approved',
                        status='Failed',
                        result='Too many operations. Max {}'.format(
                            kwargs['multiple_src_dst']))

            else:
                slack_ops.send_msg(slack_client, channel,
                                   "`Invalid sources or destinations`",
                                   kwargs['bot_name'])
                log_ops.log_msg(bot_name=kwargs['bot_name'],
                                script_name=script_name,
                                bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                                channel=channel,
                                username=kwargs['username'],
                                cmd=kwargs['command'],
                                auth='Approved',
                                status='Failed',
                                result='Invalid sources or destinations')

        else:
            slack_ops.send_msg(slack_client, channel, "`Invalid Devices`",
                               kwargs['bot_name'])
            log_ops.log_msg(bot_name=kwargs['bot_name'],
                            script_name=script_name,
                            bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                            channel=channel,
                            username=kwargs['username'],
                            cmd=kwargs['command'],
                            auth='Approved',
                            status='Failed',
                            result='Invalid Devices')

    else:
        slack_ops.send_msg(slack_client, channel, "`Invalid Syntax`",
                           kwargs['bot_name'])
        log_ops.log_msg(bot_name=kwargs['bot_name'],
                        script_name=script_name,
                        bot_cmd_log_file=kwargs['bot_cmd_log_file'],
                        channel=channel,
                        username=kwargs['username'],
                        cmd=kwargs['command'],
                        auth='Approved',
                        status='Failed',
                        result='Invalid Syntax')