os.

Here are the examples of the python api os. taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 101

Project: plinth
Source File: random_seek.py
View license
def seek_rand(keyfile, seedfile):
    try:
        with open(keyfile, 'r') as f:
            app_id = f.read()
        log.debug('Read private key from %s' % keyfile)
    except Exception, err:
        log.debug('Exception: %s' % err.message)
        app_id = plinth.Switch.new_key()
        umask = os.umask(0177)

Example 102

Project: pydoop
Source File: common_hdfs_tests.py
View license
    def chmod_w_string(self):
        path = self._make_random_dir()
        self.fs.chmod(path, 0500)
        # each user
        self.__set_and_check_perm(path, "u+w", 0700)
        self.__set_and_check_perm(path, "g+w", 0720)
        self.__set_and_check_perm(path, "o+w", 0722)
        # each permission mode
        self.__set_and_check_perm(path, "o+r", 0726)
        self.__set_and_check_perm(path, "o+x", 0727)
        # subtract operation, and multiple permission modes
        self.__set_and_check_perm(path, "o-rwx", 0720)
        # multiple users
        self.__set_and_check_perm(path, "ugo-rwx", 0000)
        # 'a' user
        self.__set_and_check_perm(path, "a+r", 0444)
        # blank user -- should respect the user's umask
        umask = os.umask(0007)

Example 103

Project: livecd-tools
Source File: kickstart.py
View license
    def write_hosts(self, hostname):
        localline = ""
        if hostname and hostname != "localhost.localdomain":
            localline += hostname + " "
            l = hostname.split(".")
            if len(l) > 1:
                localline += l[0] + " "
        localline += "localhost.localdomain localhost"

        path = self.path("/etc/hosts")
        f = file(path, "w+")
        os.chmod(path, 0644)

Example 104

Project: terminal-tools
Source File: runimage.py
View license
def install_pulldocker():
    url = 'https://www.terminal.com/pulldocker.tgz'
    try:
        subprocess.call(['wget', '--no-check-certificate', url])
        tfile = tarfile.open("pulldocker.tgz", 'r:gz')
        tfile.extractall('.')
        shutil.copy2('pulldocker','/usr/local/bin/pulldocker')
        os.chmod('/usr/local/bin/pulldocker',0755)

Example 105

Project: canape
Source File: config.py
View license
    def _store_pypirc(self, username, password):
        """Creates a default .pypirc file."""
        rc = self._get_rc_file()
        f = open(rc, 'w')
        try:
            f.write(DEFAULT_PYPIRC % (username, password))
        finally:
            f.close()
        try:
            os.chmod(rc, 0600)
        except OSError:
            # should do something better here
            pass

Example 106

Project: storyboard
Source File: credentials.py
View license
    def save(self, file_path):
        """
        Persist a Session Token to a file in JSON format.

        :type path: str
        :param path: The fully qualified path to the file where the
            the Session Token data should be written.  Any previous
            data in the file will be overwritten.  To help protect
            the credentials contained in the file, the permissions
            of the file will be set to readable/writable by owner only.
        """
        fp = open(file_path, 'wb')
        json.dump(self.to_dict(), fp)
        fp.close()
        os.chmod(file_path, 0600)

Example 107

Project: pymo
Source File: test_dumbdbm.py
View license
    def test_dumbdbm_creation_mode(self):
        # On platforms without chmod, don't do anything.
        if not (hasattr(os, 'chmod') and hasattr(os, 'umask')):
            return

        try:
            old_umask = os.umask(0002)
            f = dumbdbm.open(_fname, 'c', 0637)

Example 108

Project: imagrium
Source File: test_tempfile.py
View license
        def __init__(self, dir, pre, suf):
            self.name = tempfile.mktemp(dir=dir, prefix=pre, suffix=suf)
            # Create the file.  This will raise an exception if it's
            # mysteriously appeared in the meanwhile.
            os.close(os.open(self.name, self._bflags, 0600))
            # XXX: test_mktemp.tearDown expects the file to have been deleted
            # (via __del__) by the time it's called, which is CPython specific
            # garbage collection behavior. We need to delete it now in Jython
            self._unlink(self.name)

Example 109

Project: aws_py
Source File: fabfile.py
View license
def connect_script(node_name, node):
    filename = 'ssh_' + node_name
    command = "ssh -i %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %[email protected]%s\n"
    command = command % (node.ssh_key_file, node.ssh_user, node.hostname)

    with open(filename, 'w') as script:
        script.write('#!/bin/sh\n')
        script.write(command)

    os.chmod(filename, 0755)

Example 110

Project: django-compositepks
Source File: tests.py
View license
    def test_readonly_root(self):
        """Permission errors are not swallowed"""
        os.chmod(temp_storage.location, 0500)
        try:
            self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
        except OSError, err:
            self.assertEquals(err.errno, errno.EACCES)
        except Exception, err:
            self.fail("OSError [Errno %s] not raised." % errno.EACCES)

Example 111

Project: aws_vpc_py
Source File: fabfile.py
View license
def connect_script(host):
    filename = 'connect_' + host.name
    command = 'ssh -i %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %[email protected]%s\n'
    command = command % (host.keyfile, host.user, host.public_ip)

    with open(filename, 'w') as script:
        script.write('#!/bin/sh\n')
        script.write(command)

    os.chmod(filename, 0755)

Example 112

Project: rockstor-core
Source File: email_client.py
View license
def update_postfix(smtp_server, port, revert=False):
    fh, npath = mkstemp()
    with open(MAIN_CF) as mfo, open(npath, 'w') as tfo:
        rockstor_section = False
        for line in mfo.readlines():
            if (re.match(HEADER, line)
                is not None):
                rockstor_section = True
                rockstor_postfix_config(tfo, smtp_server, port, revert)
                break
            else:
                tfo.write(line)
        if (rockstor_section is False):
            rockstor_postfix_config(tfo, smtp_server, port, revert)
    move(npath, MAIN_CF)
    os.chmod(MAIN_CF, 0644)

Example 113

Project: trezor-emu
Source File: transport_pipe.py
View license
    def _open(self):
        if self.is_device:
            self.filename_read = self.device + '.to'
            self.filename_write = self.device + '.from'

            os.mkfifo(self.filename_read, 0600)
            os.mkfifo(self.filename_write, 0600)
        else:
            self.filename_read = self.device + '.from'
            self.filename_write = self.device + '.to'

            if not os.path.exists(self.filename_write):
                raise Exception("Not connected")

        self.write_fd = os.open(self.filename_write, os.O_RDWR)  # |os.O_NONBLOCK)
        self.write_f = os.fdopen(self.write_fd, 'w+')

        self.read_fd = os.open(self.filename_read, os.O_RDWR)  # |os.O_NONBLOCK)
        self.read_f = os.fdopen(self.read_fd, 'rb')

Example 114

Project: nubo
Source File: config.py
View license
def write_config(values):
    old_values = read_config()

    updated = dict(old_values.items() + values.items())
    open(CONFFILE, 'w').write(json.dumps(updated, indent=4))

    os.chmod(CONFFILE, 0600)

Example 115

Project: honeything
Source File: download.py
View license
  def _MakeDirsIgnoreError(self, directory):
    """Make sure a directory exists."""
    try:
      os.makedirs(directory, 0755)
    except OSError:
      pass

Example 116

Project: Bicho
Source File: utils.py
View license
def create_dir(dir):
    try:
        os.mkdir(dir, 0700)
    except OSError, e:
        if e.errno == errno.EEXIST:
            if not os.path.isdir(dir):
                raise
        else:
            raise

Example 117

View license
    def __init__(self, domain, commonName=None, security_dir=None, force=False, readonly=False):
        self.configfile = None
        self.commonName = commonName or 'runtime'
        self.config = ConfigParser.SafeConfigParser()
        self.config.optionxform = str
        os.umask(0077)

Example 118

Project: rockstor-core
Source File: services.py
View license
def refresh_afp_config(afpl):
    fo, npath = mkstemp()
    with open(AFP_CONFIG) as afo, open(npath, 'w') as tfo:
        rockstor_section = False
        for line in afo.readlines():
            if (re.match(';####BEGIN: Rockstor AFP CONFIG####', line)
                    is not None):
                rockstor_section = True
                rockstor_afp_config(tfo, afpl)
                break
            else:
                tfo.write(line)
        if (rockstor_section is False):
            rockstor_afp_config(tfo, afpl)
    shutil.move(npath, AFP_CONFIG)
    os.chmod(AFP_CONFIG, 0644)

Example 119

Project: trigger
Source File: test_tacacsrc.py
View license
    def test_perms(self):
        """Test that permissions are being enforced."""
        t = Testing_Tacacsrc()
        fname = t.file_name
        # First make sure perms are set
        old_perms = self._get_perms(fname)
        self.assertEqual(old_perms, RIGHT_PERMS)
        os.chmod(fname, 0666) # Make it world-writable

Example 120

Project: silvereye
Source File: nc.py
View license
    def postAction(self, anaconda):
        silvereye.InstallClass.postAction(self, anaconda)
        # XXX: use proper constants for path names
        shutil.copyfile('/tmp/updates/scripts/eucalyptus-nc-config.sh',
                        '/mnt/sysimage/usr/local/sbin/eucalyptus-nc-config.sh')
        os.chmod('/mnt/sysimage/usr/local/sbin/eucalyptus-nc-config.sh', 0770)

Example 121

Project: gitosis
Source File: serve.py
View license
    def handle_args(self, parser, cfg, options, args):
        try:
            (user,) = args
        except ValueError:
            parser.error('Missing argument USER.')

        main_log = logging.getLogger('gitosis.serve.main')
        os.umask(0022)

Example 122

Project: feat
Source File: log.py
View license
def reopenOutputFiles():
    """
    Reopens the stdout and stderr output files, as set by
    L{outputToFiles}.
    """
    if not _stdout and not _stderr:
        debug('log', 'told to reopen log files, but log files not set')
        return

    def reopen(name, fileno, *args):
        oldmask = os.umask(0026)

Example 123

Project: avocado-vt
Source File: utils_disk.py
View license
    @error_context.context_aware
    def close(self):
        error_context.context(
            "Creating unattended install CD image %s" % self.path)
        g_cmd = ('mkisofs -o %s -max-iso9660-filenames '
                 '-relaxed-filenames -D --input-charset iso8859-1 '
                 '%s' % (self.path, self.mount))
        process.run(g_cmd, verbose=DEBUG)

        os.chmod(self.path, 0755)
        cleanup(self.mount)
        logging.debug("unattended install CD image %s successfully created",
                      self.path)

Example 124

View license
def _init_pending_transfer_db():
    """Create the pending transfers table if it doesn't already exist."""
    db_create_str = (
        "CREATE TABLE pending_transfers (code VARCHAR(5) PRIMARY KEY,"
        " time FLOAT, from_acct INTEGER, to_acct INTEGER, amount INTEGER);")
    try:
        with open(config_db['pending_transfer_db_path']) as _:
            pass
    except IOError:
        db = sqlite3.connect(config_db['pending_transfer_db_path'])
        db.execute(db_create_str)
        db.commit()
        db.close()
        # Make the DB world-writable.
        os.chmod(config_db['pending_transfer_db_path'], 0777)

Example 125

Project: bh2014
Source File: config.py
View license
    def _store_pypirc(self, username, password):
        """Creates a default .pypirc file."""
        rc = self._get_rc_file()
        f = open(rc, 'w')
        try:
            f.write(DEFAULT_PYPIRC % (username, password))
        finally:
            f.close()
        try:
            os.chmod(rc, 0600)
        except OSError:
            # should do something better here
            pass

Example 126

Project: oleviewdotnet
Source File: config.py
View license
    def _store_pypirc(self, username, password):
        """Creates a default .pypirc file."""
        rc = self._get_rc_file()
        f = open(rc, 'w')
        try:
            f.write(DEFAULT_PYPIRC % (username, password))
        finally:
            f.close()
        try:
            os.chmod(rc, 0600)
        except OSError:
            # should do something better here
            pass

Example 127

Project: ldaptor
Source File: test_ldiftree.py
View license
    def test_children_noAccess_dir_noExec(self):
        os.chmod(self.meta.path, 0600)
        d = self.meta.children()
        def eb(fail):
            fail.trap(IOError)
            self.assertEquals(fail.value.errno, errno.EACCES)
            os.chmod(self.meta.path, 0755)
        d.addCallbacks(testutil.mustRaise, eb)
        return d

Example 128

Project: conary
Source File: datastore.py
View license
    @staticmethod
    def _fchmod(fd, mode=0666):
        global _cached_umask
        if _cached_umask is None:
            # The only way to get the current umask is to change the umask and
            # then change it back.
            _cached_umask = os.umask(022)
            os.umask(_cached_umask)

Example 129

Project: conveyor
Source File: address.py
View license
        def listen(self):
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            s.setblocking(True)
            s.bind(self._path)
            os.chmod(self._path, 0666)
            s.listen(socket.SOMAXCONN)
            listener = conveyor.listener.PipeListener(self._path, s)
            return listener

Example 130

Project: scalarizr
Source File: __init__.py
View license
def sync_globals(glob_vars=None):
    if linux.os.windows:
        return
    if not glob_vars:
        queryenv = bus.queryenv_service
        glob_vars = queryenv.list_global_variables()
    globals_path = '/etc/profile.d/scalr_globals.sh'
    with codecs.open(globals_path, 'w+', encoding='utf-8') as fp:
        for k, v in glob_vars['public'].items():
            v = v.replace('"', '\\"')
            if isinstance(v, str):
                v = v.decode('utf-8')
            fp.write(u'export %s="%s"\n' % (k, v))
    os.chmod(globals_path, 0644)

Example 131

Project: Veil-Evasion
Source File: config.py
View license
    def _store_pypirc(self, username, password):
        """Creates a default .pypirc file."""
        rc = self._get_rc_file()
        f = open(rc, 'w')
        try:
            f.write(DEFAULT_PYPIRC % (username, password))
        finally:
            f.close()
        try:
            os.chmod(rc, 0600)
        except OSError:
            # should do something better here
            pass

Example 132

Project: viewfinder
Source File: run-ui-tests.py
View license
def ExecuteTest():
  """Run the tests.
  """
  app_id = GetApplicationId(_SCHEME['ios'])
  test_name = options.testname
  if test_name:
    Setup(test_name)
    test_dir = '%s/results/current/%s/%s' % (_BASE_PATH, options.conf, test_name)
    os.makedirs(test_dir, 0755)

Example 133

Project: ferry
Source File: sparkconfig.py
View license
    def _generate_spark_env(self, new_config_dir, master):
        """
        Generate the core-site configuration for a local filesystem. 
        """
        in_file = open(self.template_dir + '/spark_env.sh.template', 'r')
        out_file = open(new_config_dir + '/spark_env.sh', 'w+')

        changes = { "MASTER": master }
        for line in in_file:
            s = Template(line).substitute(changes)
            out_file.write(s)

        in_file.close()
        out_file.close()

        # The Spark env file is a shell script, so should be
        # executable by all. 
        os.chmod(new_config_dir + '/spark_env.sh', 0755)

Example 134

Project: virt-manager
Source File: initrdinject.py
View license
def perform_initrd_injections(initrd, injections, scratchdir):
    """
    Insert files into the root directory of the initial ram disk
    """
    if not injections:
        return

    if _rhel4_initrd_inject(initrd, injections):
        return

    tempdir = tempfile.mkdtemp(dir=scratchdir)
    os.chmod(tempdir, 0775)

Example 135

Project: simoorg
Source File: test_atropos.py
View license
    def setUp(self):
        try:
            shutil.copyfile(DUMMY_HEALTHCHECK_SRC, DUMMY_HEALTHCHECK_DST)
            os.chmod(DUMMY_HEALTHCHECK_DST, 0744)
        except IOError:
            print ("Unable to write to file " + DUMMY_HEALTHCHECK_DST)
        with open(TEST_FATEBOOK_FILE) as c_fd:
            self.config_ = yaml.load(c_fd)
        test_config_file = TEST_CONFIG_DIR + "atropos_config.yaml"
        with open(test_config_file) as config_fd:
            self.test_config = yaml.load(config_fd)
        self.logger = Logger.Logger()

Example 136

Project: catnip
Source File: sandbox.py
View license
  def _EnvironmentSwap(self):
    @contextlib.contextmanager
    def Swapper():
      self._log.info('setting umask/PATH')
      last_umask = os.umask(022)
      last_path = os.environ['PATH']

Example 137

Project: simoorg
Source File: test_moirai.py
View license
    def setUp(self):
        try:
            shutil.copyfile(DUMMY_HEALTHCHECK_SRC, DUMMY_HEALTHCHECK_DST)
            os.chmod(DUMMY_HEALTHCHECK_DST, 0744)
        except:
            print ("Unable to write to file " + DUMMY_HEALTHCHECK_DST)
            raise

Example 138

Project: synctool
Source File: object.py
View license
    def set_permissions(self):
        '''set access permission bits equal to source'''

        verbose(dryrun_msg('  os.chmod(%s, %04o)' %
                           (self.name, self.stat.mode & 07777)))
        unix_out('chmod 0%o %s' % (self.stat.mode & 07777, self.name))
        if not synctool.lib.DRY_RUN:
            try:
                os.chmod(self.name, self.stat.mode & 07777)
            except OSError as err:
                error('failed to chmod %04o %s : %s' %
                      (self.stat.mode & 07777, self.name, err.strerror))
                terse(TERSE_FAIL, 'mode %s' % self.name)

Example 139

Project: usblock
Source File: registrar.py
View license
    def load_config(self):
        '''Read the config file and get all listed
        devices.
        '''
        self._create_conf_dir()
        self._config = ConfigParser.ConfigParser()
        opened_files = self._config.read(self._path)
        if not len(opened_files):
            try:
                file_handle = open(self._path, "w+")
                file_handle.close()
                os.chmod(self._path, 0600)
            except IOError:
                raise Exception("Failed to open %s for writing." %
                                self._path)
        else:
            self._set_values()

Example 140

Project: synctool
Source File: object.py
View license
    def create(self):
        '''create directory'''

        if synctool.lib.path_exists(self.name):
            # it can happen that the dir already exists
            # due to recursion in visit() + VNode.mkdir_basepath()
            # So this is double checked for dirs that did not exist
            return

        verbose(dryrun_msg('  os.mkdir(%s)' % self.name))
        unix_out('mkdir %s' % self.name)
        terse(synctool.lib.TERSE_MKDIR, self.name)
        if not synctool.lib.DRY_RUN:
            try:
                os.mkdir(self.name, self.stat.mode & 07777)
            except OSError as err:
                error('failed to make directory %s : %s' % (self.name,
                                                            err.strerror))
                terse(TERSE_FAIL, 'mkdir %s' % self.name)

Example 141

Project: mysql-tools
Source File: utils.py
View license
def GenerateKey(public_keyfile, private_keyfile, key_bits=2048):
  """Generate an RSA key pair."""
  public = open(public_keyfile, 'w')
  os.fchmod(public.fileno(), 0400)
  private = open(private_keyfile, 'w')
  os.fchmod(private.fileno(), 0400)
  key = keyfactory.generateRSAKey(key_bits)
  public.write(key.writeXMLPublicKey() + '\n')
  private.write(key.write() + '\n')

Example 142

Project: nanomon
Source File: test_basic.py
View license
    def test_Basic(self):
        config_file = 'basic_config'
        checker = Checker(self, config_file)

        #  make checker fail
        with open('test_checker', 'w') as fp:
            fp.write('#!/bin/bash\n\nfalse\n')
        os.chmod('test_checker', 0755)

Example 143

Project: lago
Source File: prefix.py
View license
    @staticmethod
    def _run_qemu(qemu_cmd, disk_path):
        ret = utils.run_command(qemu_cmd)
        if ret.code != 0:
            raise RuntimeError(
                'Failed to create image, qemu-img returned %d:\n'
                'out:%s\nerr:%s' % ret,
            )
        # To avoid losing access to the file
        os.chmod(disk_path, 0666)

Example 144

Project: rex
Source File: cgc_exploit.py
View license
    def dump_binary(self, filename=None):
        c_code = self.dump_c()
        compiled_result = compilerex.compile_from_string(c_code)
        if filename is not None:
            with open(filename, 'w') as f:
                f.write(compiled_result)
            os.chmod(filename, 0755)
            return None

Example 145

Project: Plex-Remote-Transcoder
Source File: prt.py
View license
def install_transcoder():
    prt_remote = find_executable("prt_remote")
    if not prt_remote:
        print "Couldn't find `prt_remote` executable"
        return

    print "Renaming original transcoder"
    if rename_transcoder():
        try:
            shutil.copyfile(prt_remote, get_transcoder_path(ORIGINAL_TRANSCODER_NAME))
            os.chmod(get_transcoder_path(ORIGINAL_TRANSCODER_NAME), 0755)
        except Exception, e:
            print "Error installing new transcoder: %s" % str(e)

Example 146

Project: pulp
Source File: test_launcher.py
View license
    @mock.patch('os.path.expanduser')
    @mock.patch('sys.stderr')
    def test_exists_with_wrong_perms(self, mock_stderr, mock_expanduser):
        mock_expanduser.return_value = self.pulppath
        os.mkdir(self.pulppath, 0755)

        launcher.ensure_user_pulp_dir()

        self.assertEqual(mock_stderr.write.call_count, 1)
        message = mock_stderr.write.call_args[0][0]
        # make sure it prints a warning to stderr
        self.assertTrue(message.startswith('Warning:'))

Example 147

Project: focus
Source File: test_apps.py
View license
    def test__on_taskstart(self):
        """ AppRun.on_taskstart: configured apps are launched.
            """

        # make a copy of 'sh' shell binary so we have something unique that we
        # can have plugin launch and check for accurately
        bin_file = self.make_file()
        self.plugin.paths['start'] = set([bin_file])
        shutil.copyfile('/bin/sh', bin_file)
        os.chmod(bin_file, 0700)  # set exec.. silly macosx

Example 148

Project: enigma2
Source File: mytest.py
View license
def NTPserverChanged(configelement):
	if config.misc.NTPserver.value == "pool.ntp.org":
		return
	print "[NTPDATE] save /etc/default/ntpdate"
	f = open("/etc/default/ntpdate", "w")
	f.write('NTPSERVERS="' + config.misc.NTPserver.value + '"')
	f.close()
	os.chmod("/etc/default/ntpdate", 0755)

Example 149

Project: nagcat
Source File: nagios_api.py
View license
    def _threaded_command(self, cmd_time, cmd_list, force=False):
        """Write out out the temporary command file from a thread to
        avoid any momentary delays that may be caused by creating
        creating the file.
        """

        spool_fd, spool_path = tempfile.mkstemp(dir=self.spool_dir)
        try:
            try:
                os.fchmod(spool_fd, 0644)
                for cmd in cmd_list:
                    text = self._format_command(cmd_time, *cmd)
                    log.trace("Writing Nagios command to spool: %s", text)
                    os.write(spool_fd, text)

Example 150

Project: autotest
Source File: build_externals.py
View license
def main():
    """
    Find all ExternalPackage classes defined in this file and ask them to
    fetch, build and install themselves.
    """
    logging_manager.configure_logging(BuildExternalsLoggingConfig(),
                                      verbose=True)
    os.umask(022)