示例#1
0
文件: ff.py 项目: zhuyoucai168/qsy
def process_video(video_name, video_ok_path, dir_type):

    print (video_name)

    # 创建保存目录
    # video_ok_path = os.path.dirname(video_name)

    create_dir(video_ok_path)
    frist_name = process_name(video_name)

    video_save_name = os.path.dirname(video_name)
    video_save_name_short = GetShortPathName(video_save_name)
    video_name = GetShortPathName(video_name)

    random_video_name = str(random.random())[2:]
    video_save_name = video_save_name_short + '\\' + random_video_name + '.mp4'
    video_rename_change = video_ok_path + '\\' + frist_name + '.mp4'
    

    filter_x, filter_y, filter_w, filter_h, video_duration = videojson(
        video_name, dir_type)

    # print (video_save_name, video_rename_change)
    # 去掉前 4  后 3 秒
    video_duration_start = 4
    video_duration_end = round(float(video_duration)) - 3

    strCmd = 'ffmpeg -i {} -metadata comment='' -ss {} -to {} -vf delogo=x={}:y={}:w={}:h={}:t=2:band=30 -c:a copy {}'.format(
        video_name, video_duration_start, video_duration_end, filter_x, filter_y, filter_w, filter_h, video_save_name)
    subp = subprocess.Popen(strCmd, stdout=subprocess.PIPE)
    subp.wait()
    change_rename = os.rename(video_save_name, video_rename_change)
    delete_source = os.remove(video_name)
示例#2
0
    def is_target_running (self):
        # sometimes vmrun reports that the VM is up while it's still reverting.
        time.sleep(10)

        for line in self.list().lower().split('\n'):
            if os.name == "nt":
                try:
                    line = GetShortPathName(line)
                # skip invalid paths.
                except:
                    continue

            if self.vmx.lower() == line.lower():
                return True

        return False
示例#3
0
文件: winrun.py 项目: CERTCC/certfuzz
    def __enter__(self):
        if self.verify_architecture:
            self._verify_architecture('32')

        # check various system options
        # register hook dll
        # TODO make path configurable
        hive = HKEY_LOCAL_MACHINE
        branch = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows"
        rname = "AppInit_DLLs"

        self._store_existing_values(hive, branch, rname)

        # assume hook dll is at ../hooks/winxp/Release/hook.dll relative to
        # the location of this module
        my_path = os.path.dirname(__file__)
        relative_path_to_hook_dll = os.path.join(my_path, '..', "hooks",
                                                 "winxp", "Release",
                                                 "hook.dll")
        rval = GetShortPathName(os.path.abspath(relative_path_to_hook_dll))

        try:
            _set_reg_value(hive, branch, rname, rval)
        except OSError, e:
            logger.error('Unable to set registry: %s\%s\%s=%s', hive, branch,
                         rname, rval)
            raise RunnerRegistryError(e)
示例#4
0
def main0():
    print argv
    for fname in os.listdir(unicode(argv[1])):
        #result = chardet.detect(fname)
        #print fname,type(fname),result
        #fname.decode(result['encoding'])
        #print fname,type(fname),chardet.detect(fname)
        #print fname.encode(locale.getpreferredencoding()),type(fname),
        #print argv[1]+'\\'+fname,
        print chardet.detect(fname), type(fname),
        fname = GetShortPathName(argv[1] + '\\' + fname).encode(
            locale.getpreferredencoding(), 'ignore')
        #print type(fname)
        print chardet.detect(fname), type(fname),
        print fname
示例#5
0
    def generate_components_from_path(self, element, path):
        for file_name in os.listdir(path):
            full_path = os.path.join(path, file_name)
            print(full_path)

            if os.path.isdir(full_path):
                dir_elm = ET.SubElement(element, "Directory",
                                        {'Name': file_name,
                                         'Id': 'dirid{}'.format(self.current_dir_id)})
                self.current_dir_id += 1
                self.generate_components_from_path(dir_elm, full_path)
            else:
                comp_id = 'comp{}'.format(len(self.component_list))
                self.component_list.append(comp_id)
                component_elm = ET.SubElement(element, "Component",
                                              {'Id': comp_id, 'Win64': 'yes'})
                file_elm = ET.SubElement(component_elm, "File",
                                         {'Id': 'fileid{}'.format(self.current_file_id),
                                          'Name': file_name,
                                          'Source': GetShortPathName(full_path)[4:],
                                          'DiskId': '1'})
                self.current_file_id += 1
                if file_name in self.guid:
                    component_elm.attrib['Guid'] = self.guid[file_name]
                else:
                    file_elm.attrib['KeyPath'] = 'yes'

                if file_name in self.file_id:
                    file_elm.attrib['Id'] = self.file_id[file_name]

                if file_name.endswith('.dll') or file_name.endswith('.exe'):
                    file_elm.attrib['Checksum'] = 'yes'

                if file_name.endswith('.dll'):
                    file_elm.attrib['ProcessorArchitecture'] = 'x64'

                if file_name in self.extra_childs:
                    file_elm.extend(self.extra_childs[file_name])

                if file_name in self.extra_siblings:
                    component_elm.extend(self.extra_siblings[file_name])
示例#6
0
    def __init__ (self, host, port, vmrun, vmx, snap_name=None, log_level=1, interactive=False):
        '''
        @type  host:         String
        @param host:         Hostname or IP address to bind server to
        @type  port:         Integer
        @param port:         Port to bind server to
        @type  vmrun:        String
        @param vmrun:        Path to VMWare vmrun.exe
        @type  vmx:          String
        @param vmx:          Path to VMX file
        @type  snap_name:    String
        @param snap_name:    (Optional, def=None) Snapshot name to revert to on restart
        @type  log_level:    Integer
        @param log_level:    (Optional, def=1) Log output level, increase for more verbosity
        @type  interactive:  Boolean
        @param interactive:  (Option, def=False) Interactive mode, prompts for input values
        '''

        # initialize the PED-RPC server.
        pedrpc.server.__init__(self, host, port)

        self.host        = host
        self.port        = port

        self.interactive = interactive

        if interactive:
            print "[*] Entering interactive mode..."

            # get vmrun path
            try:
                while 1:
                    print "[*] Please browse to the folder containing vmrun.exe..."
                    pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing vmrun.exe:")
                    fullpath = shell.SHGetPathFromIDList(pidl)
                    file_list = os.listdir(fullpath)
                    if "vmrun.exe" not in file_list:
                        print "[!] vmrun.exe not found in selected folder, please try again"
                    else:
                        vmrun = fullpath + "\\vmrun.exe"
                        print "[*] Using %s" % vmrun
                        break
            except:
                print "[!] Error while trying to find vmrun.exe. Try again without -I."
                sys.exit(1)

            # get vmx path
            try:
                while 1:
                    print "[*] Please browse to the folder containing the .vmx file..."
                    pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing the .vmx file:")
                    fullpath = shell.SHGetPathFromIDList(pidl)
                    file_list = os.listdir(fullpath)

                    exists = False
                    for file in file_list:
                        idx = file.find(".vmx")
                        if idx == len(file) - 4:
                            exists = True
                            vmx = fullpath + "\\" + file
                            print "[*] Using %s" % vmx

                    if exists:
                        break
                    else:
                        print "[!] No .vmx file found in the selected folder, please try again"
            except:
                raise
                print "[!] Error while trying to find the .vmx file. Try again without -I."
                sys.exit(1)

        # Grab snapshot name and log level if we're in interactive mode
        if interactive:
            snap_name = raw_input("[*] Please enter the snapshot name: ")
            log_level = raw_input("[*] Please enter the log level (default 1): ")

            if log_level:
                log_level = int(log_level)
            else:
                log_level = 1

        # if we're on windows, get the DOS path names
        if os.name == "nt":
            self.vmrun       = GetShortPathName(r"%s" % vmrun)
            self.vmx         = GetShortPathName(r"%s" % vmx)
        else:
            self.vmrun = vmrun
            self.vmx   = vmx

        self.snap_name   = snap_name
        self.log_level   = log_level
        self.interactive = interactive

        self.log("VMControl PED-RPC server initialized:")
        self.log("\t vmrun:     %s" % self.vmrun)
        self.log("\t vmx:       %s" % self.vmx)
        self.log("\t snap name: %s" % self.snap_name)
        self.log("\t log level: %d" % self.log_level)
        self.log("Awaiting requests...")
示例#7
0
class vmcontrol_pedrpc_server (pedrpc.server):
    def __init__ (self, host, port, vmrun, vmx, snap_name=None, log_level=1, interactive=False):
        '''
        @type  host:         String
        @param host:         Hostname or IP address to bind server to
        @type  port:         Integer
        @param port:         Port to bind server to
        @type  vmrun:        String
        @param vmrun:        Path to VMWare vmrun.exe
        @type  vmx:          String
        @param vmx:          Path to VMX file
        @type  snap_name:    String
        @param snap_name:    (Optional, def=None) Snapshot name to revert to on restart
        @type  log_level:    Integer
        @param log_level:    (Optional, def=1) Log output level, increase for more verbosity
        @type  interactive:  Boolean
        @param interactive:  (Option, def=False) Interactive mode, prompts for input values
        '''

        # initialize the PED-RPC server.
        pedrpc.server.__init__(self, host, port)

        self.host        = host
        self.port        = port

        self.interactive = interactive

        if interactive:
            print "[*] Entering interactive mode..."

            # get vmrun path
            try:
                while 1:
                    print "[*] Please browse to the folder containing vmrun.exe..."
                    pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing vmrun.exe:")
                    fullpath = shell.SHGetPathFromIDList(pidl)
                    file_list = os.listdir(fullpath)
                    if "vmrun.exe" not in file_list:
                        print "[!] vmrun.exe not found in selected folder, please try again"
                    else:
                        vmrun = fullpath + "\\vmrun.exe"
                        print "[*] Using %s" % vmrun
                        break
            except:
                print "[!] Error while trying to find vmrun.exe. Try again without -I."
                sys.exit(1)

            # get vmx path
            try:
                while 1:
                    print "[*] Please browse to the folder containing the .vmx file..."
                    pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing the .vmx file:")
                    fullpath = shell.SHGetPathFromIDList(pidl)
                    file_list = os.listdir(fullpath)

                    exists = False
                    for file in file_list:
                        idx = file.find(".vmx")
                        if idx == len(file) - 4:
                            exists = True
                            vmx = fullpath + "\\" + file
                            print "[*] Using %s" % vmx

                    if exists:
                        break
                    else:
                        print "[!] No .vmx file found in the selected folder, please try again"
            except:
                raise
                print "[!] Error while trying to find the .vmx file. Try again without -I."
                sys.exit(1)

        # Grab snapshot name and log level if we're in interactive mode
        if interactive:
            snap_name = raw_input("[*] Please enter the snapshot name: ")
            log_level = raw_input("[*] Please enter the log level (default 1): ")

            if log_level:
                log_level = int(log_level)
            else:
                log_level = 1

        # if we're on windows, get the DOS path names
        if os.name == "nt":
            self.vmrun       = GetShortPathName(r"%s" % vmrun)
            self.vmx         = GetShortPathName(r"%s" % vmx)
        else:
            self.vmrun = vmrun
            self.vmx   = vmx

        self.snap_name   = snap_name
        self.log_level   = log_level
        self.interactive = interactive

        self.log("VMControl PED-RPC server initialized:")
        self.log("\t vmrun:     %s" % self.vmrun)
        self.log("\t vmx:       %s" % self.vmx)
        self.log("\t snap name: %s" % self.snap_name)
        self.log("\t log level: %d" % self.log_level)
        self.log("Awaiting requests...")


    def alive (self):
        '''
        Returns True. Useful for PED-RPC clients who want to see if the PED-RPC connection is still alive.
        '''

        return True


    def log (self, msg="", level=1):
        '''
        If the supplied message falls under the current log level, print the specified message to screen.

        @type  msg: String
        @param msg: Message to log
        '''

        if self.log_level >= level:
            print "[%s] %s" % (time.strftime("%I:%M.%S"), msg)


    def set_vmrun (self, vmrun):
        self.log("setting vmrun to %s" % vmrun, 2)
        self.vmrun = vmrun


    def set_vmx (self, vmx):
        self.log("setting vmx to %s" % vmx, 2)
        self.vmx = vmx


    def set_snap_name (self, snap_name):
        self.log("setting snap_name to %s" % snap_name, 2)
        self.snap_name = snap_name


    def vmcommand (self, command):
        '''
        Execute the specified command, keep trying in the event of a failure.

        @type  command: String
        @param command: VMRun command to execute
        '''

        while 1:
            self.log("executing: %s" % command, 5)

            pipe = os.popen(command)
            out  = pipe.readlines()

            try:
                pipe.close()
            except IOError:
                self.log("IOError trying to close pipe")

            if not out:
                break
            elif not out[0].lower().startswith("close failed"):
                break

            self.log("failed executing command '%s' (%s). will try again." % (command, out))
            time.sleep(1)

        return "".join(out)


    ###
    ### VMRUN COMMAND WRAPPERS
    ###


    def delete_snapshot (self, snap_name=None):
        if not snap_name:
            snap_name = self.snap_name

        self.log("deleting snapshot: %s" % snap_name, 2)

        command = self.vmrun + " deleteSnapshot " + self.vmx + " " + '"' + snap_name + '"'
        return self.vmcommand(command)


    def list (self):
        self.log("listing running images", 2)

        command = self.vmrun + " list"
        return self.vmcommand(command)


    def list_snapshots (self):
        self.log("listing snapshots", 2)

        command = self.vmrun + " listSnapshots " + self.vmx
        return self.vmcommand(command)


    def reset (self):
        self.log("resetting image", 2)

        command = self.vmrun + " reset " + self.vmx
        return self.vmcommand(command)


    def revert_to_snapshot (self, snap_name=None):
        if not snap_name:
            snap_name = self.snap_name

        self.log("reverting to snapshot: %s" % snap_name, 2)

        command = self.vmrun + " revertToSnapshot " + self.vmx + " " + '"' + snap_name + '"'
        return self.vmcommand(command)


    def snapshot (self, snap_name=None):
        if not snap_name:
            snap_name = self.snap_name

        self.log("taking snapshot: %s" % snap_name, 2)

        command = self.vmrun + " snapshot " + self.vmx + " " + '"' + snap_name + '"'

        return self.vmcommand(command)


    def start (self):
        self.log("starting image", 2)

        command = self.vmrun + " start " + self.vmx
        return self.vmcommand(command)


    def stop (self):
        self.log("stopping image", 2)

        command = self.vmrun + " stop " + self.vmx
        return self.vmcommand(command)


    def suspend (self):
        self.log("suspending image", 2)

        command = self.vmrun + " suspend " + self.vmx
        return self.vmcommand(command)


    ###
    ### EXTENDED COMMANDS
    ###


    def restart_target (self):
        self.log("restarting virtual machine...")
        # revert to the specified snapshot and start the image.
        self.revert_to_snapshot()
        self.start()

        # wait for the snapshot to come alive.
        self.wait()


    def is_target_running (self):
        vmx_trimmed = "\\".join(self.vmx.split("\\")[:-1])

        return vmx_trimmed.lower() in self.list().lower()


    def wait (self):
        self.log("waiting for vmx to come up: %s" % self.vmx)
        while 1:
            if self.is_target_running():
                break
示例#8
0
    def __init__ (self, host, port, vmrun, vmx, snap_name=None, log_level=1, interactive=False):
        '''
        @type  host:         String
        @param host:         Hostname or IP address to bind server to
        @type  port:         Integer
        @param port:         Port to bind server to
        @type  vmrun:        String
        @param vmrun:        Path to VMWare vmrun.exe
        @type  vmx:          String
        @param vmx:          Path to VMX file
        @type  snap_name:    String
        @param snap_name:    (Optional, def=None) Snapshot name to revert to on restart
        @type  log_level:    Integer
        @param log_level:    (Optional, def=1) Log output level, increase for more verbosity
        @type  interactive:  Boolean
        @param interactive:  (Option, def=False) Interactive mode, prompts for input values
        '''

        # initialize the PED-RPC server.
        pedrpc.server.__init__(self, host, port)

        self.host        = host
        self.port        = port

        self.interactive = interactive

        if interactive:
            print "[*] Entering interactive mode..."

            # get vmrun path
            try:
                while 1:
                    print "[*] Please browse to the folder containing vmrun.exe..."
                    pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing vmrun.exe:")
                    fullpath = shell.SHGetPathFromIDList(pidl)
                    file_list = os.listdir(fullpath)
                    if "vmrun.exe" not in file_list:
                        print "[!] vmrun.exe not found in selected folder, please try again"
                    else:
                        vmrun = fullpath + "\\vmrun.exe"
                        print "[*] Using %s" % vmrun
                        break
            except:
                print "[!] Error while trying to find vmrun.exe. Try again without -I."
                sys.exit(1)

            # get vmx path
            try:
                while 1:
                    print "[*] Please browse to the folder containing the .vmx file..."
                    pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing the .vmx file:")
                    fullpath = shell.SHGetPathFromIDList(pidl)
                    file_list = os.listdir(fullpath)

                    exists = False
                    for file in file_list:
                        idx = file.find(".vmx")
                        if idx == len(file) - 4:
                            exists = True
                            vmx = fullpath + "\\" + file
                            print "[*] Using %s" % vmx

                    if exists:
                        break
                    else:
                        print "[!] No .vmx file found in the selected folder, please try again"
            except:
                raise
                print "[!] Error while trying to find the .vmx file. Try again without -I."
                sys.exit(1)

        # Grab snapshot name and log level if we're in interactive mode
        if interactive:
            snap_name = raw_input("[*] Please enter the snapshot name: ")
            log_level = raw_input("[*] Please enter the log level (default 1): ")

            if log_level:
                log_level = int(log_level)
            else:
                log_level = 1

        # if we're on windows, get the DOS path names
        if os.name == "nt":
            self.vmrun = GetShortPathName(r"%s" % vmrun)
            self.vmx   = GetShortPathName(r"%s" % vmx)
        else:
            self.vmrun = vmrun
            self.vmx   = vmx

        self.snap_name   = snap_name
        self.log_level   = log_level
        self.interactive = interactive

        self.log("VMControl PED-RPC server initialized:")
        self.log("\t vmrun:     %s" % self.vmrun)
        self.log("\t vmx:       %s" % self.vmx)
        self.log("\t snap name: %s" % self.snap_name)
        self.log("\t log level: %d" % self.log_level)
        self.log("Awaiting requests...")
示例#9
0
class vmcontrol_pedrpc_server (pedrpc.server):
    def __init__ (self, host, port, vmrun, vmx, snap_name=None, log_level=1, interactive=False):
        '''
        @type  host:         String
        @param host:         Hostname or IP address to bind server to
        @type  port:         Integer
        @param port:         Port to bind server to
        @type  vmrun:        String
        @param vmrun:        Path to VMWare vmrun.exe
        @type  vmx:          String
        @param vmx:          Path to VMX file
        @type  snap_name:    String
        @param snap_name:    (Optional, def=None) Snapshot name to revert to on restart
        @type  log_level:    Integer
        @param log_level:    (Optional, def=1) Log output level, increase for more verbosity
        @type  interactive:  Boolean
        @param interactive:  (Option, def=False) Interactive mode, prompts for input values
        '''

        # initialize the PED-RPC server.
        pedrpc.server.__init__(self, host, port)

        self.host        = host
        self.port        = port

        self.interactive = interactive

        if interactive:
            print "[*] Entering interactive mode..."

            # get vmrun path
            try:
                while 1:
                    print "[*] Please browse to the folder containing vmrun.exe..."
                    pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing vmrun.exe:")
                    fullpath = shell.SHGetPathFromIDList(pidl)
                    file_list = os.listdir(fullpath)
                    if "vmrun.exe" not in file_list:
                        print "[!] vmrun.exe not found in selected folder, please try again"
                    else:
                        vmrun = fullpath + "\\vmrun.exe"
                        print "[*] Using %s" % vmrun
                        break
            except:
                print "[!] Error while trying to find vmrun.exe. Try again without -I."
                sys.exit(1)

            # get vmx path
            try:
                while 1:
                    print "[*] Please browse to the folder containing the .vmx file..."
                    pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing the .vmx file:")
                    fullpath = shell.SHGetPathFromIDList(pidl)
                    file_list = os.listdir(fullpath)

                    exists = False
                    for file in file_list:
                        idx = file.find(".vmx")
                        if idx == len(file) - 4:
                            exists = True
                            vmx = fullpath + "\\" + file
                            print "[*] Using %s" % vmx

                    if exists:
                        break
                    else:
                        print "[!] No .vmx file found in the selected folder, please try again"
            except:
                raise
                print "[!] Error while trying to find the .vmx file. Try again without -I."
                sys.exit(1)

        # Grab snapshot name and log level if we're in interactive mode
        if interactive:
            snap_name = raw_input("[*] Please enter the snapshot name: ")
            log_level = raw_input("[*] Please enter the log level (default 1): ")

            if log_level:
                log_level = int(log_level)
            else:
                log_level = 1

        # if we're on windows, get the DOS path names
        if os.name == "nt":
            self.vmrun = GetShortPathName(r"%s" % vmrun)
            self.vmx   = GetShortPathName(r"%s" % vmx)
        else:
            self.vmrun = vmrun
            self.vmx   = vmx

        self.snap_name   = snap_name
        self.log_level   = log_level
        self.interactive = interactive

        self.log("VMControl PED-RPC server initialized:")
        self.log("\t vmrun:     %s" % self.vmrun)
        self.log("\t vmx:       %s" % self.vmx)
        self.log("\t snap name: %s" % self.snap_name)
        self.log("\t log level: %d" % self.log_level)
        self.log("Awaiting requests...")


    def alive (self):
        '''
        Returns True. Useful for PED-RPC clients who want to see if the PED-RPC connection is still alive.
        '''

        return True


    def log (self, msg="", level=1):
        '''
        If the supplied message falls under the current log level, print the specified message to screen.

        @type  msg: String
        @param msg: Message to log
        '''

        if self.log_level >= level:
            print "[%s] %s" % (time.strftime("%I:%M.%S"), msg)


    def set_vmrun (self, vmrun):
        self.log("setting vmrun to %s" % vmrun, 2)
        self.vmrun = vmrun


    def set_vmx (self, vmx):
        self.log("setting vmx to %s" % vmx, 2)
        self.vmx = vmx


    def set_snap_name (self, snap_name):
        self.log("setting snap_name to %s" % snap_name, 2)
        self.snap_name = snap_name


    def vmcommand (self, command):
        '''
        Execute the specified command, keep trying in the event of a failure.

        @type  command: String
        @param command: VMRun command to execute
        '''

        while 1:
            self.log("executing: %s" % command, 5)

            pipe = os.popen(command)
            out  = pipe.readlines()

            try:
                pipe.close()
            except IOError:
                self.log("IOError trying to close pipe")

            if not out:
                break
            elif not out[0].lower().startswith("close failed"):
                break

            self.log("failed executing command '%s' (%s). will try again." % (command, out))
            time.sleep(1)

        return "".join(out)


    ###
    ### VMRUN COMMAND WRAPPERS
    ###


    def delete_snapshot (self, snap_name=None):
        if not snap_name:
            snap_name = self.snap_name

        self.log("deleting snapshot: %s" % snap_name, 2)

        command = self.vmrun + " deleteSnapshot " + self.vmx + " " + '"' + snap_name + '"'
        return self.vmcommand(command)


    def list (self):
        self.log("listing running images", 2)

        command = self.vmrun + " list"
        return self.vmcommand(command)


    def list_snapshots (self):
        self.log("listing snapshots", 2)

        command = self.vmrun + " listSnapshots " + self.vmx
        return self.vmcommand(command)


    def reset (self):
        self.log("resetting image", 2)

        command = self.vmrun + " reset " + self.vmx
        return self.vmcommand(command)


    def revert_to_snapshot (self, snap_name=None):
        if not snap_name:
            snap_name = self.snap_name

        self.log("reverting to snapshot: %s" % snap_name, 2)

        command = self.vmrun + " revertToSnapshot " + self.vmx + " " + '"' + snap_name + '"'
        return self.vmcommand(command)


    def snapshot (self, snap_name=None):
        if not snap_name:
            snap_name = self.snap_name

        self.log("taking snapshot: %s" % snap_name, 2)

        command = self.vmrun + " snapshot " + self.vmx + " " + '"' + snap_name + '"'

        return self.vmcommand(command)


    def start (self):
        self.log("starting image", 2)

        command = self.vmrun + " start " + self.vmx
        return self.vmcommand(command)


    def stop (self):
        self.log("stopping image", 2)

        command = self.vmrun + " stop " + self.vmx
        return self.vmcommand(command)


    def suspend (self):
        self.log("suspending image", 2)

        command = self.vmrun + " suspend " + self.vmx
        return self.vmcommand(command)


    ###
    ### EXTENDED COMMANDS
    ###


    def restart_target (self):
        self.log("restarting virtual machine...")

        # revert to the specified snapshot and start the image.
        self.revert_to_snapshot()
        self.start()

        # wait for the snapshot to come alive.
        self.wait()


    def is_target_running (self):
        # sometimes vmrun reports that the VM is up while it's still reverting.
        time.sleep(10)

        for line in self.list().lower().split('\n'):
            if os.name == "nt":
                try:
                    line = GetShortPathName(line)
                # skip invalid paths.
                except:
                    continue

            if self.vmx.lower() == line.lower():
                return True

        return False


    def wait (self):
        self.log("waiting for vmx to come up: %s" % self.vmx)
        while 1:
            if self.is_target_running():
                break
示例#10
0
    def __init__(self,
                 host,
                 port,
                 vmrun,
                 vmx,
                 snap_name=None,
                 log_level=1,
                 interactive=False):
        """
        Controls an Oracle VirtualBox Virtual Machine

        @type  host:         str
        @param host:         Hostname or IP address to bind server to
        @type  port:         int
        @param port:         Port to bind server to
        @type  vmrun:        str
        @param vmrun:        Path to VBoxManage
        @type  vmx:          str
        @param vmx:          Name of the virtualbox VM to control (no quotes)
        @type  snap_name:    str
        @param snap_name:    (Optional, def=None) Snapshot name to revert to on restart
        @type  log_level:    int
        @param log_level:    (Optional, def=1) Log output level, increase for more verbosity
        @type  interactive:  bool
        @param interactive:  (Option, def=False) Interactive mode, prompts for input values
        """

        # initialize the PED-RPC server.
        pedrpc.Server.__init__(self, host, port)

        self.host = host
        self.port = port

        self.interactive = interactive

        if interactive:
            print "[*] Entering interactive mode..."

            # get vmrun path
            try:
                while 1:
                    print "[*] Please browse to the folder containing VBoxManage.exe..."
                    pidl, disp, imglist = shell.SHBrowseForFolder(
                        0, None,
                        "Please browse to the folder containing VBoxManage.exe"
                    )
                    fullpath = shell.SHGetPathFromIDList(pidl)
                    file_list = os.listdir(fullpath)
                    if "VBoxManage.exe" not in file_list:
                        print "[!] VBoxManage.exe not found in selected folder, please try again"
                    else:
                        vmrun = fullpath + "\\VBoxManage.exe"
                        print "[*] Using %s" % vmrun
                        break
            except Exception:
                print "[!] Error while trying to find VBoxManage.exe. Try again without -I."
                sys.exit(1)

        # Grab vmx, snapshot name and log level if we're in interactive mode
        if interactive:
            vmx = raw_input(
                "[*] Please enter the VirtualBox virtual machine name: ")
            snap_name = raw_input("[*] Please enter the snapshot name: ")
            log_level = raw_input(
                "[*] Please enter the log level (default 1): ")

        if log_level:
            log_level = int(log_level)
        else:
            log_level = 1

        # if we're on windows, get the DOS path names
        if os.name == "nt":
            self.vmrun = GetShortPathName(r"%s" % vmrun)
            self.vmx = GetShortPathName(r"%s" % vmx)
        else:
            self.vmrun = vmrun
            self.vmx = vmx

        self.snap_name = snap_name
        self.log_level = log_level
        self.interactive = interactive

        self.log("VirtualBox PED-RPC server initialized:")
        self.log("\t vboxmanage:     %s" % self.vmrun)
        self.log("\t machine name:       %s" % self.vmx)
        self.log("\t snap name: %s" % self.snap_name)
        self.log("\t log level: %d" % self.log_level)
        self.log("Awaiting requests...")
示例#11
0
 def execute_file(dir: str):
     if dir:
         if os.path.isfile(dir):
             sdir = GetShortPathName(dir)
             threading._start_new_thread(os.system, (sdir, ))