glusterfs

Форк
0
/
getfattr.py 
132 строки · 4.9 Кб
1

2
from __future__ import print_function
3
import os
4
import sys
5
from optparse import OptionParser
6

7
import xattr
8

9
def handle_textencoding(attr):
10
    ### required for Python's handling of NULL strings.
11
    attr_null_replace = (attr.encode('hex').decode('hex')).replace('\x00',
12
                                                                   '\\000')
13
    return attr_null_replace
14

15
def getfattr(path, option):
16
    attr = xattr.getxattr(path, option.name)
17
    encoded_attr = attr
18

19
    if option.encoding == "text":
20
        ## special case handle it.
21
        encoded_attr = handle_textencoding(attr)
22
    else:
23
        encoded_attr = attr.encode(option.encoding)
24

25
    if option.onlyvalues:
26
        print (encoded_attr)
27
        return
28

29
    print_getfattr (path, option, encoded_attr)
30
    return
31

32
def print_getfattr (path, option, encoded_attr=None):
33
    if encoded_attr:
34
        if option.encoding == "hex":
35
            print(("%s=0x%s" % (option.name, encoded_attr)))
36
        elif option.encoding == "base64":
37
            print(("%s=0s%s" % (option.name, encoded_attr)))
38
        else:
39
            print(("%s=\"%s\"" % (option.name, encoded_attr)))
40
    else:
41
        print(option.name)
42

43
    return
44

45
def print_header (path, absnames):
46
    if absnames:
47
        print(("# file: %s" % path))
48
    else:
49
        print ("getfattr: Removing leading '/' from absolute path names")
50
        print(("# file: %s" % path[1:]))
51

52
if __name__ == '__main__':
53
    usage = "usage: %prog [-n name|-d] [-e en] [-m pattern] path...."
54
    parser = OptionParser(usage=usage)
55
    parser.add_option("-n", action="store", dest="name", type="string",
56
                      help="Dump the value of the named extended attribute"
57
                      " extended attribute.")
58
    parser.add_option("-d", action="store_true", dest="dump",
59
                      help="Dump the values of all extended attributes"
60
                      " associated with pathname.")
61
    parser.add_option("-e", action="store", dest="encoding", type="string",
62
                      default="base64",
63
                      help="Encode values after retrieving"
64
                      " them. Valid values of [en] are `text`, `hex`,"
65
                      " and `base64`. Values encoded as text strings are"
66
                      " enclosed in double quotes (\"), while strings"
67
                      " encoded as hexadecimal and base64 are prefixed with"
68
                      " 0x and 0s, respectively.")
69
    parser.add_option("-m", action="store", dest="pattern", type="string",
70
                      help="Only include attributes with names matching the"
71
                      " regular expression pattern. The default value for"
72
                      " pattern is \"^user\\.\", which includes all the"
73
                      " attributes in the user namespace. Specify \"-\" for"
74
                      " including all attributes. Refer to attr(5) for a more"
75
                      " detailed discussion of namespaces.")
76
    parser.add_option("--absolute-names", action="store_true", dest="absnames",
77
                      help="Do not strip leading slash characters ('/')."
78
                      " The default behaviour is to strip leading slash characters.")
79
    parser.add_option("--only-values", action="store_true", dest="onlyvalues",
80
                      help="Dump out the raw extended attribute value(s)"
81
                      " without encoding them.")
82

83
    (option, args) = parser.parse_args()
84
    if not args:
85
        print ("Usage: getfattr [-hRLP] [-n name|-d] [-e en] [-m pattern]"
86
               " path...")
87
        print ("Try `getfattr --help' for more information.")
88
        sys.exit(1)
89

90
    if option.dump and option.name:
91
        print ("-d and -n are mutually exclusive...")
92
        sys.exit(1)
93

94
    if option.pattern and option.name:
95
        print ("-m and -n are mutually exclusive...")
96
        sys.exit(1)
97

98
    if option.encoding:
99
        if (not (option.encoding.strip() == "hex" or
100
                 option.encoding.strip() == "base64" or
101
                 option.encoding.strip() == "text")):
102
            print(("unrecognized encoding parameter... %s, please use"
103
                   " `text`, `base64` or `hex`" % option.encoding))
104
            sys.exit(1)
105

106
    args[0] = os.path.abspath(args[0])
107

108
    if option.name:
109
        print_header(args[0], option.absnames)
110
        try:
111
            getfattr(args[0], option)
112
        except KeyError as err:
113
            print(("Invalid key %s" % err))
114
            sys.exit(1)
115
        except IOError as err:
116
            print (err)
117
            sys.exit(1)
118

119
    if option.pattern:
120
        print_header(args[0], option.absnames)
121
        try:
122
            xattrs = xattr.listxattr(args[0])
123
            for attr in xattrs:
124
                if option.dump:
125
                    option.name = attr.encode('utf-8')
126
                    getfattr(args[0], option)
127
                else:
128
                    option.name = attr.encode('utf-8')
129
                    print_getfattr(args[0], option, None)
130

131
        except IOError as err:
132
            print (err)
133
            sys.exit(1)
134

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.