caellion-python-commons
unixpassword.py
Go to the documentation of this file.
1 """!
2 This module provides utlilities related to creating, reading, writing and parsing of linux-style passwd/shadow file.
3 """
4 
5 
6 class DuplicateFieldException(Exception):
7  """!
8  This exception is raised when more than exactly one instance of a given field is contained within field list.
9  """
10 
11  pass
12 
13 
14 class EmptyFieldNameException(Exception):
15  """!
16  This exception is raised when an empty field name is encountered.
17  """
18 
19  pass
20 
21 
22 class SeparatorEmptyException(Exception):
23  """!
24  This exception is raised when an empty separator string is encountered.
25  """
26 
27  pass
28 
29 
30 class NewlineEmptyException(Exception):
31  """!
32  This exception is raised when an empty line separator string is encountered.
33  """
34 
35  pass
36 
37 
38 class InvalidFileFormatException(Exception):
39  """!
40  This exception is raised when encountering invalid or non-uniform line.
41  """
42 
43  pass
44 
45 
47  """!
48  This class provides methods to read and write to linux-style passwd/shadow files, ability to parse shadow-style lines into dicts and identifying password hashing algorithms used in linux-style hash format.
49  """
50 
51  text_lines = [] # list of dicts representing lines
52  line_format = [] # list of field names to use as line format
53  separator = ":" # string separating fields in line
54  newline = "\n" # string to use as line separator when dumping text
55 
56  def __init__(self, line_format, separator=":", newline="\n"):
57  """!
58  Initialize parser.
59 
60  @param line_format List of field names, field names have to be unique and cannot be empty. Not all fields have to be in format list if dumping text.
61  @param separator String to use to separate fields in line
62  @param newline String to use as line separator
63  """
64  # validate field list
65  check_ = []
66  for x in line_format:
67  if x not in check_:
68  check_.append(x)
69  else:
70  raise DuplicateFieldException("Field '%s' is duplicated in field list." % x)
71  if x == "" or x is None:
72  raise EmptyFieldNameException("Encountered empty field name in field list.")
73 
74  if separator is None or separator == "":
75  raise SeparatorEmptyException("Encountered empty separator string.")
76 
77  if newline is None or newline == "":
78  raise NewlineEmptyException("Encountered empty line separator string.")
79 
80  self.line_formatline_formatline_format = line_format
81  self.separatorseparatorseparator = separator
82  self.newlinenewlinenewline = newline
83  self.text_linestext_linestext_lines = [] # need to cleanup this on init (tests somehow keep state unpredictably)
84 
85  def parse_line(self, line):
86  """!
87  Parses line according to line_format.
88 
89  @param line The line to be parsed
90 
91  @returns The dict representation of given line
92  """
93  split_line = line.split(self.separatorseparatorseparator)
94 
95  fieldid = 0
96  linedict = {}
97  for x in split_line:
98  # find name in field list
99  if fieldid > (len(self.line_formatline_formatline_format) - 1):
100  raise InvalidFileFormatException("Field with value '%s' is outside defined line format," % x)
101  fname = self.line_formatline_formatline_format[fieldid]
102  fvalue = x
103  linedict.update({fname: fvalue})
104  fieldid += 1
105 
106  return linedict
107 
108  def create_line(self, fields):
109  """!
110  Creates string line from fieldset and line_format
111 
112  @param fields Dict of field values to fill line with
113 
114  @returns String representation of give line data
115  """
116  line = ""
117  fieldno = 0
118  for x in self.line_formatline_formatline_format:
119  linedata = fields[x]
120 
121  line += str(linedata)
122  if fieldno < (len(self.line_formatline_formatline_format) - 1):
123  line += str(self.separatorseparatorseparator)
124 
125  fieldno += 1
126 
127  return line
128 
129  def add_new_line(self, fields):
130  """!
131  Prepares and adds new line to internal buffer.
132 
133  @param fields Dict of field values to add to internal buffer as a line
134  """
135  self.text_linestext_linestext_lines.append(fields)
136 
137  def add_line_from_text(self, line):
138  """!
139  Parsed line and adds appropriate dict to internal buffer.
140 
141  @param line String representation of a given line
142  """
143  self.text_linestext_linestext_lines.append(self.parse_lineparse_line(line))
144 
145  def dump_text(self):
146  """!
147  Prepares and returns text block representing all lines in internal buffer.
148 
149  @returns String block representing internal buffer. Empty string when no lines in buffer.
150  """
151  linestr = ""
152  for x in self.text_linestext_linestext_lines:
153  linestr += self.create_linecreate_line(x) + self.newlinenewlinenewline
154 
155  return linestr
156 
157  def load_text(self, textblock):
158  """!
159  Parses text block and adds its lines to internal buffer.
160 
161  @param textblock String to load into internal buffer
162  """
163  lines = textblock.split(self.newlinenewlinenewline)
164 
165  for line in lines:
166  line = line.strip()
167  if line is not None and line != "":
168  self.add_line_from_textadd_line_from_text(line)
This exception is raised when more than exactly one instance of a given field is contained within fie...
Definition: unixpassword.py:6
This exception is raised when an empty field name is encountered.
Definition: unixpassword.py:14
This exception is raised when encountering invalid or non-uniform line.
Definition: unixpassword.py:38
This exception is raised when an empty line separator string is encountered.
Definition: unixpassword.py:30
This exception is raised when an empty separator string is encountered.
Definition: unixpassword.py:22
This class provides methods to read and write to linux-style passwd/shadow files, ability to parse sh...
Definition: unixpassword.py:46
def dump_text(self)
Prepares and returns text block representing all lines in internal buffer.
def add_new_line(self, fields)
Prepares and adds new line to internal buffer.
def parse_line(self, line)
Parses line according to line_format.
Definition: unixpassword.py:85
def create_line(self, fields)
Creates string line from fieldset and line_format.
def add_line_from_text(self, line)
Parsed line and adds appropriate dict to internal buffer.
def __init__(self, line_format, separator=":", newline="\n")
Initialize parser.
Definition: unixpassword.py:56
def load_text(self, textblock)
Parses text block and adds its lines to internal buffer.