Python stat.S_IRWXU Examples

The following are 30 code examples of stat.S_IRWXU(). 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 stat , or try the search function .
Example #1
Source File: utils_disk.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def close(self):
        error_context.context(
            "Creating unattended install CD image %s" % self.path)
        if os.path.exists(os.path.join(self.mount, 'isolinux')):
            # bootable cdrom
            f = open(os.path.join(self.mount, 'isolinux', 'isolinux.cfg'), 'w')
            f.write('default /isolinux/vmlinuz append initrd=/isolinux/'
                    'initrd.img %s\n' % self.extra_params)
            f.close()
            boot = '-b isolinux/isolinux.bin'
        else:
            # Not a bootable CDROM, using -kernel instead (eg.: arm64)
            boot = ''

        m_cmd = ('mkisofs -o %s %s -c isolinux/boot.cat -no-emul-boot '
                 '-boot-load-size 4 -boot-info-table -f -R -J -V -T %s'
                 % (self.path, boot, self.mount))
        process.run(m_cmd)
        os.chmod(self.path, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP |
                 stat.S_IROTH | stat.S_IXOTH)
        cleanup(self.mount)
        cleanup(self.source_cdrom)
        logging.debug("unattended install CD image %s successfully created",
                      self.path) 
Example #2
Source File: utils.py    From Att-ChemdNER with Apache License 2.0 6 votes vote down vote up
def get_perf(filename):
    ''' run conlleval.pl perl script to obtain
    precision/recall and F1 score '''
    _conlleval = PREFIX + 'conlleval'
    if not isfile(_conlleval):
        #download('http://www-etud.iro.umontreal.ca/~mesnilgr/atis/conlleval.pl') 
        os.system('wget https://www.comp.nus.edu.sg/%7Ekanmy/courses/practicalNLP_2008/packages/conlleval.pl')
        chmod('conlleval.pl', stat.S_IRWXU) # give the execute permissions
    
    out = []
    proc = subprocess.Popen(["perl", _conlleval], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    stdout, _ = proc.communicate(open(filename).read())
    for line in stdout.split('\n'):
        if 'accuracy' in line:
            out = line.split()
            break
    
    # out = ['accuracy:', '16.26%;', 'precision:', '0.00%;', 'recall:', '0.00%;', 'FB1:', '0.00']
    precision = float(out[3][:-2])
    recall    = float(out[5][:-2])
    f1score   = float(out[7])

    return {'p':precision, 'r':recall, 'f1':f1score} 
Example #3
Source File: generator_utils.py    From fine-lm with MIT License 6 votes vote down vote up
def gunzip_file(gz_path, new_path):
  """Unzips from gz_path into new_path.

  Args:
    gz_path: path to the zipped file.
    new_path: path to where the file will be unzipped.
  """
  if tf.gfile.Exists(new_path):
    tf.logging.info("File %s already exists, skipping unpacking" % new_path)
    return
  tf.logging.info("Unpacking %s to %s" % (gz_path, new_path))
  # We may be unpacking into a newly created directory, add write mode.
  mode = stat.S_IRWXU or stat.S_IXGRP or stat.S_IRGRP or stat.S_IROTH
  os.chmod(os.path.dirname(new_path), mode)
  with gzip.open(gz_path, "rb") as gz_file:
    with tf.gfile.GFile(new_path, mode="wb") as new_file:
      for line in gz_file:
        new_file.write(line) 
Example #4
Source File: test_blockdevice.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_world_permissions_not_reset_if_other_files_exist(self):
        """
        If files exist in the filesystem, permissions are not reset when the
        filesystem is remounted.
        """
        mountpoint = mountroot_for_test(self).child(b"mount-test")
        scenario = self._run_success_test(mountpoint)
        mountpoint.child(b"file").setContent(b"stuff")
        check_call([b"umount", mountpoint.path])
        mountpoint.chmod(S_IRWXU)
        mountpoint.restat()
        self.successResultOf(run_state_change(
            scenario.state_change(),
            scenario.deployer, InMemoryStatePersister()))
        self.assertEqual(mountpoint.getPermissions().shorthand(),
                         'rwx------') 
Example #5
Source File: cluster_setup.py    From flocker with Apache License 2.0 6 votes vote down vote up
def _ensure_empty_directory(path):
    """
    The path should not exist or it should be an empty directory.
    If the path does not exist then a new directory is created.

    :param FilePath path: The directory path to check or create.
    """
    if path.exists():
        if not path.isdir():
            raise UsageError("{} is not a directory".format(path.path))
        if path.listdir():
            raise UsageError("{} is not empty".format(path.path))
        return

    try:
        path.makedirs()
        path.chmod(stat.S_IRWXU)
    except OSError as e:
        raise UsageError(
            "Can not create {}. {}: {}.".format(path.path, e.filename,
                                                e.strerror)
        ) 
Example #6
Source File: test_shutil.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_copy_symlinks(self):
        tmp_dir = self.mkdtemp()
        src = os.path.join(tmp_dir, 'foo')
        dst = os.path.join(tmp_dir, 'bar')
        src_link = os.path.join(tmp_dir, 'baz')
        write_file(src, 'foo')
        os.symlink(src, src_link)
        if hasattr(os, 'lchmod'):
            os.lchmod(src_link, stat.S_IRWXU | stat.S_IRWXO)
        # don't follow
        shutil.copy(src_link, dst, follow_symlinks=True)
        self.assertFalse(os.path.islink(dst))
        self.assertEqual(read_file(src), read_file(dst))
        os.remove(dst)
        # follow
        shutil.copy(src_link, dst, follow_symlinks=False)
        self.assertTrue(os.path.islink(dst))
        self.assertEqual(os.readlink(dst), os.readlink(src_link))
        if hasattr(os, 'lchmod'):
            self.assertEqual(os.lstat(src_link).st_mode,
                             os.lstat(dst).st_mode) 
Example #7
Source File: generator_utils.py    From tensor2tensor with Apache License 2.0 6 votes vote down vote up
def gunzip_file(gz_path, new_path):
  """Unzips from gz_path into new_path.

  Args:
    gz_path: path to the zipped file.
    new_path: path to where the file will be unzipped.
  """
  if tf.gfile.Exists(new_path):
    tf.logging.info("File %s already exists, skipping unpacking" % new_path)
    return
  tf.logging.info("Unpacking %s to %s" % (gz_path, new_path))
  # We may be unpacking into a newly created directory, add write mode.
  mode = stat.S_IRWXU or stat.S_IXGRP or stat.S_IRGRP or stat.S_IROTH
  os.chmod(os.path.dirname(new_path), mode)
  with gzip.open(gz_path, "rb") as gz_file:
    with tf.gfile.GFile(new_path, mode="wb") as new_file:
      for line in gz_file:
        new_file.write(line) 
Example #8
Source File: generator_utils.py    From training_results_v0.5 with Apache License 2.0 6 votes vote down vote up
def gunzip_file(gz_path, new_path):
  """Unzips from gz_path into new_path.

  Args:
    gz_path: path to the zipped file.
    new_path: path to where the file will be unzipped.
  """
  if tf.gfile.Exists(new_path):
    tf.logging.info("File %s already exists, skipping unpacking" % new_path)
    return
  tf.logging.info("Unpacking %s to %s" % (gz_path, new_path))
  # We may be unpacking into a newly created directory, add write mode.
  mode = stat.S_IRWXU or stat.S_IXGRP or stat.S_IRGRP or stat.S_IROTH
  os.chmod(os.path.dirname(new_path), mode)
  with gzip.open(gz_path, "rb") as gz_file:
    with tf.gfile.GFile(new_path, mode="wb") as new_file:
      for line in gz_file:
        new_file.write(line) 
Example #9
Source File: generator_utils.py    From BERT with Apache License 2.0 6 votes vote down vote up
def gunzip_file(gz_path, new_path):
  """Unzips from gz_path into new_path.

  Args:
    gz_path: path to the zipped file.
    new_path: path to where the file will be unzipped.
  """
  if tf.gfile.Exists(new_path):
    tf.logging.info("File %s already exists, skipping unpacking" % new_path)
    return
  tf.logging.info("Unpacking %s to %s" % (gz_path, new_path))
  # We may be unpacking into a newly created directory, add write mode.
  mode = stat.S_IRWXU or stat.S_IXGRP or stat.S_IRGRP or stat.S_IROTH
  os.chmod(os.path.dirname(new_path), mode)
  with gzip.open(gz_path, "rb") as gz_file:
    with tf.gfile.GFile(new_path, mode="wb") as new_file:
      for line in gz_file:
        new_file.write(line) 
Example #10
Source File: fwaudit.py    From fwaudit with GNU General Public License v2.0 6 votes vote down vote up
def get_sudo_user_group_mode():
    '''TBW'''
    # XXX only need uid, gid, and file mode for sudo case...
    new_uid = int(os.environ.get('SUDO_UID'))
    if new_uid is None:
        error('Unable to obtain SUDO_UID')
        return False
    #debug('new UID via SUDO_UID: ' + str(new_uid))
    new_gid = int(os.environ.get('SUDO_GID'))
    if new_gid is None:
        error('Unable to obtain SUDO_GID')
        return False
    #debug('new GID via SUDO_GID: ' + str(new_gid))
    # new_dir_mode = (stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IWGRP|stat.S_IROTH|stat.S_IWOTH)
    rwx_mode = (stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO)
    new_dir_mode = rwx_mode
    #debug('new dir mode: ' + str(new_dir_mode))
    return (new_dir_mode, new_uid, new_gid) 
Example #11
Source File: test_pkg_resources.py    From pkg_resources with MIT License 6 votes vote down vote up
def env(self, tmpdir):
        """
        Create a package environment, similar to a virtualenv,
        in which packages are installed.
        """

        class Environment(str):
            pass

        env = Environment(tmpdir)
        tmpdir.chmod(stat.S_IRWXU)
        subs = 'home', 'lib', 'scripts', 'data', 'egg-base'
        env.paths = dict(
            (dirname, str(tmpdir / dirname))
            for dirname in subs
        )
        list(map(os.mkdir, env.paths.values()))
        return env 
Example #12
Source File: util.py    From benchexec with Apache License 2.0 6 votes vote down vote up
def rmtree(path, ignore_errors=False, onerror=None):
    """Same as shutil.rmtree, but supports directories without write or execute permissions."""
    if ignore_errors:

        def onerror(*args):
            pass

    elif onerror is None:

        def onerror(*args):
            raise

    for root, dirs, _unused_files in os.walk(path):
        for directory in dirs:
            try:
                abs_directory = os.path.join(root, directory)
                os.chmod(abs_directory, stat.S_IRWXU)
            except OSError as e:
                onerror(os.chmod, abs_directory, e)
    shutil.rmtree(path, ignore_errors=ignore_errors, onerror=onerror) 
Example #13
Source File: test_shutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_copy2_symlinks(self):
        tmp_dir = self.mkdtemp()
        src = os.path.join(tmp_dir, 'foo')
        dst = os.path.join(tmp_dir, 'bar')
        src_link = os.path.join(tmp_dir, 'baz')
        write_file(src, 'foo')
        os.symlink(src, src_link)
        if hasattr(os, 'lchmod'):
            os.lchmod(src_link, stat.S_IRWXU | stat.S_IRWXO)
        if hasattr(os, 'lchflags') and hasattr(stat, 'UF_NODUMP'):
            os.lchflags(src_link, stat.UF_NODUMP)
        src_stat = os.stat(src)
        src_link_stat = os.lstat(src_link)
        # follow
        shutil.copy2(src_link, dst, follow_symlinks=True)
        self.assertFalse(os.path.islink(dst))
        self.assertEqual(read_file(src), read_file(dst))
        os.remove(dst)
        # don't follow
        shutil.copy2(src_link, dst, follow_symlinks=False)
        self.assertTrue(os.path.islink(dst))
        self.assertEqual(os.readlink(dst), os.readlink(src_link))
        dst_stat = os.lstat(dst)
        if os.utime in os.supports_follow_symlinks:
            for attr in 'st_atime', 'st_mtime':
                # The modification times may be truncated in the new file.
                self.assertLessEqual(getattr(src_link_stat, attr),
                                     getattr(dst_stat, attr) + 1)
        if hasattr(os, 'lchmod'):
            self.assertEqual(src_link_stat.st_mode, dst_stat.st_mode)
            self.assertNotEqual(src_stat.st_mode, dst_stat.st_mode)
        if hasattr(os, 'lchflags') and hasattr(src_link_stat, 'st_flags'):
            self.assertEqual(src_link_stat.st_flags, dst_stat.st_flags) 
Example #14
Source File: fileoperations.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def remove_execute_access_from_group_and_other_users(location):
    os.chmod(location, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH) 
Example #15
Source File: test__osx_support.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test__read_output(self):
        if self.env['PATH']:
            self.env['PATH'] = self.env['PATH'] + ':'
        self.env['PATH'] = self.env['PATH'] + os.path.abspath(self.temp_path_dir)
        test.support.unlink(self.prog_name)
        self.addCleanup(test.support.unlink, self.prog_name)
        with open(self.prog_name, 'w') as f:
            f.write("#!/bin/sh\n/bin/echo ExpectedOutput\n")
        os.chmod(self.prog_name, stat.S_IRWXU)
        self.assertEqual('ExpectedOutput',
                            _osx_support._read_output(self.prog_name)) 
Example #16
Source File: test__osx_support.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test__find_appropriate_compiler(self):
        compilers = (
                        ('gcc-test', 'i686-apple-darwin11-llvm-gcc-4.2'),
                        ('clang', 'clang version 3.1'),
                    )
        config_vars = {
        'CC': 'gcc-test -pthreads',
        'CXX': 'cc++-test',
        'CFLAGS': '-fno-strict-aliasing  -g -O3 -arch ppc -arch i386  ',
        'LDFLAGS': '-arch ppc -arch i386   -g',
        'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk',
        'BLDSHARED': 'gcc-test -bundle -arch ppc -arch i386 -g',
        'LDSHARED': 'gcc-test -bundle -arch ppc -arch i386 '
                        '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g',
        }
        expected_vars = {
        'CC': 'clang -pthreads',
        'CXX': 'clang++',
        'CFLAGS': '-fno-strict-aliasing  -g -O3 -arch ppc -arch i386  ',
        'LDFLAGS': '-arch ppc -arch i386   -g',
        'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk',
        'BLDSHARED': 'clang -bundle -arch ppc -arch i386 -g',
        'LDSHARED': 'clang -bundle -arch ppc -arch i386 '
                        '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g',
        }
        self.add_expected_saved_initial_values(config_vars, expected_vars)

        suffix = (':' + self.env['PATH']) if self.env['PATH'] else ''
        self.env['PATH'] = os.path.abspath(self.temp_path_dir) + suffix
        for c_name, c_output in compilers:
            test.support.unlink(c_name)
            self.addCleanup(test.support.unlink, c_name)
            with open(c_name, 'w') as f:
                f.write("#!/bin/sh\n/bin/echo " + c_output)
            os.chmod(c_name, stat.S_IRWXU)
        self.assertEqual(expected_vars,
                            _osx_support._find_appropriate_compiler(
                                    config_vars)) 
Example #17
Source File: test__osx_support.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test__remove_unsupported_archs(self):
        config_vars = {
        'CC': 'clang',
        'CFLAGS': '-fno-strict-aliasing  -g -O3 -arch ppc -arch i386  ',
        'LDFLAGS': '-arch ppc -arch i386   -g',
        'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk',
        'BLDSHARED': 'gcc-4.0 -bundle  -arch ppc -arch i386 -g',
        'LDSHARED': 'gcc-4.0 -bundle  -arch ppc -arch i386 '
                        '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g',
        }
        expected_vars = {
        'CC': 'clang',
        'CFLAGS': '-fno-strict-aliasing  -g -O3  -arch i386  ',
        'LDFLAGS': ' -arch i386   -g',
        'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk',
        'BLDSHARED': 'gcc-4.0 -bundle   -arch i386 -g',
        'LDSHARED': 'gcc-4.0 -bundle   -arch i386 '
                        '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g',
        }
        self.add_expected_saved_initial_values(config_vars, expected_vars)

        suffix = (':' + self.env['PATH']) if self.env['PATH'] else ''
        self.env['PATH'] = os.path.abspath(self.temp_path_dir) + suffix
        c_name = 'clang'
        test.support.unlink(c_name)
        self.addCleanup(test.support.unlink, c_name)
        # exit status 255 means no PPC support in this compiler chain
        with open(c_name, 'w') as f:
            f.write("#!/bin/sh\nexit 255")
        os.chmod(c_name, stat.S_IRWXU)
        self.assertEqual(expected_vars,
                            _osx_support._remove_unsupported_archs(
                                    config_vars)) 
Example #18
Source File: test_shutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_copymode_symlink_to_symlink(self):
        tmp_dir = self.mkdtemp()
        src = os.path.join(tmp_dir, 'foo')
        dst = os.path.join(tmp_dir, 'bar')
        src_link = os.path.join(tmp_dir, 'baz')
        dst_link = os.path.join(tmp_dir, 'quux')
        write_file(src, 'foo')
        write_file(dst, 'foo')
        os.symlink(src, src_link)
        os.symlink(dst, dst_link)
        os.chmod(src, stat.S_IRWXU|stat.S_IRWXG)
        os.chmod(dst, stat.S_IRWXU)
        os.lchmod(src_link, stat.S_IRWXO|stat.S_IRWXG)
        # link to link
        os.lchmod(dst_link, stat.S_IRWXO)
        shutil.copymode(src_link, dst_link, follow_symlinks=False)
        self.assertEqual(os.lstat(src_link).st_mode,
                         os.lstat(dst_link).st_mode)
        self.assertNotEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
        # src link - use chmod
        os.lchmod(dst_link, stat.S_IRWXO)
        shutil.copymode(src_link, dst, follow_symlinks=False)
        self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
        # dst link - use chmod
        os.lchmod(dst_link, stat.S_IRWXO)
        shutil.copymode(src, dst_link, follow_symlinks=False)
        self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode) 
Example #19
Source File: test_posix.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_chmod_dir_fd(self):
        os.chmod(support.TESTFN, stat.S_IRUSR)

        f = posix.open(posix.getcwd(), posix.O_RDONLY)
        try:
            posix.chmod(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)

            s = posix.stat(support.TESTFN)
            self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
        finally:
            posix.close(f) 
Example #20
Source File: blockdevice.py    From flocker with Apache License 2.0 5 votes vote down vote up
def run(self, deployer, state_persister):
        """
        Run the system ``mount`` tool to mount this change's volume's block
        device.  The volume must be attached to this node.
        """
        # Create the directory where a device will be mounted.
        # The directory's parent's permissions will be set to only allow access
        # by owner, to limit access by other users on the node.
        try:
            self.mountpoint.makedirs()
        except OSError as e:
            if e.errno != EEXIST:
                return fail()
        self.mountpoint.parent().chmod(S_IRWXU)

        # This should be asynchronous.  FLOC-1797
        deployer.block_device_manager.mount(self.device_path, self.mountpoint)

        # Remove lost+found to ensure filesystems always start out empty.
        # Mounted filesystem is also made world
        # writeable/readable/executable since we can't predict what user a
        # container will run as.  We make sure we change mounted
        # filesystem's root directory permissions, so we only do this
        # after the filesystem is mounted.  If other files exist we don't
        # bother with either change, since at that point user has modified
        # the volume and we don't want to undo their changes by mistake
        # (e.g. postgres doesn't like world-writeable directories once
        # it's initialized).

        # A better way is described in
        # https://clusterhq.atlassian.net/browse/FLOC-2074
        lostfound = self.mountpoint.child(b"lost+found")
        if self.mountpoint.children() == [lostfound]:
            lostfound.remove()
            self.mountpoint.chmod(S_IRWXU | S_IRWXG | S_IRWXO)
            self.mountpoint.restat()

        return succeed(None) 
Example #21
Source File: service.py    From flocker with Apache License 2.0 5 votes vote down vote up
def _make_public(self, filesystem):
        """
        Make a filesystem publically readable/writeable/executable.

        A better alternative will be implemented in
        https://clusterhq.atlassian.net/browse/FLOC-34

        :param filesystem: A ``IFilesystem`` provider.
        """
        filesystem.get_path().chmod(
            # 0o777 the long way:
            stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) 
Example #22
Source File: test_sftp.py    From mock-ssh-server with MIT License 5 votes vote down vote up
def test_chmod(sftp_client, tmp_dir):
    test_file = os.path.join(tmp_dir, "foo")
    open(test_file, "w").write("X")
    sftp_client.chmod(test_file, 0o600)
    st = os.stat(test_file)
    check_bits = stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO
    assert st.st_mode & check_bits == 0o600 
Example #23
Source File: fileoperations.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def set_all_unrestricted_permissions(location):
    """
    Set permissions so that user, group, and others all have read,
    write and execute permissions (chmod 777).
    :param location: Full location of either a folder or a location
    """
    os.chmod(location, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) 
Example #24
Source File: main.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _install_service(self):
        daemon_files = [
            ['daemon.in', '/etc/init.d/teleport'],
            ['start.sh.in', os.path.join(self._install_path, 'start.sh')],
            ['stop.sh.in', os.path.join(self._install_path, 'stop.sh')],
            ['status.sh.in', os.path.join(self._install_path, 'status.sh')],
        ]

        for _d in daemon_files:
            cc.v('process [{}] to [{}]'.format(_d[0], _d[1]))
            _orig_file = os.path.join(env.root_path, 'daemon', _d[0])
            with open(_orig_file, 'r') as f:
                _text = f.read()
                _text = _text.format(daemon_path=self._install_path)

            with open(_d[1], 'w') as f:
                f.write(_text)

            if not os.path.exists(_d[1]):
                raise RuntimeError('can not generate daemon file [{}].'.format(_d[1]))

            # owner: RWX, group: RX, others: RX
            os.chmod(_d[1], stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)

        # create symbolic link
        os.symlink('/etc/init.d/teleport', '/etc/rc2.d/S95teleport')
        os.symlink('/etc/init.d/teleport', '/etc/rc3.d/S95teleport')
        os.symlink('/etc/init.d/teleport', '/etc/rc4.d/S95teleport')
        os.symlink('/etc/init.d/teleport', '/etc/rc5.d/S95teleport') 
Example #25
Source File: test_cli.py    From saltyrtc-server-python with MIT License 5 votes vote down vote up
def test_generate_key(self, cli, tmpdir):
        keyfile = tmpdir.join('keyfile.key')
        await cli('generate', str(keyfile))

        # Check length
        key = binascii.unhexlify(keyfile.read())
        assert len(key) == 32

        # Check permissions
        stat_result = os.stat(str(keyfile))
        permissions = stat_result.st_mode
        assert permissions & stat.S_IRWXU == stat.S_IRUSR | stat.S_IWUSR 
Example #26
Source File: test_adbapi.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def startDB(self):
        import kinterbasdb
        self.DB_NAME = os.path.join(self.DB_DIR, DBTestConnector.DB_NAME)
        os.chmod(self.DB_DIR, stat.S_IRWXU + stat.S_IRWXG + stat.S_IRWXO)
        sql = 'create database "%s" user "%s" password "%s"'
        sql %= (self.DB_NAME, self.DB_USER, self.DB_PASS);
        conn = kinterbasdb.create_database(sql)
        conn.close() 
Example #27
Source File: testutils.py    From pythonfinder with MIT License 5 votes vote down vote up
def set_write_bit(fn):
    # type: (str) -> None
    """
    Set read-write permissions for the current user on the target path.  Fail silently
    if the path doesn't exist.

    :param str fn: The target filename or path
    :return: None
    """

    if not os.path.exists(fn):
        return
    file_stat = os.stat(fn).st_mode
    os.chmod(fn, file_stat | stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
    if not os.path.isdir(fn):
        for path in [fn, os.path.dirname(fn)]:
            try:
                os.chflags(path, 0)
            except AttributeError:
                pass
        return None
    for root, dirs, files in os.walk(fn, topdown=False):
        for dir_ in [os.path.join(root, d) for d in dirs]:
            set_write_bit(dir_)
        for file_ in [os.path.join(root, f) for f in files]:
            set_write_bit(file_) 
Example #28
Source File: test__osx_support.py    From oss-ftp with MIT License 5 votes vote down vote up
def test__find_appropriate_compiler(self):
        compilers = (
                        ('gcc-test', 'i686-apple-darwin11-llvm-gcc-4.2'),
                        ('clang', 'clang version 3.1'),
                    )
        config_vars = {
        'CC': 'gcc-test -pthreads',
        'CXX': 'cc++-test',
        'CFLAGS': '-fno-strict-aliasing  -g -O3 -arch ppc -arch i386  ',
        'LDFLAGS': '-arch ppc -arch i386   -g',
        'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk',
        'BLDSHARED': 'gcc-test -bundle -arch ppc -arch i386 -g',
        'LDSHARED': 'gcc-test -bundle -arch ppc -arch i386 '
                        '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g',
        }
        expected_vars = {
        'CC': 'clang -pthreads',
        'CXX': 'clang++',
        'CFLAGS': '-fno-strict-aliasing  -g -O3 -arch ppc -arch i386  ',
        'LDFLAGS': '-arch ppc -arch i386   -g',
        'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk',
        'BLDSHARED': 'clang -bundle -arch ppc -arch i386 -g',
        'LDSHARED': 'clang -bundle -arch ppc -arch i386 '
                        '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g',
        }
        self.add_expected_saved_initial_values(config_vars, expected_vars)

        suffix = (':' + self.env['PATH']) if self.env['PATH'] else ''
        self.env['PATH'] = os.path.abspath(self.temp_path_dir) + suffix
        for c_name, c_output in compilers:
            test.test_support.unlink(c_name)
            self.addCleanup(test.test_support.unlink, c_name)
            with open(c_name, 'w') as f:
                f.write("#!/bin/sh\n/bin/echo " + c_output)
            os.chmod(c_name, stat.S_IRWXU)
        self.assertEqual(expected_vars,
                            _osx_support._find_appropriate_compiler(
                                    config_vars)) 
Example #29
Source File: test__osx_support.py    From oss-ftp with MIT License 5 votes vote down vote up
def test__read_output(self):
        if self.env['PATH']:
            self.env['PATH'] = self.env['PATH'] + ':'
        self.env['PATH'] = self.env['PATH'] + os.path.abspath(self.temp_path_dir)
        test.test_support.unlink(self.prog_name)
        self.addCleanup(test.test_support.unlink, self.prog_name)
        with open(self.prog_name, 'w') as f:
            f.write("#!/bin/sh\n/bin/echo ExpectedOutput\n")
        os.chmod(self.prog_name, stat.S_IRWXU)
        self.assertEqual('ExpectedOutput',
                            _osx_support._read_output(self.prog_name)) 
Example #30
Source File: test__osx_support.py    From oss-ftp with MIT License 5 votes vote down vote up
def test__find_executable(self):
        if self.env['PATH']:
            self.env['PATH'] = self.env['PATH'] + ':'
        self.env['PATH'] = self.env['PATH'] + os.path.abspath(self.temp_path_dir)
        test.test_support.unlink(self.prog_name)
        self.assertIsNone(_osx_support._find_executable(self.prog_name))
        self.addCleanup(test.test_support.unlink, self.prog_name)
        with open(self.prog_name, 'w') as f:
            f.write("#!/bin/sh\n/bin/echo OK\n")
        os.chmod(self.prog_name, stat.S_IRWXU)
        self.assertEqual(self.prog_name,
                            _osx_support._find_executable(self.prog_name))