def symlink(src, dst): if os.path.lexists(dst): try: if Platform.system == 'Windows': os.rmdir(dst) else: os.unlink(dst) except: Utils.exit( "Can not unlink %s/%s. Manually rename or remove this file" % (os.getcwd(), dst)) if Platform.system == "Windows": # TODO : Not supported import win32file try: win32file.CreateSymbolicLink(dst, src, 1) except: Log.error("""Insufficicient rights to create symlinks. You can try the following: 1) Run 'secpol.msc' as administrator, Select 'Local Policies > User Rights Assignment > Create symbolic links' and add your user. Click Apply to save your changes. 2) Press "Windows R" and run 'GPUpdate /Force' to activate your changes""") Utils.exit() else: os.symlink(src, dst)
def setUpClass(cls): ''' Create special file_roots for symlink test on Windows ''' if salt.utils.platform.is_windows(): root_dir = tempfile.mkdtemp(dir=TMP) source_sym = os.path.join(root_dir, 'source_sym') with salt.utils.files.fopen(source_sym, 'w') as fp_: fp_.write('hello world!\n') cwd = os.getcwd() try: os.chdir(root_dir) win32file.CreateSymbolicLink('dest_sym', 'source_sym', 0) finally: os.chdir(cwd) cls.test_symlink_list_file_roots = {'base': [root_dir]} else: cls.test_symlink_list_file_roots = None cls.tmp_dir = tempfile.mkdtemp(dir=TMP) full_path_to_file = os.path.join(FILES, 'file', 'base', 'testfile') with salt.utils.files.fopen(full_path_to_file, 'rb') as s_fp: with salt.utils.files.fopen(os.path.join(cls.tmp_dir, 'testfile'), 'wb') as d_fp: for line in s_fp: d_fp.write( line.rstrip(b'\n').rstrip(b'\r') + os.linesep.encode('utf-8'))
def test_symlinks_enabled(self): """ Test if symlinks are harvested """ self.render_config_template( path=os.path.abspath(self.working_dir) + "/log/symlink.log", symlinks="true", ) os.mkdir(self.working_dir + "/log/") logfile = self.working_dir + "/log/test.log" symlink = self.working_dir + "/log/symlink.log" if os.name == "nt": import win32file win32file.CreateSymbolicLink(symlink, logfile, 0) else: os.symlink(logfile, symlink) with open(logfile, 'a') as file: file.write("Hello World\n") filebeat = self.start_beat() # Make sure content in symlink file is read self.wait_until(lambda: self.output_has(lines=1), max_timeout=10) filebeat.check_kill_and_wait()
def test_symlink_failure(self): """ Test that filebeat does not start if a symlink is set as registry file """ self.render_config_template( path=os.path.abspath(self.working_dir) + "/log/*", registryFile="registry_symlink", ) os.mkdir(self.working_dir + "/log/") testfile_path = self.working_dir + "/log/test.log" with open(testfile_path, 'w') as testfile: testfile.write("Hello World\n") registryfile = self.working_dir + "/registry" with open(registryfile, 'w') as testfile: testfile.write("[]") if os.name == "nt": import win32file # pylint: disable=import-error win32file.CreateSymbolicLink( self.working_dir + "/registry_symlink", registryfile, 0) else: os.symlink(registryfile, self.working_dir + "/registry_symlink") filebeat = self.start_beat() # Make sure states written appears one more time self.wait_until(lambda: self.log_contains( "CRIT Exiting: Registry file path is not a regular file"), max_timeout=10) filebeat.check_kill_and_wait(exit_code=1)
def _save_shortcut(self, name, target): # Shortcut actual file goes to "Enso Learn As" directory. This is typically # different for each platform. shortcut_file_path = os.path.join(self._get_learn_as_dir(), name) if self._is_url(target): shortcut_file_path = shortcut_file_path + ".url" if os.path.isfile(shortcut_file_path): raise ShortcutAlreadyExistsError() s = win_shortcuts.PyInternetShortcut() s.set_url(target) s.save(shortcut_file_path) else: shortcut_file_path = shortcut_file_path + ".lnk" if os.path.isfile(shortcut_file_path): raise ShortcutAlreadyExistsError() if os.path.splitext(target)[1] == ".lnk": try: win32file.CreateSymbolicLink( shortcut_file_path, target, win32file.SYMBOLIC_LINK_FLAG_DIRECTORY if os.path.isdir(target) else 0) except Exception, e: s = win_shortcuts.PyShellLink() s.set_path(target) s.set_working_dir(os.path.dirname(target)) s.set_icon_location(target, 0) s.save(shortcut_file_path) else:
def test_symlink_and_file(self): """ Tests that if symlink and original file are read, that only events from one are added """ self.render_config_template( path=os.path.abspath(self.working_dir) + "/log/*", symlinks="true", ) os.mkdir(self.working_dir + "/log/") logfile = self.working_dir + "/log/test.log" symlink = self.working_dir + "/log/symlink.log" if os.name == "nt": import win32file win32file.CreateSymbolicLink(symlink, logfile, 0) else: os.symlink(logfile, symlink) with open(logfile, 'a') as file: file.write("Hello World1\n") filebeat = self.start_beat() # Make sure both files were read self.wait_until(lambda: self.output_has(lines=1), max_timeout=10) filebeat.check_kill_and_wait() # Check if two different files are in registry data = self.get_registry() assert len(data) == 1
def symlink(source, link_name): import platform if platform.system() == 'Windows': import win32file win32file.CreateSymbolicLink(source, link_name, 1) else: os.symlink(source, link_name)
def setUpClass(cls): """ Create special file_roots for symlink test on Windows """ if salt.utils.platform.is_windows(): root_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP) source_sym = os.path.join(root_dir, 'source_sym') with salt.utils.files.fopen(source_sym, 'w') as fp_: fp_.write('hello world!\n') cwd = os.getcwd() try: os.chdir(root_dir) win32file.CreateSymbolicLink("dest_sym", "source_sym", 0) finally: os.chdir(cwd) cls.test_symlink_list_file_roots = {"base": [root_dir]} else: dest_sym = os.path.join(RUNTIME_VARS.BASE_FILES, "dest_sym") if not os.path.islink(dest_sym): # Fix broken symlink by recreating it if os.path.exists(dest_sym): os.remove(dest_sym) os.symlink("source_sym", dest_sym) cls.test_symlink_list_file_roots = None cls.tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP) full_path_to_file = os.path.join(RUNTIME_VARS.BASE_FILES, 'testfile') with salt.utils.files.fopen(full_path_to_file, 'rb') as s_fp: with salt.utils.files.fopen(os.path.join(cls.tmp_dir, 'testfile'), 'wb') as d_fp: for line in s_fp: d_fp.write(line)
def test_ignore_symlink(self): """ Test that symlinks are ignored """ self.render_config_template(path=os.path.abspath(self.working_dir) + "/log/symlink.log", ) os.mkdir(self.working_dir + "/log/") logfile = self.working_dir + "/log/test.log" symlink = self.working_dir + "/log/symlink.log" if os.name == "nt": import win32file win32file.CreateSymbolicLink(symlink, logfile, 0) else: os.symlink(logfile, symlink) with open(logfile, 'a') as file: file.write("Hello World\n") filebeat = self.start_beat() # Make sure symlink is skipped self.wait_until( lambda: self.log_contains("skipped as it is a symlink"), max_timeout=15) filebeat.check_kill_and_wait()
def symlink(src, dst): if os.name == 'nt': try: win32file.CreateSymbolicLink(src, dst, 1) except ImportError: raise Exception('Please install pywin32') else: os.symlink(src, dst)
def symlink(source, link_name): ''' Handle symlinks on Windows with Python < 3.2 ''' if salt.utils.platform.is_windows(): win32file.CreateSymbolicLink(link_name, source) else: os.symlink(source, link_name)
def _get_vss_dir(self, shadow, i=0): vssfolder = os.getenv( "SystemDrive") + "\\" + "registrydecodervss%d" % i try: win32file.CreateSymbolicLink(vssfolder, shadow, 1) except Exception, e: #print "Exception: %s" % str(e) (vssfolder, i) = self._get_vss_dir(shadow, i + 1)
def link_local_settings(environment): """ link local_settings.py.environment as local_settings.py """ # check that settings imports local_settings, as it always should, # and if we forget to add that to our project, it could cause mysterious # failures settings_file = os.path.join(env['django_dir'], 'settings.py') with open(settings_file) as settings_file: matching_lines = [ line for line in settings_file if line.find('local_settings') ] if not matching_lines: print "Fatal error: settings.py doesn't seem to import " \ "local_settings.*: %s" % settings_file sys.exit(1) # die if the correct local settings does not exist if not env['quiet']: print "### creating link to local_settings.py" local_settings_env_path = os.path.join(env['django_dir'], 'local_settings.py.' + environment) if not os.path.exists(local_settings_env_path): print "Could not find file to link to: %s" % local_settings_env_path sys.exit(1) files_to_remove = ('local_settings.py', 'local_settings.pyc') for file in files_to_remove: full_path = os.path.join(env['django_dir'], file) if os.path.exists(full_path): os.remove(full_path) source = os.path.join(env['django_dir'], 'local_settings.py.%s' % environment) target = os.path.join(env['django_dir'], 'local_settings.py') if os.name == 'posix': os.symlink('local_settings.py.%s' % environment, target) elif os.name == 'nt': try: import win32file except ImportError: raise Exception("It looks like the PyWin32 extensions are not " + "installed") if os.path.exists(target): os.unlink(target) try: win32file.CreateSymbolicLink(target, source) except NotImplementedError: win32file.CreateHardLink(target, source) else: import shutil shutil.copy2(source, target) env['environment'] = environment
def mklink(fpath, target): """ Creates a symlink. :param fpath: symlinkfile path to create :type fpath: basestring :param target: path to link to :type target: basestring :return: """ win32file.CreateSymbolicLink(SymlinkFileName=fpath, TargetFileName=target, Flags=(1 if os.path.isdir(target) else 0))
def link_local_settings(environment): """ link local_settings.py.environment as local_settings.py """ if not env['quiet']: print "### creating link to local_settings.py" # check that settings imports local_settings, as it always should, # and if we forget to add that to our project, it could cause mysterious # failures settings_file_path = path.join(env['django_settings_dir'], 'settings.py') if not (path.isfile(settings_file_path)): raise InvalidProjectError( "Fatal error: settings.py doesn't seem to exist") with open(settings_file_path) as settings_file: matching_lines = [ line for line in settings_file if 'local_settings' in line ] if not matching_lines: raise InvalidProjectError( "Fatal error: settings.py doesn't seem to import " "local_settings.*: %s" % settings_file_path) source = path.join(env['django_settings_dir'], 'local_settings.py.%s' % environment) target = path.join(env['django_settings_dir'], 'local_settings.py') # die if the correct local settings does not exist if not path.exists(source): raise InvalidProjectError("Could not find file to link to: %s" % source) # remove any old versions, plus the pyc copy for old_file in (target, target + 'c'): if path.exists(old_file): os.remove(old_file) if os.name == 'posix': os.symlink('local_settings.py.%s' % environment, target) elif os.name == 'nt': try: import win32file except ImportError: raise Exception( "It looks like the PyWin32 extensions are not installed") try: win32file.CreateSymbolicLink(target, source) except NotImplementedError: win32file.CreateHardLink(target, source) else: import shutil shutil.copy2(source, target) env['environment'] = environment
def make_link( source_path, target_path ): # links two paths. Files are hard linked, where as dirs are linked as junctions. if path.isfile(source_path): unlink(target_path) win32file.CreateHardLink(target_path, path.abspath(source_path)) elif path.isdir(source_path): rmdir(target_path) win32file.CreateSymbolicLink(target_path, path.abspath(source_path), 1) else: return 1 # error
def create_lnks(self): if len(self.files) < 1: return self.lnk_dir = tempfile.mkdtemp() logger.info('Created temporary folder: %s' % self.lnk_dir) logger.info('Creating LNKs...') for file in self.files: lnk = win32file.CreateSymbolicLink( os.path.join(self.lnk_dir, '{}.lnk'.format(file)), self.files[file]['local_path']) logger.info('Done; created %i LNKs.' % len(os.listdir(self.lnk_dir)))
def test_symlink_removed(self): """ Tests that if a symlink to a file is removed, further data is read which is added to the original file """ self.render_config_template( path=os.path.abspath(self.working_dir) + "/log/symlink.log", symlinks="true", clean_removed="false", close_removed="false", ) os.mkdir(self.working_dir + "/log/") logfile = self.working_dir + "/log/test.log" symlink = self.working_dir + "/log/symlink.log" if os.name == "nt": import win32file win32file.CreateSymbolicLink(symlink, logfile, 0) else: os.symlink(logfile, symlink) with open(logfile, 'a') as file: file.write("Hello World1\n") filebeat = self.start_beat() # Make sure symlink is skipped self.wait_until( lambda: self.output_has(lines=1), max_timeout=10) os.remove(symlink) with open(logfile, 'a') as file: file.write("Hello World2\n") # Sleep 1s to make sure new events are not picked up time.sleep(1) # Make sure also new file was read self.wait_until( lambda: self.output_has(lines=2), max_timeout=10) filebeat.check_kill_and_wait() # Check if two different files are in registry data = self.get_registry() assert len(data) == 1
def CreateSymbolicLink(link_target, origin): from vyperlogix.misc import _utils if (_utils.isUsingWindows): import win32file win32file.CreateSymbolicLink(link_target, origin, 1) else: from vyperlogix.process import Popen Popen.Shell('ln -s %s %s' % (origin, link_target), shell=None, env=None, isExit=True, isWait=True, isVerbose=True, fOut=sys.stdout)
def symlink(filename, linkname): """Create a symbolic link. filename: target name of symblic link. Should be an existing filename. linkename: name of new symblic link to be created.""" from os import remove from os.path import exists if exists(linkname): remove(linkname) # Replacememnt for os.symlink that is platform independent. try: from os import symlink symlink(filename, linkname) except ImportError: import win32file win32file.CreateSymbolicLink(linkname, filename, 0)
def symlink(self, targetdir, link): """ """ try: os.symlink(targetdir, link) except AttributeError: import win32file flag = 1 if os.path.isdir(targetdir) else 0 try: win32file.CreateSymbolicLink(link, targetdir, flag) except Exception as e: log.error("Failed to symlink %s to %s: %s", targetdir, link, e) raise with open('%s.target' % link, 'w') as f: f.write(targetdir)
def symlink(src, link): ''' Create a symbolic link to a file This is only supported with Windows Vista or later and must be executed by a user with the SeCreateSymbolicLink privilege. The behavior of this function matches the Unix equivalent, with one exception - invalid symlinks cannot be created. The source path must exist. If it doesn't, an error will be raised. CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' # When Python 3.2 or later becomes the minimum version, this function can be # replaced with the built-in os.symlink function, which supports Windows. if sys.getwindowsversion().major < 6: raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.') if not os.path.exists(src): raise SaltInvocationError('The given source path does not exist.') if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') # ensure paths are using the right slashes src = os.path.normpath(src) link = os.path.normpath(link) is_dir = os.path.isdir(src) try: win32file.CreateSymbolicLink(link, src, int(is_dir)) return True except pywinerror as exc: raise CommandExecutionError( 'Could not create \'{0}\' - [{1}] {2}'.format( link, exc.winerror, exc.strerror ) )
def setUpClass(cls): ''' Create special file_roots for symlink test on Windows ''' if salt.utils.is_windows(): root_dir = tempfile.mkdtemp(dir=TMP) source_sym = os.path.join(root_dir, 'source_sym') with salt.utils.fopen(source_sym, 'w') as fp_: fp_.write('hello world!\n') cwd = os.getcwd() try: os.chdir(root_dir) win32file.CreateSymbolicLink('dest_sym', 'source_sym', 0) finally: os.chdir(cwd) cls.test_symlink_list_file_roots = {'base': [root_dir]} else: cls.test_symlink_list_file_roots = None
def _update_fetch_history(self, storage_dir, package, deps): LOG.debug('Updating history') # Add index to allow access to our fetched files only knowing the hash index = os.path.join(STORAGE_DIR, '.index') if not os.path.exists(index): os.makedirs(index) symlink = os.path.join(index, package.hash) if not os.path.exists(symlink): if scalarizr.linux.os['name'] == 'Windows': win32file.CreateSymbolicLink(symlink, storage_dir, 1) else: os.symlink(storage_dir, symlink) # Write down version, date and package order Metadata(storage_dir).set( version=package.version, download_date=time.time(), packages=map(lambda pkg: posixpath.basename(pkg.location), deps + [package]))
def csharp_symlinks(args): dirname = os.path.dirname(args.project_file) engine_path = get_engine_path() symlinks = [] SymlinkFileName = os.path.join(dirname, 'Code', 'CryManaged', 'CESharp') TargetFileName = os.path.join(engine_path, 'Code', 'CryManaged', 'CESharp') symlinks.append((SymlinkFileName, TargetFileName)) SymlinkFileName = os.path.join(dirname, 'bin', args.platform, 'CryEngine.Common.dll') TargetFileName = os.path.join(engine_path, 'bin', args.platform, 'CryEngine.Common.dll') symlinks.append((SymlinkFileName, TargetFileName)) create_symlinks = [] for (SymlinkFileName, TargetFileName) in symlinks: if os.path.islink(SymlinkFileName): if os.path.samefile(SymlinkFileName, TargetFileName): continue elif os.path.exists(SymlinkFileName): error_unable_to_replace_file(SymlinkFileName) create_symlinks.append((SymlinkFileName, TargetFileName)) if create_symlinks and not admin.isUserAdmin(): cmdline = getattr(sys, 'frozen', False) and sys.argv or None rc = admin.runAsAdmin(cmdline) sys.exit(rc) for (SymlinkFileName, TargetFileName) in create_symlinks: if os.path.islink(SymlinkFileName): os.remove(SymlinkFileName) sym_dirname = os.path.dirname(SymlinkFileName) if not os.path.isdir(sym_dirname): os.makedirs(sym_dirname) SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1 dwFlags = os.path.isdir( TargetFileName) and SYMBOLIC_LINK_FLAG_DIRECTORY or 0x0 win32file.CreateSymbolicLink(SymlinkFileName, TargetFileName, dwFlags)
def test_skip_symlinks(self): """ Test that symlinks are skipped """ self.render_config_template( path=os.path.abspath(self.working_dir) + "/log/*", ) os.mkdir(self.working_dir + "/log/") testfile = self.working_dir + "/log/test-2016.log" symlink_file = self.working_dir + "/log/test.log" # write first line with open(testfile, 'a') as file: file.write("Hello world\n") if os.name == "nt": import win32file win32file.CreateSymbolicLink(symlink_file, testfile, 0) else: os.symlink(testfile, symlink_file) filebeat = self.start_beat() # wait for file to be skipped self.wait_until( lambda: self.log_contains("skipped as it is a symlink"), max_timeout=10) # wait for log to be read self.wait_until( lambda: self.output_has(lines=1), max_timeout=15) time.sleep(5) filebeat.check_kill_and_wait() data = self.read_output() # Make sure there is only one entry, means it didn't follow the symlink assert len(data) == 1
def Execute(op): """実行処理。リトライが必要になった項目数を返す。""" try: f = op.instructions["from"] t = op.instructions["to"] except KeyError as e: log.error("Required parameter is not specified %s." % e) return False # end 必要な情報がない op.output["all_OK"] = True op.output["retry"]["from"] = [] op.output["retry"]["to"] = [] i = 0 retry = 0 for elem in op.instructions["from"]: try: flag = 0 if os.path.isdir(elem): flag = win32file.SYMBOLIC_LINK_FLAG_DIRECTORY # 相対パスで作成の場合 if op.instructions["relative"]: elem = os.path.relpath(elem, start=os.path.dirname(t[i])) win32file.CreateSymbolicLink( t[i], elem, flag | win32file.SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE ) # これで、昇格しなくてもできるのか? except win32file.error as err: if helper.CommonFailure(op, elem, err, log): appendRetry(op.output, elem, t[i]) continue # end except op.output["succeeded"] += 1 i += 1 # end 項目の数だけ if len(op.output["retry"]["from"]) > 0: op.output["retry"]["operation"] = VERB retry = len(op.output["retry"]["from"]) # end リトライあるか return retry
def symlink(source, link_name): os_symlink = getattr(os, "symlink", None) try: os_symlink(source, link_name) except: try: import ctypes csl = ctypes.windll.kernel32.CreateSymbolicLinkW csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32) csl.restype = ctypes.c_ubyte flags = 1 if os.path.isdir(source) else 0 if csl(link_name, source, flags) == 0: raise ctypes.WinError() except: try: import win32file win32file.CreateSymbolicLink(fileSrc, fileTarget, 1) except: print('unable to create symbolic link from [{src}] to [{dst}]'.format( src=source, dst=link_name))
def run(self, blocks, Filepath, lst): if os.path.exists(Filepath + '/ALL') == 0: os.makedirs(Filepath + '/ALL') if os.path.exists(Filepath + '/REPORT') == 0: os.makedirs(Filepath + '/REPORT') if os.path.exists(Filepath + '/' + str(datetime.now().year)) == 0: os.makedirs(Filepath + '/' + str(datetime.now().year)) for block in blocks: for code in block.share: self.complete = 0 if os.path.exists(Filepath + '/ALL/' + self.basic[code]) == 0: os.makedirs(Filepath + '/ALL/' + self.basic[code]) elif code not in lst: continue self.Parse(code, Filepath + '/ALL/' + self.basic[code] + '/') oldpwd = os.getcwd() for block in blocks: if os.path.exists(Filepath + '/REPORT/' + block.name) == 0: os.makedirs(Filepath + '/REPORT/' + block.name) os.chdir(Filepath + '/REPORT/' + block.name) for code in block.share: if os.path.exists(self.basic[code]) == 0: if (cmp(init.Platform(), "Linux") == 0): os.symlink('../../ALL/' + self.basic[code], self.basic[code]) else: path = os.path.abspath("../../ALL") win32file.CreateSymbolicLink( self.basic[code], path + '/' + self.basic[code], 1) os.chdir(oldpwd) self.analyse(Filepath, block, block.share, None, u'资产负债表.csv') self.analyse(Filepath, block, block.share, None, u'利润表.csv') self.Parse("", Filepath + '/' + str(datetime.now().year) + '/SH/') self.Parse("", Filepath + '/' + str(datetime.now().year) + '/SZ/') self.end()
shutil.copyfile('Stevefire.mdb.3', 'Stevefire.mdb.4') shutil.copyfile('Stevefire.mdb.2', 'Stevefire.mdb.3') subprocess.Popen( os.path.join('Tools', 'JETCOMP.exe') + ' -src:"Stevefire.mdb.2" -dest:"Stevefire.mdb" -w' + dbpassword).wait() # Enviroment setup regdecimalorg = winreg.QueryValueEx(registry, 'sDecimal')[0] regthousandorg = winreg.QueryValueEx(registry, 'sThousand')[0] winreg.SetValueEx(registry, 'sDecimal', 0, 1, '.') winreg.SetValueEx(registry, 'sThousand', 0, 1, ' ') if portable: subprocess.Popen('regsvr32 /s MSSTDFMT.DLL').wait() try: win32file.CreateSymbolicLink( os.path.splitdrive(os.getcwd())[0] + os.path.sep + 'Logs', os.path.join(os.getcwd(), 'Logs'), 1) except: pass # Starting Aurora time.sleep(1) show_image(random.choice(os.listdir('Background'))) aurora = subprocess.Popen('Aurora.exe') # Main event loop while aurora.poll() is None: clock.tick(1) for event in pygame.event.get(): if event.type == pygame.USEREVENT: pygame.mixer.music.load(random.choice(playlist))