Esempio n. 1
0
 def execute(self):
     logger.info("BackupJob")
     report = self.get_report("default", "default", self.kwargs['notify_handlers'],
                              report_title="Backup executions for host: " + self.context.node_name)
     with context.localdb:
         if self.kwargs['period'] not in module_db:
             module_db[self.kwargs['period']] = {"last_backup": -1}
     period_object = module_db[self.kwargs['period']]
     new_backup = period_object["last_backup"] + 1
     if new_backup >= self.kwargs['max_backups'] or new_backup < 0:
         new_backup = 0
     try:
         tarfilename = "backup_%s_%d.tag.gz" % (self.kwargs['period'], new_backup)
         tarfilepath = os.path.join(BACKUP_DIR, tarfilename)
         if os.path.isfile(tarfilepath):
             os.unlink(tarfilepath)
         return_code, output = run_command_ex1(['tar', '-zvcf', tarfilepath, DATA_DIR])
         output = output.decode(errors="replace")
         report.append_report_entry("Buckup executed", output)
     except:
         logger.error("Error while executing Backup")
         report.append_report_entry("Error while executing Backup.", "")
     finally:
         with context.localdb:
             period_object["last_backup"] = new_backup
     report.send_report()
Esempio n. 2
0
def crop(input_filepath, output_filepath, position):
    try:
        return_code, output = run_command_ex1(["convert", input_filepath, "-crop", position, output_filepath])
        if return_code != 0:
            raise Exception("Non-Zero return code: %d" % return_code)
    except:
        logging.error("Error while running crop command for (input_filepath=%s, output_filepath=%s, position=%s)",
                      input_filepath, output_filepath, position, exc_info=True)
Esempio n. 3
0
def get_active_window_id():
    try:
        return_code, output = run_command_ex1(
            ['xprop', '-root', '_NET_ACTIVE_WINDOW'])
        if return_code != 0:
            return None
        return output.decode(errors='replace').split()[4][:-1]
    except:
        logger.error('Error getting active window id', exc_info=True)
        return None
Esempio n. 4
0
def get_window_pid(window_id):
    try:
        return_code, output = run_command_ex1(
            ['xprop', '-id', window_id, '_NET_WM_PID'])
        if return_code != 0:
            return None
        return int(output.decode(errors='replace').split('=')[1].strip())
    except:
        logger.error('Error getting window pid', exc_info=True)
        return None
Esempio n. 5
0
def get_window_title(window_id):
    try:
        return_code, output = run_command_ex1(
            ['xprop', '-id', window_id, '_NET_WM_NAME'])
        if return_code != 0:
            return None
        return output.decode(errors='replace').split('=')[1].strip()[1:-1]
    except:
        logger.error('Error getting window title', exc_info=True)
        return None
Esempio n. 6
0
def identify(filepath):
    try:
        return_code, output = run_command_ex1(["identify", filepath])
        if return_code != 0:
            raise Exception("Non-Zero return code: %d" % return_code)
        output = output.decode(errors="replace")
        splits = output.split()
        return splits[1:4]
    except:
        logging.error("Error while running and parsing identify command for file: %s", filepath, exc_info=True)
Esempio n. 7
0
File: ps.py Progetto: xaled/easilyb
def get_process_cmd(pid):
    try:
        return_code, output = run_command_ex1(
            ['ps', '--no-headers', '-fw', '--pid',
             str(pid)])
        if return_code != 0:
            return None
        return output.decode(errors='replace').split()[7].strip()
    except:
        logger.error('Error getting process cmd', exc_info=True)
        return None
Esempio n. 8
0
def memfree():
    try:
        return_code, output = run_command_ex1(["free", "-b"])
        if return_code != 0:
            raise Exception("Non-Zero return code: %d" % return_code)
        splits = output.decode(errors="ignore").split('\n')[1].split()
        total, available = int(splits[1]), int(splits[6])
        used = total - available
        return total, used, available
    except:
        logging.error("Error while running free command", exc_info=True)
        raise
Esempio n. 9
0
def directory_usage(dir="./"):
    try:
        return_code, output = run_command_ex1(["du", "-b", "-d0", dir])
        if return_code != 0 and return_code != 1:
            raise Exception("Non-Zero return code: %d" % return_code)
        usage = int(output.decode(errors="ignore").split("\n")[-2].split()[0])
        return usage
    except:
        logging.error("Error while running du command on directory:%s",
                      dir,
                      exc_info=True)
        raise
Esempio n. 10
0
def get_mouse_location():
    try:
        return_code, output = run_command_ex1(
            ['xdotool', 'getmouselocation', '--shell'])
        if return_code != 0:
            return None
        return {
            k.split('=')[0]: k.split('=')[1]
            for k in output.decode(errors='replace').split('\n') if '=' in k
        }
    except:
        logger.error('Error getting mouse location', exc_info=True)
        return None
Esempio n. 11
0
def whois(query):
    from easilyb.commands import run_command_ex1
    from easilyb.validators import validate_ip, validate_domain, validate_charset
    if not validate_ip(query) and not validate_domain(query) and not validate_charset(query, TLD_CHARSET):
        raise ValueError("Query is not an IP address nor a domain")
    ret_code, output = run_command_ex1(["whois", query])
    output = output.decode(errors="replace")
    output_parsed = _parse_whois_output(output)
    org = _find_organization(output_parsed)
    if org == '': org = None
    netrange = _find_netrange(output_parsed)
    if netrange == '': netrange = None
    emails = _find_emails(output)
    return org, netrange, emails, output
Esempio n. 12
0
def disk_usage(disk="/"):
    try:
        return_code, output = run_command_ex1(["df", "-B1", disk])
        if return_code != 0:
            raise Exception("Non-Zero return code: %d" % return_code)
        total, used, available = output.decode(
            errors="ignore").split('\n')[1].split()[1:4]
        total, available = int(total), int(available)
        used = total - available
        return total, used, available
    except:
        logging.error("Error while running df command on drive:%s",
                      disk,
                      exc_info=True)
        raise
Esempio n. 13
0
    def execute(self):
        logger.info("executing EasyShellExecutionJob")
        report = self.get_report("easyshell", "easyshell_executions", self.kwargs['notify_handlers'],
                                 report_title="EasyShell Executions for host " + self.context.node_name)
        for command in self.kwargs['commands']:
            logger.debug("Excuting command :%s", command['name'])
            try:
                return_code, output = run_command_ex1(command['cmd_vector'])
                output = output.decode(errors="replace")
                report.append_report_entry("Command %s executed" % command['name'],
                                           "cmd: %s\n return_code: %s\n output:%s" %
                                           (' '.join(command['cmd_vector']), return_code, output))
            except:
                logger.error("Error while executing command: %s", command)
                report.append_report_entry("Command %s failed to execute" % command['name'],
                                           "cmd: %s" % (' '.join(command['cmd_vector'])))

        report.send_report()
Esempio n. 14
0
def cymru_whois(ip):
    from easilyb.commands import run_command_ex1
    from easilyb.validators import validate_ip
    if not validate_ip(ip):
        raise ValueError("Param is not an IP address")
    ret_code, output = run_command_ex1(["whois", "-h", "whois.cymru.com", "-v " + ip])
    keys = list()
    for l in output.decode(errors="replace").splitlines():
        if ip in l:
            values = [v.strip() for v in l.split('|')]
            ret = {keys[i]:values[i] for i in range(min(len(keys), len(values)))}
            for k in ['AS', 'BGP Prefix', 'AS Name']:
                if ret[k] == 'NA':
                    ret[k] = None
            if ret['CC'] == '':
                ret['CC'] = None
            return ret
        elif "BGP Prefix" in l:
            keys = [k.strip() for k in l.split('|')]
    return None
Esempio n. 15
0
def whois_ex1(query):
    from easilyb.commands import run_command_ex1
    from easilyb.validators import validate_ip, validate_domain, validate_charset
    if not validate_ip(query) and not validate_domain(query) and not validate_charset(query, TLD_CHARSET):
        raise ValueError("Query is not an IP address nor a domain")
    ret_code, output = run_command_ex1(["whois", query])
    output = output.decode(errors="replace")
    output_parsed = _parse_whois_output(output)
    org = _find_organization(output_parsed)
    if org == '': org = None
    netrange = _find_netrange(output_parsed)
    if netrange == '': netrange = None
    emails = _find_emails(output)
    netname = _find_keys_value(output_parsed, NETNAME_KEYS)
    return {
        'org': org,
        'netrange': netrange,
        'netname': netname,
        'emails': emails,
        'output': output,
        # 'whois_parsed': output_parsed
    }
Esempio n. 16
0
def button_view(button_name):
    button = _get_button(button_name)
    return_code, output = run_command_ex1(button['cmd_vector'])
    output = output.decode(errors="replace")
    return render_template("easy_shell/button_view.html", title="EasyShell", button=button_name,
                           output=output, return_code=return_code)