Пример #1
0
	def do_next (self):
		if self.current>self.maximum:
			raise StopIteration

		if self.base==16:
			lgth=len(hex(self.maximum).replace("0x",""))
			num=hex(self.current).replace("0x","")	
		elif self.base==8:
			lgth=len(oct(self.maximum)[1:])
			num=oct(self.current)[1:]
		else:
			lgth=len(str(self.maximum))
			num=str(self.current)	

		pl="%"+str(lgth)+"s"
		pl= pl % (num)
		fz=self.suffix+pl.replace(" ","0")

		if self.width:
			fz="%0"+str(self.width)+"s"
			fz=fz % (pl)
		else:
			fz=pl

		fz=fz.replace(" ","0")

		self.current+=self.step
		return self.suffix+fz
Пример #2
0
    def __init__(self, fullpath, owner=None):
        for check in self.checks:
            if not check( fullpath ):
                raise http.Http404('Path not found `%s` or IADMIN_FM_ROOT not configured in settings' % fullpath)

        self.name = self.basename = os.path.basename(fullpath) or ROOT_NAME
        self.parent = os.path.dirname(fullpath)

        self.absolute_path = fullpath # file system absolute path
        self.relative_path = utils.relpath(fullpath, utils.get_document_root())

        self.path = self.relative_path.split('/')
        self.mime = mimetypes.guess_type(self.absolute_path, False)[0] or ''
        self.can_read = os.access(self.absolute_path, os.R_OK)
        self.can_write = os.access(self.absolute_path, os.W_OK)
        self.is_link = os.path.islink(self.absolute_path)
        try:
            itemstat = os.stat(self.absolute_path)
            self.user = getpwuid(itemstat.st_uid)[0]
            self.group = getgrgid(itemstat.st_gid)[0]
            self.size = itemstat.st_size
            self.ctime = datetime.fromtimestamp(itemstat.st_ctime)
            self.mtime = datetime.fromtimestamp(itemstat.st_mtime)
            octs = "%04d" % int(oct(itemstat.st_mode & 0777))
            self.perms_numeric = octs
            self.perms = "%s%s%s" % (perms[int(octs[1])],
                                     perms[int(octs[2])],
                                     perms[int(octs[3])])
        except:
            self.user = self.group = self.perms_numeric = self.perms = ''
            self.size = self.ctime = self.mtime = None
    def test_post(self):

        uploaded_path = os.path.join(self.F_SUBFOLDER.path, 'testimage.jpg')
        self.assertFalse(site.storage.exists(uploaded_path))

        url = '?'.join([self.url, urlencode({'folder': self.F_SUBFOLDER.path_relative_directory})])

        with open(self.STATIC_IMG_PATH, "rb") as f:
            file_size = os.path.getsize(f.name)
            response = self.client.post(url, data={'qqfile': 'testimage.jpg', 'file': f}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        # Check we get OK response
        self.assertTrue(response.status_code == 200)
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(data["filename"], "testimage.jpg")
        self.assertEqual(data["temp_filename"], None)

        # Check the file now exists
        self.testfile = FileObject(uploaded_path, site=site)
        self.assertTrue(site.storage.exists(uploaded_path))

        # Check the file has the correct size
        self.assertTrue(file_size == site.storage.size(uploaded_path))

        # Check permissions
        # TODO: break out into separate test
        if DEFAULT_PERMISSIONS is not None:
            permissions_default = oct(DEFAULT_PERMISSIONS)
            permissions_file = oct(os.stat(self.testfile.path_full).st_mode & 0o777)
            self.assertTrue(permissions_default == permissions_file)
Пример #4
0
def gen_items (rootdir, verbose=False):
    global locked_dirs

    if os.path.isfile(rootdir):

        file_path = rootdir

        dir_path = os.path.dirname(rootdir)
        file_name = os.path.basename(rootdir)

        perm = oct(os.lstat(file_path).st_mode & 0o777).rjust(4, '0')[1:]

        action = get_file_action(perm, dir_path, file_name)

        if (action != 'ign' and action != perm) or verbose:
            yield (action, 'f', perm, dir_path + '/' + file_name)

        return

    for dir_path, sub_dirs, files in os.walk(rootdir):
        perm = oct(os.lstat(dir_path).st_mode & 0o777).rjust(4, '0')[1:]

        action = get_dir_action(perm, dir_path, sub_dirs, files)

        if action == 'ign' or action == 'non':
            if verbose:
                for i in ignore_tree(dir_path):
                    yield i
            del sub_dirs[:]
        else:
            if action != perm or (action == perm and verbose):
                yield (action, 'd', perm, dir_path)

            ign_sub_dir_list = get_ignore_sub_dirs_list(sub_dirs)

            if verbose:
                for i in ign_sub_dir_list:
                    for j in ignore_tree(dir_path + '/' + i):
                        yield j

            for i in ign_sub_dir_list:
                sub_dirs.remove(i)

            # may have problem to walk
            for i in sub_dirs:
                perm = oct(os.lstat(dir_path + '/' + i).st_mode & 0o777).rjust(4, '0')[1:]
                if re.match(r'^.*[0123].*$', perm):
                    locked_dirs.append(
                        '[{perm}] {itemname}'.format(
                        perm=perm,
                        itemname=dir_path+'/'+i) )

            for file_name in files:
                perm = oct(os.lstat(dir_path + '/' + file_name).st_mode & 0o777).rjust(4, '0')[1:]
                action = get_file_action(perm, dir_path, file_name)

                output = False

                if (action != 'ign' and action != perm) or verbose:
                    yield (action, 'f', perm, dir_path + '/' + file_name)
Пример #5
0
 def SetMode(self, mode):
     """Set the mode value of the display"""
     if self._mode == DEC_MODE:
         tmp = self.GetValAsInt()
         if mode == OCT_MODE:
             val = oct(tmp)
         elif mode == HEX_MODE:
             val = str(hex(tmp))
             val = '0x' + val.lstrip('0x').upper()
         else:
             val = self._val
     elif self._mode == OCT_MODE:
         tmp = self._val.lstrip('0').rstrip('L')
         if not len(tmp):
             tmp = '0'
         if mode == DEC_MODE and len(tmp):
             val = int(tmp, 8)
         elif mode == HEX_MODE and len(tmp):
             val = str(hex(int(tmp, 8)))
             val = '0x' + val.lstrip('0x').upper()
         else:
             val = self._val
     else:
         tmp = self._val.lstrip('0x').rstrip('L')
         if not len(tmp):
             tmp = '0'
         if mode == DEC_MODE:
             val = int(tmp, 16)
         elif mode == OCT_MODE:
             val = oct(int(tmp, 16))
         else:
             val = self._val
     self._val = str(val)
     self._mode = mode
     self.Refresh()
Пример #6
0
def check_ftype(objs):
    """ Checks the filetype, permissions and uid,gid of the
    pkgdg object(objs) sent to it. Returns two dicts: ed and pd
    (the error_dict with a descriptive explanantion of the problem
    if present, none otherwise, the perm_dict with a description of
    the incoorect perms if present, none otherwise
    """
    ed = None
    pd = None
    lst_var = os.lstat(objs["path"])
    ftype, perm = get_ftype_and_perm(lst_var.st_mode)
    if ftype != objs["kind"]:
        ed = dict([('path', objs["path"]),
                ('problem', 'Expected %s, Got %s' %(objs["kind"], ftype)),
                ('pkgdb_entry', objs)])
    pdtmp = ''
    if perm!=objs["mode"]:
        pdtmp+="\nExpected MODE: %s, Got: %s" %(oct(objs["mode"]), oct(perm))
    if lst_var.st_uid!=objs["uid"]:
        pdtmp+="\nExpected UID: %s, Got: %s" %(objs["uid"], lst_var.st_uid)
    if lst_var.st_gid!=objs["gid"]:
        pdtmp+="\nExpected GID: %s, Got: %s" %(objs["gid"], lst_var.st_gid)
    if pdtmp and not objs["path"].endswith(".pyc"):
        pd = dict([('path', objs["path"]),
                ('problem', pdtmp[1:]),
                ('pkgdb_entry', objs)])
    return ed, pd
Пример #7
0
 def assert_file_permissions(self, expected_permissions, name):
     full_path = self.full_path(name)
     actual_file_permissions = stat.S_IMODE(os.stat(full_path).st_mode)
     if sys.platform != "win32":
         self.assertEqual(oct(expected_permissions), oct(actual_file_permissions))
     else:
         self.assertEqual(oct(0o666), oct(actual_file_permissions))
Пример #8
0
    def test_something_typeConversions(self):
        import math

        self.assertEqual(complex(1), complex(Something(1)))
        self.assertEqual(oct(1), oct(Something(1)))
        self.assertEqual(hex(16), hex(Something(16)))
        self.assertEqual(math.trunc(math.pi), math.trunc(maybe(math.pi)))
Пример #9
0
 def chmod ( self, path, mode ):
     print '*** chmod', path, oct(mode)
     from DIRAC.DataManagementSystem.Client.FileCatalogClientCLI import FileCatalogClientCLI
     from COMDIRAC.Interfaces import DCatalog
     FileCatalogClientCLI( DCatalog().catalog ).do_chmod(str(oct(mode&0777))[1:]+" "+path)
     #return -errno.ENOSYS
     return 0
Пример #10
0
 def format(self, checktype, val):
     """ python 3: Octal literals are no longer of the form 0720; use 0o720 instead.
     """
     if sys.version_info > (3,0):
         return '0' + str(oct(val))[2:] if checktype=='mode' else str(val)
     else:
         return str(oct(val)) if checktype=='mode' else str(val)
Пример #11
0
    def createdir(self, path, mode=None):
        parts = path.split("/")
        tmpPath = ""
        for part in parts:
            tmpPath = os.path.join(tmpPath, part)
            if tmpPath == "":
                tmpPath = "/"

            try:
                if mode:
                    self._iop.mkdir(tmpPath, mode)
                else:
                    self._iop.mkdir(tmpPath)
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise
                else:
                    if tmpPath == path and mode is not None:
                        statinfo = self._iop.stat(path)
                        curMode = statinfo[stat.ST_MODE]
                        if curMode != mode:
                            raise OSError(errno.EPERM,
                                          ("Existing %s "
                                           "permissions %s are not as "
                                           "requested %s") % (path,
                                                              oct(curMode),
                                                              oct(mode)))
Пример #12
0
def test_jobsub_setup():
  # User 'test' triggers the setup of the examples.
  # 'hue' home will be deleted, the examples installed in the new one
  # and 'test' will try to access them.
  cluster = pseudo_hdfs4.shared_cluster()
  cluster.fs.setuser('test')

  username = '******'
  home_dir = '/user/%s/' % username
  finish = conf.REMOTE_DATA_DIR.set_for_testing('%s/jobsub' % home_dir)

  try:
    data_dir = conf.REMOTE_DATA_DIR.get()
    cluster.fs.setuser(cluster.fs.superuser)
    if cluster.fs.exists(home_dir):
      cluster.fs.rmtree(home_dir)
    cluster.fs.setuser('test')

    jobsub_setup.Command().handle()

    cluster.fs.setuser('test')
    stats = cluster.fs.stats(home_dir)
    assert_equal(stats['user'], username)
    assert_equal(oct(stats['mode']), '040755') #04 because is a dir

    stats = cluster.fs.stats(data_dir)
    assert_equal(stats['user'], username)
    assert_equal(oct(stats['mode']), '041777')

    stats = cluster.fs.listdir_stats(data_dir)
    assert_equal(len(stats), 2) # 2 files inside
  finally:
    finish()
def test_do_upload(test):
    """
    Test the actual uploading
    """

    url = reverse('%s:fb_do_upload' % test.site_name)
    url = '?'.join([url, urlencode({'folder': test.tmpdir.path_relative_directory, 'qqfile': 'testimage.jpg'})])

    with open(os.path.join(FILEBROWSER_PATH, 'static/filebrowser/img/testimage.jpg'), "rb") as f:
        file_size = os.path.getsize(f.name)
        response = test.c.post(url, data={'qqfile': 'testimage.jpg', 'file': f}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')

    # Check we get OK response
    test.assertTrue(response.status_code == 200)

    # Check the file now exists
    path = os.path.join(test.tmpdir.path, 'testimage.jpg')
    test.testfile = FileObject(path, site=test.site)
    test.assertTrue(test.site.storage.exists(path))

    # Check the file has the correct size
    test.assertTrue(file_size == test.site.storage.size(path))

    # Check permissions
    if DEFAULT_PERMISSIONS is not None:
        permissions_default = oct(DEFAULT_PERMISSIONS)
        permissions_file = oct(os.stat(test.testfile.path_full).st_mode & 777)
        test.assertTrue(permissions_default == permissions_file)
Пример #14
0
	def posix_chmod_parser(self,test_path):
		log_path = "../logs/log_run.log"
		self.test_dir = test_path  # path to test dir with files and dirs (different chmod)
		print
		print "    [Get directories and files in test directory " + self.test_dir + "] :"
		self.log_add(log_path,"[Get directories and files in test directory " + self.test_dir + "] :")
		print
		for dir_n, dir_nn, file_nn in os.walk(self.test_dir):
			blank = 0
			for dir2 in dir_nn:			# Get directories
				dir_true = os.path.join(dir_n, dir2)
				mode_d = int(oct(os.stat(dir_true).st_mode)[-3:])  # get chmod (permissions) ___uga
				print "    Get dir: " + dir_true + " permissions: " + str(mode_d)
				self.log_add(log_path,"Get dir: " + dir_true + " permissions: " + str(mode_d))
				blank += 1
				self.dirs.append(dir_true)
				if mode_d in range (444,446):	#444 (r--r--r--) .. 446 (r--r--rw-)
					self.dir_r.append(dir_true)
				elif mode_d in range (666,778): #666 (rw-rw-rw-) .. 777 (rwxrwxrwx))
					self.dir_rw.append(dir_true)
			for file_n in file_nn:			# Get files
				file_true = os.path.join(dir_n, file_n)
				mode_f = int(oct(os.stat(file_true).st_mode)[-3:])			# get chmod (permissions) ___uga
				print "    Get file: " + file_true + " permissions: " + str(mode_f)
				self.log_add(log_path,"Get file: " + file_true + " permissions: " + str(mode_f))
				self.files.append(file_true) #444 = -r--r--r--  any can read  /  #666 = -rw-rw-rw-  any can read and write
				if mode_f in range(444, 446):  # 444 .. 446
					self.file_r.append(file_true)
				elif mode_f in range(666, 778):  # 666 .. 777
					self.file_rw.append(file_true)
		# add markers into the typles in order to find it in future tests
		self.files_chmod["r"] = self.file_r
		self.files_chmod["rw"] = self.file_rw
		self.dirs_chmod["r"] = self.dir_r
		self.dirs_chmod["rw"] = self.dir_rw
    def test_copy_real_file(self):
        """Typical usage of deprecated copyRealFile()"""
        # Use this file as the file to be copied to the fake file system
        fake_file = self.copyRealFile(self.filepath)

        self.assertTrue(
            'class TestCopyOrAddRealFile(TestPyfakefsUnittestBase)'
            in self.real_string_contents,
            'Verify real file string contents')
        self.assertTrue(
            b'class TestCopyOrAddRealFile(TestPyfakefsUnittestBase)'
            in self.real_byte_contents,
            'Verify real file byte contents')

        # note that real_string_contents may differ to fake_file.contents
        # due to newline conversions in open()
        self.assertEqual(fake_file.byte_contents, self.real_byte_contents)

        self.assertEqual(oct(fake_file.st_mode), oct(self.real_stat.st_mode))
        self.assertEqual(fake_file.st_size, self.real_stat.st_size)
        self.assertAlmostEqual(fake_file.st_ctime,
                               self.real_stat.st_ctime, places=5)
        self.assertAlmostEqual(fake_file.st_atime,
                               self.real_stat.st_atime, places=5)
        self.assertLess(fake_file.st_atime, self.real_stat.st_atime + 10)
        self.assertAlmostEqual(fake_file.st_mtime,
                               self.real_stat.st_mtime, places=5)
        self.assertEqual(fake_file.st_uid, self.real_stat.st_uid)
        self.assertEqual(fake_file.st_gid, self.real_stat.st_gid)
Пример #16
0
    def __init__(self):
        self.ssl_cert_file_path = SSL_CERT_FILE_PATH
        self.ssl_key_file_path = SSL_KEY_FILE_PATH
        self.proxy_file_path = VOMS_PROXY_FILE_PATH
        self.lifetime = 43200
        self.voms = 'atlas:/atlas/Role=production'

        if not os.path.isfile(self.ssl_cert_file_path):
            raise Exception("MyProxyClient: SSL certificate file %s is not found" % self.ssl_cert_file_path)
        if not os.path.isfile(self.ssl_key_file_path):
            raise Exception("MyProxyClient: SSL key file %s is not found" % self.ssl_key_file_path)

        self.required_ssl_cert_file_access = 0444
        self.required_ssl_key_file_access = 0400
        self.required_proxy_file_access = 0600

        ssl_cert_file_access = stat.S_IMODE(os.stat(self.ssl_cert_file_path).st_mode)
        ssl_key_file_access = stat.S_IMODE(os.stat(self.ssl_key_file_path).st_mode)

        if ssl_cert_file_access != self.required_ssl_cert_file_access:
            raise Exception("MyProxyClient: wrong permissions on SSL certificate file %s (%s). Required: %s" %
                            (self.ssl_cert_file_path,
                             oct(ssl_cert_file_access),
                             oct(self.required_ssl_cert_file_access)))
        if ssl_key_file_access != self.required_ssl_key_file_access:
            raise Exception("MyProxyClient: wrong permissions on SSL key file %s (%s). Required: %s" %
                            (self.ssl_key_file_path, oct(ssl_key_file_access), oct(self.required_ssl_key_file_access)))
Пример #17
0
def generate_specfile_pair( data, output_fd=None ):
   """
   Generate a <Pair> section of the specfile.
   If output_fd is not None, write it to output_fd.
   Otherwise, return the string.
   """
   
   return_string = False 

   if output_fd is None:
      return_string = True
      output_fd = StringIO.StringIO()
   
   output_fd.write("  <Pair reval=\"%s\">\n" % data.reval_sec )
   
   if data.__class__.__name__ == "AG_file_data":
      # this is a file 
      output_fd.write("    <File perm=\"%s\">%s</File>\n" % (oct(data.perm), data.path))
      output_fd.write("    <Query type=\"%s\">%s</Query>\n" % (data.driver, data.query_string))
                              
   else:
      # this is a directory 
      output_fd.write("    <Dir perm=\"%s\">%s</Dir>\n" % (oct(data.perm), data.path))
      output_fd.write("    <Query type=\"%s\"></Query>\n" % (data.driver))
      
   output_fd.write("  </Pair>\n")
   
   if return_string:
      return output_fd.getvalue()
   else:
      return True 
Пример #18
0
    def testUnaryOps(self):
        testme = AllTests()

        callLst[:] = []
        -testme
        self.assertCallStack([('__neg__', (testme,))])
        callLst[:] = []
        +testme
        self.assertCallStack([('__pos__', (testme,))])
        callLst[:] = []
        abs(testme)
        self.assertCallStack([('__abs__', (testme,))])
        callLst[:] = []
        int(testme)
        self.assertCallStack([('__int__', (testme,))])
        callLst[:] = []
        long(testme)
        self.assertCallStack([('__long__', (testme,))])
        callLst[:] = []
        float(testme)
        self.assertCallStack([('__float__', (testme,))])
        callLst[:] = []
        oct(testme)
        self.assertCallStack([('__oct__', (testme,))])
        callLst[:] = []
        hex(testme)
        self.assertCallStack([('__hex__', (testme,))])
Пример #19
0
def index(directory,trim,excludedirs,excludefiles):
    stack = [directory]
    files = []
    while stack:
        directory = stack.pop()
        directory = os.path.abspath(directory)
        for file in os.listdir(directory):
            fullname = os.path.join(directory, file)
            truncname = fullname[trim:]
            if truncname not in excludedirs and truncname not in excludefiles:
                if os.path.isfile(fullname) and not os.path.islink(fullname):
                    mode = getStat(fullname)
                    files.append([truncname,fchksum.fmd5t(fullname)[0],oct(mode[0]),str(mode[1]),str(mode[2])])
                if os.path.isfile(fullname) and os.path.islink(fullname):
                    mode = getStat(fullname)
                    files.append([truncname,"symlink to file",oct(mode[0]),str(mode[1]),str(mode[2])])
                if os.path.isdir(fullname) and os.path.islink(fullname):
                    mode = getStat(fullname)
                    files.append([truncname,"symlink to directory",oct(mode[0]),str(mode[1]),str(mode[2])])
                if os.path.isdir(fullname) and not os.path.islink(fullname) and os.listdir(fullname) == []:
                    mode = getStat(fullname)
                    files.append([truncname,"empty dir",oct(mode[0]),str(mode[1]),str(mode[2])])
                if os.path.isdir(fullname) and not os.path.islink(fullname):
                    stack.append(fullname)
            else:
                print "excluding", fullname
    return files
Пример #20
0
def VerEXIST():
    
    
    # xpath = argv[1]                                                                                                                                                                                                                                                         

    if(argv[1][-1] == '/'):
        xpath = argv[1][:-1]

    else:
        xpath = argv[1]

    if os.path.exists(xpath):
        if os.path.isfile(xpath):
            right = oct(stat.S_IMODE(os.lstat(argv[1]).st_mode))
            if right == '0':
                 print("Vous n'avez pas les droits necessaire.")
            elif right[1] == '4' or right[1] == '5' or right[1] == '6' or right[1] == '7':
                FileEXIST()
            else:
                print("Vous n'avez pas les droits necessaire.")

        if os.path.isdir(xpath):
            right = oct(stat.S_IMODE(os.lstat(argv[1]).st_mode))
            if right == '0':
                 print("Vous n'avez pas les droits necessaire.")
            if right[1] == '4' or right[1] == '5' or right[1] == '6' or right[1] == '7':
                DirectoryEXIST()
            else:
                print("Vous n'avez pas les droits necessaire.")
    else:
        print(xpath + " --> N'existe pas.")
def test_securedrop_application_test_journalist_key(File, Sudo):
    """
    Ensure the SecureDrop Application GPG public key file is present.
    This is a test-only pubkey provided in the repository strictly for testing.
    """
    pubkey_file = File("{}/test_journalist_key.pub".format(
        securedrop_test_vars.securedrop_data))
    # Sudo is only necessary when testing against app hosts, since the
    # permissions are tighter. Let's elevate privileges so we're sure
    # we can read the correct file attributes and test them.
    with Sudo():
        assert pubkey_file.is_file
        assert pubkey_file.user == "root"
        assert pubkey_file.group == "root"
        assert oct(pubkey_file.mode) == "0644"

    # Let's make sure the corresponding fingerprint is specified
    # in the SecureDrop app configuration.
    securedrop_config = File("{}/config.py".format(
        securedrop_test_vars.securedrop_code))
    with Sudo():
        assert securedrop_config.is_file
        # travis needs the config.py file ran owned by root not sure why
        # just saw this note in the travis.yml config
        if hostenv == "travis":
            assert securedrop_config.user == "root"
            assert securedrop_config.group == "root"
        else:
            assert securedrop_config.user == \
                securedrop_test_vars.securedrop_user
            assert securedrop_config.group == \
                securedrop_test_vars.securedrop_user
        assert oct(securedrop_config.mode) == "0600"
        assert securedrop_config.contains(
            "^JOURNALIST_KEY = '65A1B5FF195B56353CC63DFFCC40EF1228271441'$")
Пример #22
0
def createdir(dirPath, mode=None):
    """
    Recursively create directory if doesn't exist

    If already exists check that permissions are as requested.
    """
    if mode is not None:
        mode |= stat.S_IFDIR
        params = (dirPath, mode)
    else:
        params = (dirPath,)

    try:
        os.makedirs(*params)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
        else:
            log.warning("Dir %s already exists", dirPath)
            if mode is not None:
                statinfo = os.stat(dirPath)
                curMode = statinfo[stat.ST_MODE]
                if curMode != mode:
                    raise OSError(errno.EPERM,
                                  ("Existing %s permissions %s are not as "
                                   "requested %s") % (dirPath,
                                                      oct(curMode),
                                                      oct(mode)))
Пример #23
0
def TestOwnerGroupMode(DestinationPath, SourcePath, fc):
    stat_info = os.lstat(DestinationPath)

    if SourcePath:
        stat_info_src = os.lstat(SourcePath)

    if fc.Owner:
        Specified_Owner_ID = pwd.getpwnam(fc.Owner)[2]
        if Specified_Owner_ID != pwd.getpwuid(stat_info.st_uid)[2]:
            return False
    elif SourcePath:
        # Owner wasn't specified, if SourcePath is specified then check that the Owners match
        if pwd.getpwuid(stat_info.st_uid)[2] != pwd.getpwuid(stat_info_src.st_uid)[2]:
            return False

    if fc.Group:
        Specified_Group_ID = grp.getgrnam(fc.Group)[2]
        if Specified_Group_ID != grp.getgrgid(stat_info.st_gid)[2]:
            return False
    elif SourcePath:
        # Group wasn't specified, if SourcePath is specified then check that the Groups match
        if grp.getgrgid(stat_info.st_gid)[2] != grp.getgrgid(stat_info_src.st_gid)[2]:
            return False
    
    # Mode is irrelevant to symlinks
    if not os.path.islink(DestinationPath):
        if fc.Mode:
            if str(oct(stat_info.st_mode))[-3:] != fc.Mode:
                return False
        elif SourcePath:
            # Mode wasn't specified, if SourcePath is specified then check that the Modes match
            if str(oct(stat_info.st_mode))[-3:] != str(oct(stat_info_src.st_mode))[-3:]:
                return False

    return True
Пример #24
0
def print_file_stats(path, filename, full_path=False):

    stat_details = os.stat(os.path.join(path, filename))

    uid = stat_details.st_uid
    gid = stat_details.st_gid
    filesize = stat_details.st_size
    mode = stat_details.st_mode
    lastmodified = time.gmtime(stat_details.st_mtime)
    mtime = time.strftime('%d %b %H.%M', lastmodified)

    username = pwd.getpwuid(uid)[0]
    group = grp.getgrgid(gid)[0]

    if os.path.isdir(os.path.join(path, filename)):
        _hard_links = hard_links(os.path.join(path, filename))
        mode = oct(mode)[3:]

        if full_path == False:
            print '%s %s %s %s %s %s %s' % (mode, _hard_links, username, group, filesize, mtime, filename)
        else:
            print '%s %s %s %s %s %s %s' % (mode, _hard_links, username, group, filesize, mtime, os.path.join(path, filename))            
    else:
        mode = oct(mode)[4:]

        if full_path == False:
            print '%s %s %s %s %s %s' % (mode, username, group, filesize, mtime, filename)
        else:
            print '%s %s %s %s %s %s' % (mode, username, group, filesize, mtime, os.path.join(path, filename))

    return username, group, filesize, mode, mtime
Пример #25
0
Файл: config.py Проект: olpa/tex
    def checkDir(self, path, mode):
        """checkDir locks, if the user has full read, write, execute
        access to a given directory. 
        
        I don't think this works on non-Unix filesystems
        
        """
        def checkRights(pos):
            if oct(os.stat(path).st_mode)[pos] < 7:
                try:
                    chmodDir = os.chmod(path, mode)
                except OSError:
                    exit(_(u"Insufficient rights to enter the required directory %s. Aborting!") % path)

        def makeDir(path):
            try:
                makeDir = os.mkdir(path, mode)
            except OSError:
                exit(_(u"I was not able to enter the required directory %s. Aborting!") % path)
            #Recheck
            if os.path.isdir(path) == True:
                return True
            return False

        if os.path.isdir(path) == False:
            if makeDir(path) == False:
                exit(_(u"Could not access required directory " + path))
        if 'win32' != sys.platform:
          if oct(os.stat(path).st_uid) == os.getuid():
              checkRights(3)
          elif oct(os.stat(path).st_gid) == os.getgid():
              checkRights(4)
          else:
              checkRights(5)
Пример #26
0
 def testOct(self):
     self.assertEqual(oct(23), '027')
     try:
         o = oct(23.2)
         self.fail("No oct() argument error raised")
     except TypeError, why:
         self.assertEqual(str(why), "oct() argument can't be converted to oct")
Пример #27
0
 def __str__(self):
     return "{root: " + self.fsdbRoot + \
            ", depth: " + str(self._conf['depth']) + \
            ", hash_alg: " + self._conf['hash_alg'] + \
            ", fmode: " + str(oct(self._conf['fmode'])) + \
            ", dmode: " + str(oct(self._conf['dmode'])) + \
            "}"
Пример #28
0
    def testShelltoolsChmod(self):
        from pisi.actionsapi.shelltools import chmod

        chmod("tests/actionsapitests/file")
        self.assertEqual(oct(os.stat("tests/actionsapitests/file").st_mode)[-3:], "755")
        chmod("tests/actionsapitests/file", 0644)
        self.assertEqual(oct(os.stat("tests/actionsapitests/file").st_mode)[-3:], "644")
Пример #29
0
def ignore_tree (root_dir):
    for dir_path, sd, files in os.walk(root_dir):
        perm = oct(os.lstat(dir_path).st_mode & 0o777).rjust(4, '0')[1:]
        yield ('ign', 'd', perm, dir_path)
        for f in files:
            perm = oct(os.lstat(dir_path+'/'+f).st_mode & 0o777).rjust(4, '0')[1:]
            yield ('ign', 'f', perm, dir_path + '/' + f)
Пример #30
0
    def testEncapToNativeSloppy(self):
        """
        Update from encapsulated package to native package with the same
        contents but different modes, ensure that the file does not disappear.

        @tests: CNY-3762
        """
        self.addRPMComponent('foo:rpm=1.0', 'simple-1.0-1.i386.rpm')
        self.updatePkg('foo:rpm', raiseError=True)

        recipe = r"""
class TestPackage(CapsuleRecipe):
    name = 'foo'
    version = '2.0'

    clearBuildReqs()
    def setup(r):
        r.addArchive('simple-1.0-1.i386.rpm', dir='/')
        r.Ownership('nobody', 'nobody', '.*')
        r.SetModes('/dir', 0700)
        r.SetModes('/normal', 0600)
"""
        src = self.makeSourceTrove('foo', recipe)
        self.cookFromRepository('foo')[0]
        self.updatePkg(['-foo:rpm', 'foo:runtime'], depCheck=False,
                raiseError=True)
        path = os.path.join(self.rootDir, 'normal')
        self.assertEqual(os.stat(path).st_size, 7)
        self.assertEqual(oct(os.stat(path).st_mode), '0100600')
        path = os.path.join(self.rootDir, 'dir')
        self.assertEqual(oct(os.stat(path).st_mode), '040700')
Пример #31
0
def bin2oct(binNumber):
    octa = oct(int(binNumber, 2))
    octa = octa[2:]
    return octa
Пример #32
0
sample_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
reversed_list = sample_list[::-1]
print('列表反转====', reversed_list)
joined_str = ''.join([str(i) for i in reversed_list])
print('反转后转换成字符串===', joined_str)
sliced_str = joined_str[2:8]
print('切片后取出第三到第八个字符', sliced_str)
reversed_str = sliced_str[::-1]
print('字符串反转', reversed_str)
int_value = int(reversed_str)
print('转换为int====', int_value)
print('转换为二进制====', bin(int_value))
print('转换为八进制====', oct(int_value))
print('转换为十六进制====', hex(int_value))
Пример #33
0
def decimal_to_octal(dec):
    decimal = int(dec)
    return oct(decimal)