Python os.R_OK Examples
The following are 30
code examples of os.R_OK().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
os
, or try the search function
.
Example #1
Source File: deploy-dashboard-vm.py From JetPack with Apache License 2.0 | 6 votes |
def create_floppy_image(vlock_filename, floppy_image): """ Creates the floppy image used to install the vlock file """ # Delete any existing image to start clean if os.access(floppy_image, os.R_OK): os.unlink(floppy_image) subprocess.check_call("mkfs.vfat -C {} 1440".format(floppy_image), shell=True) floppy_mnt = "/tmp/mnt-dashboard" os.mkdir(floppy_mnt) subprocess.check_call("mount -o loop {} {}".format(floppy_image, floppy_mnt), shell=True) shutil.copy(vlock_filename, os.path.join(floppy_mnt, "versionlock.list")) subprocess.check_call("umount {}".format(floppy_mnt), shell=True) os.rmdir(floppy_mnt)
Example #2
Source File: options.py From yatsm with MIT License | 6 votes |
def opt_resultdir(f): def callback(ctx, param, value): # Check if path qualifies alone if os.path.isdir(value): _value = value else: # Check if path relative to root qualifies _value = os.path.join(ctx.params['root'], value) if not os.path.isdir(_value): raise click.BadParameter('Cannot find result directory ' '"{d}"'.format(d=value)) if not os.access(_value, os.R_OK): raise click.BadParameter('Found result directory but cannot ' 'read from "{d}"'.format(d=_value)) return os.path.abspath(_value) return click.option('--result', '-r', default='YATSM', metavar='<directory>', show_default=True, help='Directory of results', callback=callback)(f) # CALLBACKS
Example #3
Source File: options.py From yatsm with MIT License | 6 votes |
def opt_exampleimg(f): def callback(ctx, param, value): # Check if file qualifies alone if os.path.isfile(value): _value = value else: # Check if path relative to root qualifies _value = os.path.join(ctx.params['root'], value) if not os.path.isfile(_value): raise click.BadParameter('Cannot find example image ' '"{f}"'.format(f=value)) if not os.access(_value, os.R_OK): raise click.BadParameter('Found example image but cannot ' 'read from "{f}"'.format(f=_value)) return os.path.abspath(_value) return click.option('--image', '-i', default='example_img', metavar='<image>', show_default=True, help='Example timeseries image', callback=callback)(f)
Example #4
Source File: cache.py From rekall with GNU General Public License v2.0 | 6 votes |
def GetCacheDir(session): """Returns the path of a usable cache directory.""" cache_dir = session.GetParameter("cache_dir") if cache_dir == None: return cache_dir cache_dir = os.path.expandvars(cache_dir) if not cache_dir: raise io_manager.IOManagerError( "Local profile cache is not configured - " "add a cache_dir parameter to ~/.rekallrc.") # Cache dir may be specified relative to the home directory. cache_dir = os.path.join(config.GetHomeDir(session), cache_dir) if not os.access(cache_dir, os.F_OK | os.R_OK | os.W_OK | os.X_OK): try: os.makedirs(cache_dir) except (IOError, OSError): raise io_manager.IOManagerError( "Unable to create or access cache directory %s" % cache_dir) return cache_dir
Example #5
Source File: application.py From pulseaudio-dlna with GNU General Public License v3.0 | 6 votes |
def read_device_config(self): for config_path in self.DEVICE_CONFIG_PATHS: config_file = os.path.join(config_path, self.DEVICE_CONFIG) if os.path.isfile(config_file) and \ os.access(config_file, os.R_OK): with open(config_file, 'r') as h: json_text = h.read().decode(self.ENCODING) logger.debug('Device configuration:\n{}'.format(json_text)) json_text = json_text.replace('\n', '') try: device_config = json.loads(json_text) logger.info( 'Loaded device config "{}"'.format(config_file)) return device_config except ValueError: logger.error( 'Unable to parse "{}"! ' 'Check the file for syntax errors ...'.format( config_file)) return None
Example #6
Source File: osquery.py From rekall with GNU General Public License v2.0 | 6 votes |
def try_to_find_osquery(self): extention = "" if platform.system() == "Windows": extention = ".exe" try: return resources.get_resource("osqueryi" + extention) except IOError as e: # Maybe it is installed on the system. if platform.system() == "Windows": result = r"c:\ProgramData\osquery\osqueryi.exe" if os.access(result, os.R_OK): return result else: # Try to find it somewhere on the system. return spawn.find_executable("osqueryi") raise e
Example #7
Source File: droidsample.py From droidlysis with MIT License | 6 votes |
def extract_kit_properties(self): """ Detects which kits are present in the sample currently analyzed Returns something like: ['apperhand', 'jackson', 'applovin', 'leadbolt', 'airpush'] """ list = [] if self.properties.filetype == droidutil.APK or self.properties.filetype == droidutil.DEX: smali_dir = os.path.join(self.outdir, "smali") if os.access(smali_dir, os.R_OK): for section in self.properties.kitsconfig.get_sections(): pattern_list = self.properties.kitsconfig.get_pattern(section).split('|') for pattern in pattern_list: if os.access(os.path.join(smali_dir, pattern), os.R_OK): if self.verbose: print("kits[%s] = True (detected pattern: %s)" % (section, pattern)) list.append(section) self.properties.kits[ section ] = True break # break one level return list
Example #8
Source File: droidsample.py From droidlysis with MIT License | 6 votes |
def extract_file_properties(self): """Extracts file size, nb of dirs and classes in smali dir""" if self.verbose: print("------------- Extracting file properties") self.properties.file_size = os.stat(self.absolute_filename).st_size if self.properties.file_size < 70000: self.properties.file_small = True smali_dir = os.path.join(self.outdir, "smali") if os.access(smali_dir, os.R_OK): self.properties.file_nb_dir, self.properties.file_nb_classes = droidutil.count_filedirs(smali_dir) if self.verbose: print( "Filesize: %d" % (self.properties.file_size)) print( "Is Small: %d" % (self.properties.file_small)) print( "Nb Class: %d" % (self.properties.file_nb_classes)) print( "Nb Dir : %d" % (self.properties.file_nb_dir))
Example #9
Source File: Image.py From pcocc with GNU General Public License v3.0 | 6 votes |
def read_vm_image_type(path): if not os.path.isfile(path): raise PcoccError("{} is not an image file".format(path)) if not os.access(path, os.R_OK): raise PcoccError("{} is not readable".format(path)) try: jsdata = subprocess.check_output(["qemu-img", "info","--output=json", path]) except subprocess.CalledProcessError: return None try: data = json.loads(jsdata) except Exception: return None return data.get("format", None)
Example #10
Source File: Image.py From pcocc with GNU General Public License v3.0 | 6 votes |
def read_vm_image_backing_file(path, full=False): if not os.path.isfile(path): raise PcoccError("{} is not an image file".format(path)) if not os.access(path, os.R_OK): raise PcoccError("{} is not readable".format(path)) try: jsdata = subprocess.check_output(["qemu-img", "info","--output=json", path]) except subprocess.CalledProcessError: return None try: data = json.loads(jsdata) except Exception: return None res = None if full: res = data.get("full-backing-filename", None) if not res: res = data.get("backing-filename", None) return res
Example #11
Source File: util.py From benchexec with Apache License 2.0 | 6 votes |
def check_msr(): """ Checks if the msr driver is loaded and if the user executing benchexec has the read and write permissions for msr. """ res = {"loaded": False, "write": False, "read": False} loaded_modules = subprocess.check_output(["lsmod"]).decode("utf-8").split("\n") if any("msr" in module for module in loaded_modules): res["loaded"] = True if res["loaded"]: cpu_dirs = os.listdir("/dev/cpu") cpu_dirs.remove("microcode") if all(os.access("/dev/cpu/{}/msr".format(cpu), os.R_OK) for cpu in cpu_dirs): res["read"] = True if all(os.access("/dev/cpu/{}/msr".format(cpu), os.W_OK) for cpu in cpu_dirs): res["write"] = True return res
Example #12
Source File: result_collections_test.py From rekall with GNU General Public License v2.0 | 6 votes |
def testCollectionAction(self): collection, final_path = self._make_collection() with collection.create_temp_file(): self.assertFalse(os.access(final_path, os.R_OK)) self.assertTrue(os.access(collection._filename, os.R_OK)) # Insert some data. collection.insert(c1=5, c2="foobar", c3=1.1) # Make sure the tempfile is removed and the final_path exists. self.assertFalse(os.access(collection._filename, os.R_OK)) self.assertTrue(os.access(final_path, os.R_OK)) # Re-open the collection for reading. with result_collections.GenericSQLiteCollection.load_from_location( collection.location, session=self.session) as read_collection: # This should reuse the final_path saving a local copy. self.assertEqual(read_collection._filename, final_path) # Query the collection. self.assertEqual([tuple(x) for x in read_collection.query()], [(5, "foobar", 1.1)])
Example #13
Source File: proc.py From stem with GNU Lesser General Public License v3.0 | 6 votes |
def test_connections(self): """ Checks for our control port in the stem.util.proc.connections output if we have one. """ runner = test.runner.get_runner() if test.runner.Torrc.PORT not in runner.get_options(): self.skiTestp('(no control port)') return elif not os.access('/proc/net/tcp', os.R_OK) or not os.access('/proc/net/udp', os.R_OK): self.skipTest('(proc lacks read permissions)') # making a controller connection so that we have something to query for with runner.get_tor_socket(): tor_pid = test.runner.get_runner().get_pid() for conn in proc.connections(tor_pid): if ('127.0.0.1', test.runner.CONTROL_PORT) == conn[:2]: return self.fail()
Example #14
Source File: generate_data.py From rtc-video-quality with Apache License 2.0 | 6 votes |
def clip_arg(clip): (file_root, file_ext) = os.path.splitext(clip) if file_ext == '.y4m': width = int(subprocess.check_output(["mediainfo", "--Inform=Video;%Width%", clip])) height = int(subprocess.check_output(["mediainfo", "--Inform=Video;%Height%", clip])) fps = float(subprocess.check_output(["mediainfo", "--Inform=Video;%FrameRate%", clip])) return {'input_file': clip, 'height': height, 'width': width, 'fps': fps, 'file_type': 'y4m'} # Make sure YUV files are correctly formatted + look readable before actually # running the script on them. clip_match = yuv_clip_pattern.match(clip) if not clip_match: raise argparse.ArgumentTypeError("Argument '%s' doesn't match input format.\n" % clip) input_file = clip_match.group(1) if not os.path.isfile(input_file) or not os.access(input_file, os.R_OK): raise argparse.ArgumentTypeError("'%s' is either not a file or cannot be opened for reading.\n" % input_file) return {'input_file': clip_match.group(1), 'width': int(clip_match.group(2)), 'height': int(clip_match.group(3)), 'fps' : float(clip_match.group(4)), 'file_type': 'yuv'}
Example #15
Source File: disasm.py From codimension with GNU General Public License v3.0 | 6 votes |
def getFileDisassembled(path, optimization): """Dsassembles a file""" if not os.path.exists(path): raise Exception("Cannot find " + path + " to disassemble") if not os.access(path, os.R_OK): raise Exception("No read permissions for " + path) tempPycFile = makeTempFile(suffix='.pyc') try: py_compile.compile(path, tempPycFile, doraise=True, optimize=optimization) except Exception as exc: safeUnlink(tempPycFile) raise Exception("Cannot disassemble file " + path + ': ' + str(exc)) try: result = getCompiledfileDisassembled(tempPycFile, path, optimization) except: safeUnlink(tempPycFile) raise safeUnlink(tempPycFile) return result
Example #16
Source File: generate_test_html.py From apple-emoji-linux with Apache License 2.0 | 6 votes |
def do_generate_fonts(template_file, font_basename, pairs, reuse=0, verbosity=1): out_woff = font_basename + '.woff' if reuse > 1 and os.path.isfile(out_woff) and os.access(out_woff, os.R_OK): if verbosity: print('Reusing ' + out_woff) return out_ttx = font_basename + '.ttx' if reuse == 0: add_svg_glyphs.add_image_glyphs(template_file, out_ttx, pairs, verbosity=verbosity) elif verbosity: print('Reusing ' + out_ttx) quiet=verbosity < 2 font = ttx.TTFont(flavor='woff', quiet=quiet) font.importXML(out_ttx, quiet=quiet) font.save(out_woff) if verbosity: print('Wrote ' + out_woff)
Example #17
Source File: campaign.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _kpm_file_path_is_valid(file_path): if not file_path: return False if not os.path.isfile(file_path) and os.access(file_path, os.R_OK): return False if not archive.is_archive(file_path): return False return True
Example #18
Source File: keys.py From sawtooth-core with Apache License 2.0 | 5 votes |
def load_identity_signer(key_dir, key_name): """Loads a private key from the key directory, based on a validator's identity. Args: key_dir (str): The path to the key directory. key_name (str): The name of the key to load. Returns: Signer: the cryptographic signer for the key """ key_path = os.path.join(key_dir, '{}.priv'.format(key_name)) if not os.path.exists(key_path): raise LocalConfigurationError( "No such signing key file: {}".format(key_path)) if not os.access(key_path, os.R_OK): raise LocalConfigurationError( "Key file is not readable: {}".format(key_path)) LOGGER.info('Loading signing key: %s', key_path) try: with open(key_path, 'r') as key_file: private_key_str = key_file.read().strip() except IOError as e: raise LocalConfigurationError( "Could not load key file: {}".format(str(e))) try: private_key = Secp256k1PrivateKey.from_hex(private_key_str) except signing.ParseError as e: raise LocalConfigurationError( "Invalid key in file {}: {}".format(key_path, str(e))) context = signing.create_context('secp256k1') crypto_factory = CryptoFactory(context) return crypto_factory.new_signer(private_key)
Example #19
Source File: validators.py From panoptes with Apache License 2.0 | 5 votes |
def valid_readable_path(cls, path): try: return True if (os.path.isdir(path) and os.access(path, os.R_OK)) else False except: return False
Example #20
Source File: debug.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def format_path_status(self, path): if not os.path.exists(path): return "File does not exist" if not os.path.isfile(path): return "Not a file" if not os.access(path, os.R_OK): return "File is not readable" return "File exists"
Example #21
Source File: validators.py From panoptes with Apache License 2.0 | 5 votes |
def valid_readable_file(cls, filename): try: return True if (os.path.isfile(filename) and os.access(filename, os.R_OK)) else False except: return False
Example #22
Source File: application.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_user_paths(self): app = application.KingPhisherClientApplication() for user_path in (app.user_data_path, app.user_library_path): self.assertIsNotNone(user_path) self.assertIsNotEmpty(user_path) self.assertTrue(os.path.isdir(user_path)) self.assertTrue(os.access(user_path, os.R_OK | os.W_OK)) self.assertEqual(user_path, os.path.abspath(user_path))
Example #23
Source File: ftp.py From dionaea with GNU General Public License v2.0 | 5 votes |
def apply_config(self, config): self.basedir = config.get("root") if self.basedir is None: raise ServiceConfigError("basedir not defined") if not os.path.isdir(self.basedir): raise ServiceConfigError("The basedir '%s' is not a directory", self.basedir) if not os.access(self.basedir, os.R_OK): raise ServiceConfigError("Unable to read files in the '%s' directory", self.basedir) self.response_msgs.update(config.get("response_messages", {}))
Example #24
Source File: cache.py From rekall with GNU General Public License v2.0 | 5 votes |
def io_manager(self): if not self.enabled: return cache_dir = os.path.expandvars( self.session.GetParameter("cache_dir", cached=False)) cache_dir = os.path.join(config.GetHomeDir(self.session), cache_dir) # Force the IO manager to be recreated if the cache dir has # changed. This allows the session to change it's cache directory on the # fly (which is actually done when setting it from the command line). if cache_dir != self.cache_dir: self._io_manager = None self.cache_dir = cache_dir if self._io_manager is None and cache_dir: # Cache dir may be specified relative to the home directory. if os.access(cache_dir, os.F_OK | os.R_OK | os.W_OK | os.X_OK): self._io_manager = PicklingDirectoryIOManager( "%s/sessions" % cache_dir, session=self.session, mode="w") self.cache_dir = cache_dir else: self.session.logging.warn( "Cache directory inaccessible. Disabling.") self.enabled = False return self._io_manager
Example #25
Source File: resources.py From rekall with GNU General Public License v2.0 | 5 votes |
def get_resource(filename, package="rekall-core", prefix="resources"): """Use the pkg_resources API to extract resources. This will extract into a temporary file in case the egg is compressed. Args: package: name of the package (e.g. rekall-core, rekall-gui). filename: The filename inside the package. prefix: The sub-directory in the source distribution which contains the resource. Returns: A path to the actual filename. """ target = _get_pkg_resource(filename, package, prefix) if target and os.access(target, os.R_OK): return target # Installing from wheel places data_files relative to sys.prefix and not # site-packages. If we can not find in site-packages, check sys.prefix # instead. # https://python-packaging-user-guide.readthedocs.io/en/latest/distributing/#data-files target = os.path.join(sys.prefix, prefix, filename) if target and os.access(target, os.R_OK): return target raise IOError("Unable to find resource %s" % filename)
Example #26
Source File: config_updater.py From rekall with GNU General Public License v2.0 | 5 votes |
def collect(self): """This should be an interactive script.""" self.config_dir = self.plugin_args.config_dir if not os.access(self.config_dir, os.R_OK): raise plugin.PluginError("Unable to write to config directory %s" % self.config_dir) for method in [self.generate_keys, self.write_config, self.write_manifest]: for x in method(): yield x yield dict(Message="Done!")
Example #27
Source File: cos_params_check.py From cos-python-sdk with MIT License | 5 votes |
def check_local_file_valid(self, local_path): if not os.path.exists(local_path): self._err_tips = 'local_file %s not exist!' % local_path return False if not os.path.isfile(local_path): self._err_tips = 'local_file %s is not regular file!' % local_path return False if not os.access(local_path, os.R_OK): self._err_tips = 'local_file %s is not readable!' % local_path return False return True # 检查分片大小有效
Example #28
Source File: types.py From jbox with MIT License | 5 votes |
def convert(self, value, param, ctx): rv = value is_dash = self.file_okay and self.allow_dash and rv in (b'-', '-') if not is_dash: if self.resolve_path: rv = os.path.realpath(rv) try: st = os.stat(rv) except OSError: if not self.exists: return self.coerce_path_result(rv) self.fail('%s "%s" does not exist.' % ( self.path_type, filename_to_ui(value) ), param, ctx) if not self.file_okay and stat.S_ISREG(st.st_mode): self.fail('%s "%s" is a file.' % ( self.path_type, filename_to_ui(value) ), param, ctx) if not self.dir_okay and stat.S_ISDIR(st.st_mode): self.fail('%s "%s" is a directory.' % ( self.path_type, filename_to_ui(value) ), param, ctx) if self.writable and not os.access(value, os.W_OK): self.fail('%s "%s" is not writable.' % ( self.path_type, filename_to_ui(value) ), param, ctx) if self.readable and not os.access(value, os.R_OK): self.fail('%s "%s" is not readable.' % ( self.path_type, filename_to_ui(value) ), param, ctx) return self.coerce_path_result(rv)
Example #29
Source File: __init__.py From jbox with MIT License | 5 votes |
def find_on_path(importer, path_item, only=False): """Yield distributions accessible on a sys.path directory""" path_item = _normalize_cached(path_item) if os.path.isdir(path_item) and os.access(path_item, os.R_OK): if _is_unpacked_egg(path_item): yield Distribution.from_filename( path_item, metadata=PathMetadata( path_item, os.path.join(path_item,'EGG-INFO') ) ) else: # scan for .egg and .egg-info in directory for entry in os.listdir(path_item): lower = entry.lower() if lower.endswith('.egg-info') or lower.endswith('.dist-info'): fullpath = os.path.join(path_item, entry) if os.path.isdir(fullpath): # egg-info directory, allow getting metadata metadata = PathMetadata(path_item, fullpath) else: metadata = FileMetadata(fullpath) yield Distribution.from_location( path_item, entry, metadata, precedence=DEVELOP_DIST ) elif not only and _is_unpacked_egg(entry): dists = find_distributions(os.path.join(path_item, entry)) for dist in dists: yield dist elif not only and lower.endswith('.egg-link'): with open(os.path.join(path_item, entry)) as entry_file: entry_lines = entry_file.readlines() for line in entry_lines: if not line.strip(): continue path = os.path.join(path_item, line.rstrip()) dists = find_distributions(path) for item in dists: yield item break
Example #30
Source File: iso.py From multibootusb with GNU General Public License v2.0 | 5 votes |
def is_readable(iso_link): return os.access(iso_link, os.R_OK)