def on_init(protocol, args):
    """ server side """
    from AVMaster import vm_manager

    vm, mq = protocol.vm, protocol.mq
    cmd = "c:\\python27\\python.exe"

    if args:
        redis = args
    else:
        redis = config.redis

    arg = [
        "C:\\AVTest\\AVAgent\\av_agent.py", "-m", vm, "-s", mq.session, "-d",
        redis
    ]
    ret = vm_manager.execute(vm, "executeCmd", cmd, arg, 40, True, True)

    #logging.debug("execution: %s" % ret)
    python = None

    for i in range(5):
        time.sleep(10)
        processes = vm_manager.execute(vm, "list_processes")
        if not processes:
            logging.debug("%s: null list_processes" % vm)
            continue
        python = [p for p in processes if "python" in p['cmd_line']]
        logging.debug("processes python: %s" % python)
        if python:
            return True

    if not python:
        logging.error("Error executing command av_agent on %s" % vm)
    return False
Exemple #2
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"
    tick = 15
    if args:
        assert isinstance(args, int), "you must specify an int for timeout."

        timeout = args
        off = False


        logging.debug("%s, shutting down with timeout %s." % (vm,timeout))

        vm_manager.execute(vm, "executeCmd","C:/Windows/System32/shutdown.exe",["/s", "/t", "30"], timeout, False, True)

        for i in range(0, timeout, tick):
            sleep(tick)
            if vm_manager.execute(vm, "is_powered_off"):
                return True, "Stopped VM"


    logging.info("Forcing shutdown")
    ret = vm_manager.execute(vm, "shutdown")

    logging.debug("%s, shutdown returns: %s" % (vm, ret))

    for i in range(10):
        if vm_manager.execute(vm, "is_powered_off"):
            return True, "Stopped VM"
        sleep(tick)

    return False, "Cannot stop VM"
Exemple #3
0
def on_init(protocol, args):
    """ server side """
    from AVMaster import vm_manager

    vm, mq = protocol.vm, protocol.mq
    cmd = "c:\\python27\\python.exe"

    if args:
        redis = args
    else:
        redis = config.redis

    arg = ["C:\\AVTest\\AVAgent\\av_agent.py", "-m", vm, "-s", mq.session, "-d", redis]
    ret = vm_manager.execute(vm, "executeCmd", cmd, arg, 40, True, True)

    #logging.debug("execution: %s" % ret)
    python = None

    for i in range(5):
        time.sleep(10)
        processes = vm_manager.execute(vm, "list_processes")
        if not processes:
            logging.debug("%s: null list_processes" % vm)
            continue
        python = [ p for p in processes if "python" in p['cmd_line'] ]
        logging.debug("processes python: %s" % python)
        if python:
            return True

    if not python:
        logging.error("Error executing command av_agent on %s" % vm)
    return False
Exemple #4
0
def on_answer(vm, success, answer):
    from AVMaster import vm_manager

    #assert command.context, "Null context"

    logging.debug("CROP answer: %s|%s" % (success, answer))
    # answer = [1,5,7]

    if answer and isinstance(answer, list):

        logging.warn("We have to PULL images: %s" % answer)
        dir = "%s/crop" % logger.logdir

        for iter in answer:
            try:
                src = "%s/%s.png" % (config.basedir_crop, iter)
                #name = src.split('/')[-1]
                dst_dir = "%s/%s" % (dir, vm)
                if not os.path.exists(dst_dir):
                    os.makedirs(dst_dir)
                dst = "%s/%s.png" % (dst_dir, iter)

                src = src.replace('/', '\\')
                logging.debug("PULL: %s -> %s" % (src, dst))
                vm_manager.execute(vm, "copyFileFromGuest", src, dst)
            except:
                logging.exception("Cannot get image %s" % src)
Exemple #5
0
def execute(vm, protocol, args):
    from AVMaster import vm_manager

    """ server side """
    #logging.debug("    CS Execute")
    assert vm, "null vm"


    for i in range (30):
        if vm_manager.execute(vm, "is_powered_off"):
            return True, "%s VM is stopped" % vm
        else:
            logging.debug("%s, not yet powered off" % vm)
            time.sleep(30)

    ret = vm_manager.execute(vm, "shutdown")
    if not ret:
        return False, "Not Stopped VM %s" % ret

    for i in range (10):
        if vm_manager.execute(vm, "is_powered_off"):
            return True, "%s VM is stopped" % vm
        else:
            logging.debug("%s, not yet powered off" % vm)
            time.sleep(30)

    return False, "%s VM isn't stopped" % vm
def execute(vm, protocol, args):
    from AVMaster import vm_manager
    """ server side """
    #logging.debug("    CS Execute")
    assert vm, "null vm"

    for i in range(30):
        if vm_manager.execute(vm, "is_powered_off"):
            return True, "%s VM is stopped" % vm
        else:
            logging.debug("%s, not yet powered off" % vm)
            time.sleep(30)

    ret = vm_manager.execute(vm, "shutdown")
    if not ret:
        return False, "Not Stopped VM %s" % ret

    for i in range(10):
        if vm_manager.execute(vm, "is_powered_off"):
            return True, "%s VM is stopped" % vm
        else:
            logging.debug("%s, not yet powered off" % vm)
            time.sleep(30)

    return False, "%s VM isn't stopped" % vm
Exemple #7
0
def test_execute():
#    vmm = VMManager()
    logging.info( "TEST VMManager")
    #vms=["zenovm", "noav"]
    vms = ["noav"]
    vm = "noav"
    vm_manager.execute(vm, "executeCmd", "c:/python27/python.exe", [], 40, True, False)
Exemple #8
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"
    mq = protocol.mq

    timeout = 9  #9 = 90 sec; 30 = 300 sec
    if args:
        timeout = args / 10

    mq.reset_connection(vm)

    cmd = "/Windows/System32/logoff.exe"
    ret = vm_manager.execute(vm, "executeCmd", cmd, [], 10, True, True)
    logging.debug("logoff ret: %s" % ret)

    started = False
    if ret:
        for i in range(6):
            if vm_manager.execute(vm, "is_powered_on"):
                logging.debug("%s: powered on" % vm)
                for i in range(timeout):
                    if mq.check_connection(vm):
                        logging.debug("got connection from %s" % vm)
                        return True, "Login VM"
                    sleep(10)

                logging.debug("%s: try to reboot" % vm)
                ret = vm_manager.execute(vm, "reboot")
            else:
                sleep(10)

    return False, "Cannot relogin"
Exemple #9
0
def on_answer(vm, success, answer):
    from AVMaster import vm_manager

    #assert command.context, "Null context"

    logging.debug("CROP answer: %s|%s" % (success, answer))
    # answer = [1,5,7]

    if answer and isinstance(answer, list):

        logging.warn("We have to PULL images: %s" % answer)
        dir = "%s/crop" % logger.logdir

        for iter in answer:
            try:
                src = "%s/%s.png" % (config.basedir_crop, iter)
                #name = src.split('/')[-1]
                dst_dir = "%s/%s" %(dir, vm)
                if not os.path.exists(dst_dir):
                    os.makedirs(dst_dir)
                dst = "%s/%s.png" % (dst_dir, iter)

                src = src.replace('/','\\')
                logging.debug("PULL: %s -> %s" % (src, dst))
                vm_manager.execute(vm, "copyFileFromGuest", src ,dst)
            except:
                logging.exception("Cannot get image %s" % src)
Exemple #10
0
def get_status(vm):
    from AVMaster import vm_manager
    # [19/12/13 11:09:23] Seppia: pid=1432, owner=WIN7-NOAV\avtest, cmd=vmtoolsd.exe
    # pid=1776, owner=NT AUTHORITY\SYSTEM, cmd=vmtoolsd.exe
    # pid=712, owner=NT AUTHORITY\SYSTEM, cmd=TrustedInstaller.exe
    # pid=1376, owner=WIN7-NOAV\avtest, cmd=wuauclt.exe
    # pid=1408, owner=WIN7-NOAV\avtest, cmd=wuauclt.exe
    # [19/12/13 11:09:53] Seppia: questa e' una vm che sta facendo aggiornamento, con i vmwaretools partiti (user logged on)

    user_logged = False
    vm_tools = False
    install = False
    try:
        processes = vm_manager.execute(vm, "list_processes")
    except:
        logging.exception("cannot get processes")
        #processes = vm_manager.execute(vm, "listProcesses");
        #logging.debug("listProcesses: %s" % processes)

    if not processes:
        try:
            sleep(60)
            logging.debug("trying listProcesses")
            procs = vm_manager.execute(vm, "listProcesses")
            if config.verbose:
                logging.debug("listProcesses: %s" % procs)
            processes = helper.convert_processes(procs)
        except:
            logging.exception("listProcesses")

    if not processes:
        return "NOT-STARTED"

    try:
        if config.verbose:
            logging.debug("%s, list_processes: %s" %
                          (vm, [(p["name"], p["owner"]) for p in processes]))

        for process in processes:
            if process["owner"].endswith("avtest"):
                user_logged = True
                if process["name"] == "vmtoolsd.exe":
                    # owner=WIN7-NOAV\avtest, cmd=VMwareTray.exe
                    vm_tools = True
            if process["name"] == "wuauclt.exe" or process[
                    "name"] == "TrustedInstaller.exe":
                install = True
        # explorer, vmware solo se logged in
    except:
        logging.exception("error")

    if vm_tools:
        return "LOGGED-IN"
    if install:
        return "INSTALL"
    if not user_logged:
        return "LOGGED-OFF"
    else:
        return "NO-VM-TOOLS"
def test_execute():
    #    vmm = VMManager()
    logging.info("TEST VMManager")
    #vms=["zenovm", "noav"]
    vms = ["noav"]
    vm = "noav"
    vm_manager.execute(vm, "executeCmd", "c:/python27/python.exe", [], 40,
                       True, False)
Exemple #12
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"
    mq = protocol.mq

    check_avagent = (args == "AV_AGENT")

    mq.reset_connection(vm)
    ret = vm_manager.execute(vm, "startup")
    started = False
    if not ret:
        return False, "Not Started VM"

    max_install = 10
    max_tries = 10

    for i in range(3):
        sleep(10)
        if vm_manager.execute(vm, "is_powered_on"):
            for i in range(max_tries):
                if mq.check_connection(vm):
                    logging.debug("got connection from %s" % vm)
                    return True, "Started VM"

                for i in range(max_install):
                    status = get_status(vm)
                    logging.debug("%s, got status: %s" % (vm, status))

                    if status == "INSTALL":
                        logging.debug("waiting for the install to finish: %s/%s" % (i, max_install))
                        sleep(60)
                    else:
                        break

                if status == "LOGGED-IN":
                    logging.debug("%s, executing ipconfig, time: %s/%s" % (vm, i, max_tries))
                    started = vm_manager.execute(vm, "executeCmd", "c:\\windows\\system32\\ipconfig.exe") == 0
                    logging.debug("%s, executed ipconfig, ret: %s" % (vm, started))

                if started and not check_avagent:
                    return True, "Started VM"
                else:
                    sleep(20)

            if not started:
                logging.debug("%s: reboot requested" % vm)
                vm_manager.execute(vm, "reboot")
                sleep(60)
                continue

            return False, "Not started VM"
        else:
            logging.debug("%s: not yet powered" % vm)

    return False, "Error Occurred: Timeout while starting VM"
Exemple #13
0
def get_status(vm):
    from AVMaster import vm_manager
    # [19/12/13 11:09:23] Seppia: pid=1432, owner=WIN7-NOAV\avtest, cmd=vmtoolsd.exe
    # pid=1776, owner=NT AUTHORITY\SYSTEM, cmd=vmtoolsd.exe
    # pid=712, owner=NT AUTHORITY\SYSTEM, cmd=TrustedInstaller.exe
    # pid=1376, owner=WIN7-NOAV\avtest, cmd=wuauclt.exe
    # pid=1408, owner=WIN7-NOAV\avtest, cmd=wuauclt.exe
    # [19/12/13 11:09:53] Seppia: questa e' una vm che sta facendo aggiornamento, con i vmwaretools partiti (user logged on)

    user_logged = False
    vm_tools = False
    install = False
    try:
        processes = vm_manager.execute(vm, "list_processes");
    except:
        logging.exception("cannot get processes")
        #processes = vm_manager.execute(vm, "listProcesses");
        #logging.debug("listProcesses: %s" % processes)

    if not processes:
        try:
            sleep(60)
            logging.debug("trying listProcesses")
            procs = vm_manager.execute(vm, "listProcesses");
            if config.verbose:
                logging.debug("listProcesses: %s" % procs)
            processes = helper.convert_processes(procs)
        except:
            logging.exception("listProcesses")

    if not processes:
        return "NOT-STARTED"

    try:
        if config.verbose:
            logging.debug("%s, list_processes: %s" % (vm, [ (p["name"],p["owner"]) for p in processes] ))

        for process in processes:
            if process["owner"].endswith("avtest"):
                user_logged = True
                if process["name"] == "vmtoolsd.exe":
                    # owner=WIN7-NOAV\avtest, cmd=VMwareTray.exe
                    vm_tools = True
            if process["name"] == "wuauclt.exe" or process["name"] == "TrustedInstaller.exe":
                install = True
        # explorer, vmware solo se logged in
    except:
        logging.exception("error")

    if vm_tools:
        return "LOGGED-IN"
    if install:
        return "INSTALL"
    if not user_logged:
        return "LOGGED-OFF"
    else:
        return "NO-VM-TOOLS"
Exemple #14
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    #logging.debug("    CS Execute REVERT")
    assert vm, "null vm"

    # TODO: check
    vm_manager.execute(vm, "revert_last_snapshot")
    return True, "Reverted VM"
def execute(vm, protocol, args):
    """ server side """

    from AVMaster import vm_manager

    logging.debug("    CS Execute REFRESH SNAPSHOT")
    assert vm, "null vm"

    # TODO: check
    vm_manager.execute(vm, "refreshSnapshot")
    return True, "Snapshot refreshed for VM"
Exemple #16
0
def execute(vm, protocol, args):
    from AVMaster import vm_manager

    """ server side """
    clean = True # VM IS NOT INFECTED!! TEST CAN CONTINUE!!!

    #logging.debug("    CS Execute")
    assert vm, "null vm"

    invert = "STOP_IF_CLEAN" in args if args else False

    #blacklist = ['BTHSAmpPalService','CyCpIo','CyHidWin','iSCTsysTray','quickset']

    dirs = ['C:Users/avtest/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup',
            'C:/Documents and Settings/avtest/Start Menu/Programs/Startup']


    names = build.names[:]
    names.remove("agent")

    for d in dirs:
        out = vm_manager.execute(vm, "listDirectoryInGuest", d)
        #logging.debug("listDirectoryInGuest: %s" % out)

        for b in names:
            if b in out:
                logging.info("%s, found %s in %s" % (vm, b, d))
                clean = False
                break

    ret = xor(clean is True, invert)
    if clean is True:
        return ret, "VM is not infected"
    else:
        return ret, "VM is INFECTED"
Exemple #17
0
def execute(vm, protocol, args):
    from AVMaster import vm_manager
    """ server side """
    clean = True  # VM IS NOT INFECTED!! TEST CAN CONTINUE!!!

    #logging.debug("    CS Execute")
    assert vm, "null vm"

    invert = "STOP_IF_CLEAN" in args if args else False

    #blacklist = ['BTHSAmpPalService','CyCpIo','CyHidWin','iSCTsysTray','quickset']

    dirs = [
        'C:Users/avtest/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup',
        'C:/Documents and Settings/avtest/Start Menu/Programs/Startup'
    ]

    names = build.names[:]
    names.remove("agent")

    for d in dirs:
        out = vm_manager.execute(vm, "listDirectoryInGuest", d)
        #logging.debug("listDirectoryInGuest: %s" % out)

        for b in names:
            if b in out:
                logging.info("%s, found %s in %s" % (vm, b, d))
                clean = False
                break

    ret = xor(clean is True, invert)
    if clean is True:
        return ret, "VM is not infected"
    else:
        return ret, "VM is INFECTED"
Exemple #18
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"
    assert len(args) == 3 and isinstance(
        args, list), "PULL expects a list of 3 elements"

    #TODO pull files from vm
    src_files, src_dir, dst_dir = args
    assert isinstance(src_files, list), "PULL expects a list of src files"

    if not (src_dir.startswith("\\") or src_dir.startswith("/")
            or src_dir[1] == ':'):
        src_dir = "%s/%s" % (config.basedir_av, src_dir)
        logging.debug("Added basedir to src_dir: %s" % src_dir)

    memo = []
    for src_file in src_files:
        print src_file
        try:
            d, f = src_file.split("\\")
        except ValueError:
            d = ""
            f = src_file

        src = "%s\\%s\\%s" % (src_dir, d, f)
        src = src.replace('/', '\\')

        if d == "":
            dst = "%s/%s/%s" % (dst_dir, vm, f)
        else:
            dst = "%s/%s/%s/%s" % (dst_dir, vm, d, f)

        rdir = "%s/%s/%s" % (dst_dir, vm, d)
        if not rdir in memo:
            if not os.path.exists(rdir):
                logging.debug("mkdir %s " % (rdir))
                os.mkdir(rdir)
                memo.append(rdir)

        logging.debug("%s copy %s -> %s" % (vm, src, dst))
        vm_manager.execute(vm, "copyFileFromGuest", src, dst)

    return True, "Files copied from VM"
def execute(vm, protocol, args):
    from AVMaster import vm_manager
    """ server side """
    #logging.debug("    CS Execute")
    assert vm, "null vm"

    if vm_manager.execute(vm, "is_powered_off"):
        return True, "%s VM is stopped" % vm
    return False, "%s VM isn't stopped" % vm
Exemple #20
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"
    assert len(args) == 3 and isinstance(args, list), "PULL expects a list of 3 elements"

    #TODO pull files from vm
    src_files, src_dir, dst_dir = args
    assert isinstance(src_files, list), "PULL expects a list of src files"

    if not (src_dir.startswith("\\") or src_dir.startswith("/") or src_dir[1]==':'):
        src_dir = "%s/%s" % (config.basedir_av, src_dir)
        logging.debug("Added basedir to src_dir: %s" % src_dir)

    memo = []
    for src_file in src_files:
        print src_file
        try:
            d, f = src_file.split("\\")
        except ValueError:
            d = ""
            f = src_file

        src = "%s\\%s\\%s" % (src_dir, d, f)
        src = src.replace('/','\\')

        if d == "":
            dst = "%s/%s/%s" % (dst_dir, vm, f)
        else:
            dst = "%s/%s/%s/%s" % (dst_dir, vm, d, f)

        rdir = "%s/%s/%s" % (dst_dir, vm, d)
        if not rdir in memo:
            if not os.path.exists(rdir):
                logging.debug("mkdir %s " % (rdir))
                os.mkdir(rdir)
                memo.append(rdir)

        logging.debug("%s copy %s -> %s" % (vm, src, dst))
        vm_manager.execute(vm, "copyFileFromGuest", src, dst)

    return True, "Files copied from VM"
Exemple #21
0
def execute(vm, protocol, args):
    from AVMaster import vm_manager

    """ server side """
    # logging.debug("    CS Execute")
    assert vm, "null vm"

    if vm_manager.execute(vm, "is_powered_off"):
        return True, "%s VM is stopped" % vm
    return False, "%s VM isn't stopped" % vm
Exemple #22
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"
    mq = protocol.mq

    timeout = 9  #9 = 90 sec; 30 = 300 sec
    if args:
        timeout = args / 10

    mq.reset_connection(vm)

    cmd = "/Windows/System32/logoff.exe"
    ret = vm_manager.execute(vm, "executeCmd", cmd, [] , 10, True, True)
    logging.debug("logoff ret: %s" % ret)

    started = False
    if ret:
        for i in range(6):
            if vm_manager.execute(vm, "is_powered_on"):
                logging.debug("%s: powered on" % vm)
                for i in range(timeout):
                    if mq.check_connection(vm):
                        logging.debug("got connection from %s" % vm)
                        return True, "Login VM"
                    sleep(10)

                logging.debug("%s: try to reboot" % vm)
                ret = vm_manager.execute(vm, "reboot")
            else:
                sleep(10)


    return False, "Cannot relogin"
Exemple #23
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"

    if isinstance(args, list):
        cmd_args = tuple(args)
    else:
        cmd_args = (args,)
    ret = vm_manager.execute(vm, "executeCmd", *cmd_args)

    logging.debug("ret: %s" % ret)
    if ret == 0:
        return True, "Command %s executed" % args
    else:
        return True, "Command %s not executed" % args
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"

    if isinstance(args, list):
        cmd_args = tuple(args)
    else:
        cmd_args = (args, )
    ret = vm_manager.execute(vm, "executeCmd", *cmd_args)

    logging.debug("ret: %s" % ret)
    if ret == 0:
        return True, "Command %s executed" % args
    else:
        return True, "Command %s not executed" % args
def execute(vm, protocol, dirname):
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"
    #assert len(args) == 1 and isinstance(args, str), "Argument must be a string."
    assert isinstance(dirname, str), "Argument must be single."

    if not dirname.startswith("/") and not dirname.startswith("\\"):
        dirname = "%s/%s" % (config.basedir_av, dirname)
    dirname = dirname.replace('/', '\\')

    logging.debug("Deleting %s from %s" % (dirname, vm))
    r = vm_manager.execute(vm, "deleteDirectoryInGuest", dirname)

    return True, "%s deleted" % dirname

    # TODO: return True only if directory is deleted for real
    """
Exemple #26
0
def execute(vm, protocol, dirname):
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"
    #assert len(args) == 1 and isinstance(args, str), "Argument must be a string."
    assert isinstance(dirname, str), "Argument must be single."

    if not dirname.startswith("/") and not dirname.startswith("\\"):
        dirname = "%s/%s" %(config.basedir_av, dirname)
    dirname = dirname.replace('/','\\')

    logging.debug("Deleting %s from %s" % (dirname, vm))
    r = vm_manager.execute(vm, "deleteDirectoryInGuest", dirname)

    return True, "%s deleted" % dirname

    # TODO: return True only if directory is deleted for real

    """
Exemple #27
0
def execute(vm, protocol, img_path):
    """ server side """
    # TODO: add Proc name
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"

    basedir = "%s/screenshots" % logger.logdir

    if not img_path:
        if not os.path.exists(basedir):
            os.makedirs(basedir)
        img_path = "%s/%s.%s.png" % (basedir, vm, int(time.time()))

    ret = vm_manager.execute(vm, "takeScreenshot", img_path)
    if ret is True:
        #blob = open(img_path).read()
        return ret, img_path
    else:
        return ret, "Screenshot not saved"
Exemple #28
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    logging.debug("    CS PUSH: %s" % str(args))
    assert vm, "null self.vm"
    assert isinstance(args, list)

    if isinstance(args[0], list):
        src_files, src_dir, dst_dir = args
    elif isinstance(args[0], basestring):
        src_files, src_dir, dst_dir = args, config.basedir_server, config.basedir_av
    else:
        raise RuntimeError("wrong arguments")

    assert isinstance(src_files, list), "PUSH expects a list of src files"

    all_src = []
    relative_parents = set()

    """ look if i need all files in one directory """
    for src_file in src_files:
        g = glob.glob(os.path.join(src_dir, src_file))
        if not g:
            logging.warn("Empty glob")
        # if you arrive here, then you already found the file on the filesystem.
        # typically the file have a relative path
        for f in g:
            # s is the relative file, expanded by glob
            s = f.replace("%s/" % src_dir, "")
            all_src.append(s)
            # logging.debug("file completo f: %s, file relativo s: %s" % (f,s))

            # logging.debug("Check if exists file %s" % f)
            assert os.path.exists(f), "%s %s" % (f, os.getcwd())

            # inserito da Marco
            # logging.debug("Check if exists file %s" % os.path.join(src_dir, s))
            assert os.path.exists(os.path.join(src_dir, s)), "%s %s" % (s, os.getcwd())

            # add all the parents to the relative_parents set, to avoid repetitions
            p = os.path.split(s)[0]
            while p and p != src_dir:
                relative_parents.add(p)
                # print("1_relative parents")
                p = os.path.split(p)[0]

    # sorts the parents by length, so that parent is always before its sons

    relative_parents.add("./")
    parents = list(relative_parents)
    parents.sort(lambda x, y: len(x) - len(y))
    logging.debug("parents: %s" % parents)

    ntdir = lambda x: x.replace("/", "\\")

    print(parents)

    for r in parents:
        # print(dst_dir)
        rdir = ntdir(os.path.join(dst_dir, r))
        # print("2_crea cartelle %s" % rdir)
        logging.debug("mkdir %s " % (rdir))
        vm_manager.execute(vm, "mkdirInGuest", rdir)

    """ then upload parsed files """
    logging.debug("All files to copy are:\n%s" % src_files)
    if not all_src:
        return False, "Empty file list"

    for src_file in all_src:
        # print("3_processa file")
        src = os.path.join(src_dir, src_file)
        dst = ntdir(os.path.join(dst_dir, src_file))

        # logging.debug("Check if exists file %s" % src)

        if not os.path.exists(src):
            return False, "Not existent file: %s" % src
        else:
            pass
            # logging.debug("file exists")

        logging.debug("%s copy %s -> %s" % (vm, src, dst))
        r = vm_manager.execute(vm, "copyFileToGuest", src, dst)

        if r > 0:
            return False, "Cant Copy %s on VM" % src_file

    return True, "Files copied on VM"
Exemple #29
0
def on_answer(vm, success, answer):
    """ server side """
    from AVMaster import vm_manager
    cmd = "/windows/system32/logout.exe"
    arg = []
    ret = vm_manager.execute(vm, "executeCmd", cmd, arg, 40, True, True)
def execute(vm, protocol, inst_args):
    from AVMaster import vm_manager
    """ client side, returns (bool,*) """
    logging.debug("    INSTALL_AGENT")
    mq = protocol.mq

    assert vm, "null vm"
    assert command.context is not None

    if inst_args:
        redis = inst_args
    else:
        redis = config.redis

    cmd = "rmdir /s /q C:\\AVTest\\running \r\n"\
          "cd C:\\AVTest\\AVAgent\r\n" \
          "c:\\python27\\python.exe"
    arg = [
        "C:\\AVTest\\AVAgent\\av_agent.py", "-m", vm, "-s", mq.session, "-d",
        redis
    ]
    start_bat = "%s %s\r\n" % (cmd, " ".join(arg))

    agent_bat = "start /min C:\\AVTest\\AVAgent\\start.bat ^& exit\r\n"

    fd, filename = tempfile.mkstemp(".bat")
    logging.debug("opening file %s with fd: %s" % (filename, fd))
    os.write(fd, agent_bat)
    os.close(fd)

    startup_dir_7 = 'C:/Users/avtest/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup'
    startup_dir_XP = 'C:/Documents and Settings/avtest/Start Menu/Programs/Startup'

    if vm.endswith("32"):
        startup_dir = startup_dir_XP
    else:
        startup_dir = startup_dir_7

    remote_name = "%s/av_agent.bat" % startup_dir
    remote_name = remote_name.replace("/", "\\")
    r = vm_manager.execute(vm, "copyFileToGuest", filename, remote_name)
    os.remove(filename)

    fd, filename = tempfile.mkstemp(".bat")
    logging.debug("opening file %s with fd: %s" % (filename, fd))
    os.write(fd, start_bat)
    os.close(fd)

    remote_name = "C:\\AVTest\\AVAgent\\start.bat"
    r = vm_manager.execute(vm, "copyFileToGuest", filename, remote_name)
    os.remove(filename)

    dirname = "%s/avagent/running" % config.basedir_av
    r = vm_manager.execute(vm, "deleteDirectoryInGuest", dirname)

    dirname = "%s/logs" % config.basedir_av
    r = vm_manager.execute(vm, "deleteDirectoryInGuest", dirname)

    if r > 0:
        return False, "Cant Copy %s on VM" % filename

    else:
        return True, "File copied"
Exemple #31
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    logging.debug("    CS PUSHZIP: %s" % str(args))
    assert vm, "null self.vm"
    assert isinstance(args, list)

    if isinstance(args[0], basestring):
        src_files, src_dir, dst_dir = args, config.basedir_server, config.basedir_av
    else:
        raise RuntimeError("wrong arguments")

    assert isinstance(src_files, list), "PUSHZIP expects a list of src files"

    all_src = []
    """ look if i need all files in one directory """
    for src_file in src_files:
        g = glob.glob(os.path.join(src_dir, src_file))
        if not g:
            logging.warn("Empty glob")
        # if you arrive here, then you already found the file on the filesystem.
        # typically the file have a relative path
        for f in g:
            # s is the relative file, expanded by glob
            s = f.replace("%s/" % src_dir, "")
            all_src.append(s)

            #logging.debug("Check if exists file %s" % f)
            assert os.path.exists(f), "%s %s" % (f, os.getcwd())

            #inserito da Marco
            #logging.debug("Check if exists file %s" % os.path.join(src_dir, s))
            assert os.path.exists(os.path.join(src_dir,
                                               s)), "%s %s" % (s, os.getcwd())

    ntdir = lambda x: x.replace("/", "\\")

    print 'creating archive'
    d = tempfile.mkdtemp()
    zfname = d + '/zipfile_write.zip'
    zf = zipfile.ZipFile(zfname, mode='w')
    pwd = config.basedir_server
    """ then upload parsed files """
    logging.debug("All files to copy are:\n%s" % src_files)
    if not all_src:
        return False, "Empty file list"

    for src_file in all_src:
        #print("3_processa file")
        src = os.path.join(src_dir, src_file)

        #logging.debug("Check if exists file %s" % src)
        if not os.path.exists(src):
            return False, "Not existent file: %s" % src
        else:
            pass

        logging.debug("%s adding %s -> %s" % (vm, src_file, src))
        zf.write(src_file)

    zf.close()
    #zip file is ready

    vm_manager.execute(vm, "mkdirInGuest", ntdir(dst_dir))

    # copy unzip (it should be already in AVAgent/assets...)
    unzipexe = "assets/unzip.exe"
    dst = ntdir(os.path.join(dst_dir, "unzip.exe"))

    logging.debug("Copy unzip: %s -> %s" % (unzipexe, dst))
    vm_manager.execute(vm, "copyFileToGuest", unzipexe, dst)

    tmpzip = "tmp.zip"
    dst = ntdir(os.path.join(dst_dir, tmpzip))
    logging.debug("Copy zip: %s -> %s" % (zfname, dst))
    vm_manager.execute(vm, "copyFileToGuest", zfname, dst)

    logging.debug("Executing unzip on %s" % dst)
    unzipargs = ("/AVTest/unzip.exe", ["-o", "-d", "c:\\avtest",
                                       dst], 40, True, True)
    ret = vm_manager.execute(vm, "executeCmd", *unzipargs)
    logging.debug("ret: %s" % ret)

    logging.debug("Removing zip: %s" % d)
    shutil.rmtree(d)

    return True, "Files copied on VM"
Exemple #32
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    logging.debug("    CS PUSHZIP: %s" % str(args))
    assert vm, "null self.vm"
    assert isinstance(args, list)

    if  isinstance(args[0], basestring):
        src_files, src_dir, dst_dir = args, config.basedir_server, config.basedir_av
    else:
        raise RuntimeError("wrong arguments")

    assert isinstance(src_files, list), "PUSHZIP expects a list of src files"

    all_src = []

    """ look if i need all files in one directory """
    for src_file in src_files:
        g = glob.glob(os.path.join(src_dir, src_file))
        if not g:
            logging.warn("Empty glob")
        # if you arrive here, then you already found the file on the filesystem.
        # typically the file have a relative path
        for f in g:
            # s is the relative file, expanded by glob
            s = f.replace("%s/" % src_dir, "")
            all_src.append(s)

            #logging.debug("Check if exists file %s" % f)
            assert os.path.exists(f), "%s %s" % (f, os.getcwd())

            #inserito da Marco
            #logging.debug("Check if exists file %s" % os.path.join(src_dir, s))
            assert os.path.exists(os.path.join(src_dir, s)), "%s %s" % (s, os.getcwd())

    ntdir = lambda x: x.replace("/", "\\")

    print 'creating archive'
    d = tempfile.mkdtemp()
    zfname = d + '/zipfile_write.zip'
    zf = zipfile.ZipFile(zfname, mode='w')
    pwd = config.basedir_server

    """ then upload parsed files """
    logging.debug("All files to copy are:\n%s" % src_files)
    if not all_src:
        return False, "Empty file list"

    for src_file in all_src:
        #print("3_processa file")
        src = os.path.join(src_dir, src_file)

        #logging.debug("Check if exists file %s" % src)
        if not os.path.exists(src):
            return False, "Not existent file: %s" % src
        else:
            pass

        logging.debug("%s adding %s -> %s" % (vm, src_file, src))
        zf.write(src_file)

    zf.close()
    #zip file is ready

    vm_manager.execute(vm, "mkdirInGuest", ntdir(dst_dir))

    # copy unzip (it should be already in AVAgent/assets...)
    unzipexe = "assets/unzip.exe"
    dst = ntdir(os.path.join(dst_dir, "unzip.exe"))

    logging.debug("Copy unzip: %s -> %s" % (unzipexe, dst) )
    vm_manager.execute(vm, "copyFileToGuest", unzipexe, dst)

    tmpzip = "tmp.zip"
    dst = ntdir(os.path.join(dst_dir, tmpzip))
    logging.debug("Copy zip: %s -> %s" % (zfname, dst) )
    vm_manager.execute(vm, "copyFileToGuest", zfname, dst)

    logging.debug("Executing unzip on %s" % dst)
    unzipargs= ( "/AVTest/unzip.exe", [ "-o", "-d", "c:\\avtest", dst], 40, True, True )
    ret = vm_manager.execute(vm, "executeCmd", *unzipargs )
    logging.debug("ret: %s" % ret)

    logging.debug("Removing zip: %s" % d)
    shutil.rmtree(d)

    return True, "Files copied on VM"
Exemple #33
0
def execute(vm, protocol, inst_args):
    from AVMaster import vm_manager

    """ client side, returns (bool,*) """
    logging.debug("    INSTALL_AGENT" )
    mq = protocol.mq

    assert vm, "null vm"
    assert command.context is not None

    if inst_args:
        redis = inst_args
    else:
        redis = config.redis

    cmd = "rmdir /s /q C:\\AVTest\\running \r\n"\
          "cd C:\\AVTest\\AVAgent\r\n" \
          "c:\\python27\\python.exe"
    arg = ["C:\\AVTest\\AVAgent\\av_agent.py", "-m", vm, "-s", mq.session, "-d", redis]
    start_bat = "%s %s\r\n" %( cmd, " ".join(arg) )

    agent_bat = "start /min C:\\AVTest\\AVAgent\\start.bat ^& exit\r\n"

    fd, filename = tempfile.mkstemp(".bat")
    logging.debug("opening file %s with fd: %s" % (filename, fd))
    os.write(fd, agent_bat)
    os.close(fd)

    startup_dir_7 = 'C:/Users/avtest/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup'
    startup_dir_XP = 'C:/Documents and Settings/avtest/Start Menu/Programs/Startup'

    if vm.endswith("32"):
        startup_dir = startup_dir_XP
    else:
        startup_dir = startup_dir_7

    remote_name = "%s/av_agent.bat" % startup_dir
    remote_name= remote_name.replace("/","\\")
    r = vm_manager.execute(vm, "copyFileToGuest", filename, remote_name )
    os.remove(filename)

    fd, filename = tempfile.mkstemp(".bat")
    logging.debug("opening file %s with fd: %s" % (filename, fd))
    os.write(fd, start_bat)
    os.close(fd)

    remote_name = "C:\\AVTest\\AVAgent\\start.bat"
    r = vm_manager.execute(vm, "copyFileToGuest", filename, remote_name )
    os.remove(filename)

    dirname = "%s/avagent/running" % config.basedir_av
    r = vm_manager.execute(vm, "deleteDirectoryInGuest", dirname)

    dirname = "%s/logs" % config.basedir_av
    r = vm_manager.execute(vm, "deleteDirectoryInGuest", dirname)

    if r > 0:
        return False, "Cant Copy %s on VM" % filename

    else:
        return True, "File copied"
Exemple #34
0
def on_answer(vm, success, answer):
    """ server side """
    from AVMaster import vm_manager
    cmd = "/windows/system32/logout.exe"
    arg = []
    ret = vm_manager.execute(vm, "executeCmd", cmd, arg, 40, True, True)
Exemple #35
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    logging.debug("    CS PUSH: %s" % str(args))
    assert vm, "null self.vm"
    assert isinstance(args, list)

    if isinstance(args[0], list):
        src_files, src_dir, dst_dir = args
    elif isinstance(args[0], basestring):
        src_files, src_dir, dst_dir = args, config.basedir_server, config.basedir_av
    else:
        raise RuntimeError("wrong arguments")

    assert isinstance(src_files, list), "PUSH expects a list of src files"

    all_src = []
    relative_parents = set()
    """ look if i need all files in one directory """
    for src_file in src_files:
        g = glob.glob(os.path.join(src_dir, src_file))
        if not g:
            logging.warn("Empty glob")
        # if you arrive here, then you already found the file on the filesystem.
        # typically the file have a relative path
        for f in g:
            # s is the relative file, expanded by glob
            s = f.replace("%s/" % src_dir, "")
            all_src.append(s)
            #logging.debug("file completo f: %s, file relativo s: %s" % (f,s))

            #logging.debug("Check if exists file %s" % f)
            assert os.path.exists(f), "%s %s" % (f, os.getcwd())

            #inserito da Marco
            #logging.debug("Check if exists file %s" % os.path.join(src_dir, s))
            assert os.path.exists(os.path.join(src_dir,
                                               s)), "%s %s" % (s, os.getcwd())

            # add all the parents to the relative_parents set, to avoid repetitions
            p = os.path.split(s)[0]
            while p and p != src_dir:
                relative_parents.add(p)
                #print("1_relative parents")
                p = os.path.split(p)[0]

    # sorts the parents by length, so that parent is always before its sons

    relative_parents.add("./")
    parents = list(relative_parents)
    parents.sort(lambda x, y: len(x) - len(y))
    logging.debug("parents: %s" % parents)

    ntdir = lambda x: x.replace("/", "\\")

    print(parents)

    for r in parents:
        #print(dst_dir)
        rdir = ntdir(os.path.join(dst_dir, r))
        #print("2_crea cartelle %s" % rdir)
        logging.debug("mkdir %s " % (rdir))
        vm_manager.execute(vm, "mkdirInGuest", rdir)
    """ then upload parsed files """
    logging.debug("All files to copy are:\n%s" % src_files)
    if not all_src:
        return False, "Empty file list"

    for src_file in all_src:
        #print("3_processa file")
        src = os.path.join(src_dir, src_file)
        dst = ntdir(os.path.join(dst_dir, src_file))

        #logging.debug("Check if exists file %s" % src)

        if not os.path.exists(src):
            return False, "Not existent file: %s" % src
        else:
            pass
            #logging.debug("file exists")

        logging.debug("%s copy %s -> %s" % (vm, src, dst))
        r = vm_manager.execute(vm, "copyFileToGuest", src, dst)

        if r > 0:
            return False, "Cant Copy %s on VM" % src_file

    return True, "Files copied on VM"
Exemple #36
0
def execute(vm, protocol, args):
    """ server side """
    from AVMaster import vm_manager

    #logging.debug("    CS Execute")
    assert vm, "null vm"
    mq = protocol.mq

    check_avagent = (args == "AV_AGENT")

    mq.reset_connection(vm)
    ret = vm_manager.execute(vm, "startup")
    started = False
    if not ret:
        return False, "Not Started VM"

    max_install = 10
    max_tries = 10

    for i in range(3):
        sleep(10)
        if vm_manager.execute(vm, "is_powered_on"):
            for i in range(max_tries):
                if mq.check_connection(vm):
                    logging.debug("got connection from %s" % vm)
                    return True, "Started VM"

                for i in range(max_install):
                    status = get_status(vm)
                    logging.debug("%s, got status: %s" % (vm, status))

                    if status == "INSTALL":
                        logging.debug(
                            "waiting for the install to finish: %s/%s" %
                            (i, max_install))
                        sleep(60)
                    else:
                        break

                if status == "LOGGED-IN":
                    logging.debug("%s, executing ipconfig, time: %s/%s" %
                                  (vm, i, max_tries))
                    started = vm_manager.execute(
                        vm, "executeCmd",
                        "c:\\windows\\system32\\ipconfig.exe") == 0
                    logging.debug("%s, executed ipconfig, ret: %s" %
                                  (vm, started))

                if started and not check_avagent:
                    return True, "Started VM"
                else:
                    sleep(20)

            if not started:
                logging.debug("%s: reboot requested" % vm)
                vm_manager.execute(vm, "reboot")
                sleep(60)
                continue

            return False, "Not started VM"
        else:
            logging.debug("%s: not yet powered" % vm)

    return False, "Error Occurred: Timeout while starting VM"