class Setting(object): def __init__(self, cfg_path): super(Setting, self).__init__() self.cf = MyConfigParser(cfg_path) def get_default_config(self): return self.cf["basic"]["default_config"] def get_work_path(self): return self.cf["basic"]["work_path"] def get_file_config_path(self, file_name): for name in self.cf["file_config_mapper"]: value = self.cf["file_config_mapper"][name] if file_name.find(name) >= 0: return value return None def set_config_mapper(self, name, value): self.cf["file_config_mapper"][name] = value self.cf.write() def del_config_mapper(self, name): del self.cf["file_config_mapper"][name] self.cf.write()
def extract(self): members = self.zf.infolist() if self.show_info: self.start_extract() total = 0 for zip_info in members: total += zip_info.file_size if not self.regex_util or not self.regex_util.do_match(spit_filename(zip_info.filename, True)): if len(zip_info.filename) + len(self.work_path) + 1 < 255: self.zf.extract(zip_info.filename, self.work_path) if self.eu_text and spit_filename(zip_info.filename, True) == "important.properties": file_path = os.path.join(self.work_path, zip_info.filename) try: cf = MyConfigParser(file_path, file_error=True) regrex = ["\$\{" + key + "\}" for key in cf.keys()] self.eu_text.add_regex(regrex) except Exception as exe: print exe print self.work_path + "/" + zip_info.filename if self.show_info: self.update_extract(total) else: print "path len > 255 ", self.work_path, zip_info.filename else: pass if self.show_info: self.finish_extract() self.zf.close()
def __init__(self): """ Initializes the Model class for trove with empty member variables. """ self.program_name = "" self.version = "" self.config = MyConfigParser() self.entries = MyConfigParser() self.start_marker = False self.end_marker = False self.entry_dict = {} self.trove_dir = os.path.join(os.getenv('HOME'), '.trove') self.config_file_name = 'trove.conf' return None
from gettext import gettext from sys import path as sys_path sys_path.append("money/reusing") from casts import list2string, string2list_of_strings, string2list_of_integers, str2bool from datetime_functions import string2dtnaive from text_inputs import input_string, input_YN from myconfigparser import MyConfigParser _=gettext if __name__ == "__main__": print("Hidden settings are going to be generated in /etc/django_money/settings.conf") config=MyConfigParser("/etc/django_money/settings.conf") ans=input_YN("Do you want to change database settings?") if ans is True: ans = input_string("Add you database server", "127.0.0.1") config.set("db", "server", ans) ans = input_string("Add you database port", "5432") config.set("db", "port", ans) ans = input_string("Add your database name", "mylibrary") config.set("db", "db", ans) ans = input_string("Add you database user", "postgres") config.cset("db", "user", ans) ans = input_string("Add you database password", "your_pass") config.cset("db", "password", ans) ans=input_YN("Do you want to change smtp mail server settings?")
def __init__(self, cfg_path): super(Setting, self).__init__() self.cf = MyConfigParser(cfg_path)
class Model(): """ Model for the trove program. This class handles all business logic. """ def __init__(self): """ Initializes the Model class for trove with empty member variables. """ self.program_name = "" self.version = "" self.config = MyConfigParser() self.entries = MyConfigParser() self.start_marker = False self.end_marker = False self.entry_dict = {} self.trove_dir = os.path.join(os.getenv('HOME'), '.trove') self.config_file_name = 'trove.conf' return None def new_entry(self): """ Initialise and return a new ``TroveEntry``. """ return TroveEntry() def calculate_hash(self, entry): """ Calculate and return the entry's SHA1 hash. """ return hashlib.sha1(entry.name + entry.user + entry.passwd + entry.helptext + entry.description).hexdigest() def check_choice(self, choice_type, choice, maximum = 0): """ Method to verify a user input. Two modes are available: 1) Integer mode allows for verification of a given integer to (a) be an integer indeed and (b) lie within a given range. Returns True in this case, False in all other cases. 2) Boolean mode returns True if the user types either 'y', 'Y', 'yes' or 'Yes', and returns False in all other cases. """ if choice_type == 'integer': if not self.is_int(choice): return False if (int(choice) > maximum): return False elif (int(choice) < 1): return False else: return True elif choice_type == 'boolean': if choice == 'y' or choice == 'Y': return True elif choice == 'yes' or choice == 'Yes': return True else: return False else: return False def decrypt_file(self, filename, passwd): """ Decrypt the encrypted secrets file. """ f = open(os.devnull, 'w') decrypt = subprocess.Popen(['bcrypt', filename], stdin=subprocess.PIPE, stdout=f, stderr=f) decrypt.stdin.write(passwd + "\n") decrypt.wait() f.close() def is_int(self, s): """ Takes a string s and checks if is an integer """ try: int(s) return True except ValueError: return False def get_entries(self, encrypted_file, passphrase): """ Decrypts encrypted_file with a given master passphrase, reads in all entries (by calling extract_entries method) and encrypts the password file again with the same master passphrase. """ filesize = 0 self.decrypt_file(encrypted_file, passphrase) decrypted_filename = encrypted_file.rstrip('.bfe') if os.path.isfile(decrypted_filename): filesize = os.path.getsize(decrypted_filename) if filesize > 0: self.extract_entries(decrypted_filename) self.encrypt_file(decrypted_filename, passphrase) else: # workaround for bcrypt. If the master passphrase is incorrect, # bcrypt creates an *empty* file (0 bytes) (and doesn't warn # about this being the case), which would then be encrypted by # trove and the old database would be overwritten with this # empty file. Deleting the zero size password file is a # workaround so that the database with real data in doesn't get # overwritten with empty data. os.system("rm -f " + decrypted_filename) def write_encrypted_file(self, encryptedfile, masterpasswd): """ Write the encrypted data to file using the given master password. """ passwdfile = encryptedfile.rstrip('.bfe') ef = open(passwdfile, 'w') ef.write("# Auto generated by " + self.program_name + " " + self.version + "\n") now = datetime.datetime.now() ef.write("# Date: " + \ datetime.date.strftime(now, "%Y-%m-%d %H:%M:%S") + "\n\n") ef.write("# ### TROVE START MARKER ###\n\n") for key in self.entry_dict: entry = self.entry_dict[key] ef.write("[" + entry.name + "]\n") ef.write("user: "******"\n") ef.write("password: "******"\n") ef.write("help: " + entry.helptext + "\n") ef.write("description: " + entry.description + "\n\n") ef.write("# ### TROVE END MARKER ###\n") ef.close() os.system("rm -f " + encryptedfile) self.encrypt_file(passwdfile, masterpasswd) def encrypt_file(self, filename, passwd): """ Encrypt the secrets file. """ f = open(os.devnull, 'w') encrypt = subprocess.Popen(['bcrypt', filename], stdin=subprocess.PIPE, stdout=f, stderr=f) encrypt.stdin.write(passwd + "\n" + passwd + "\n") encrypt.wait() f.close() def extract_entries(self, filename): """ Reads in decrypted password file and fills self.entry_dict with TroveEntry objects. Keys of this dictionary are the SHA1 hashes of the entries calculated with self.calculate_hash(). """ fh = open(filename, 'r') fhlines = fh.readlines() fh.close() for line in fhlines: line = line.strip() if (re.search('TROVE START MARKER', line)): self.start_marker = True if (re.search('TROVE END MARKER', line)): self.end_marker = True if self.start_marker and self.end_marker: self.entries.read(filename) for entry in self.entries.sections(): myentry = TroveEntry() myentry.name = entry if 'user' in self.entries.options(entry): myentry.user = self.entries.get(entry, 'user') if 'password' in self.entries.options(entry): myentry.passwd = self.entries.get(entry, 'password') if 'help' in self.entries.options(entry): myentry.helptext = self.entries.get(entry, 'help') if 'description' in self.entries.options(entry): myentry.description = self.entries.get(entry, 'description') myentry.eid = self.calculate_hash(myentry) self.entry_dict[myentry.eid] = myentry return def search(self, search_term): """ Searches name fields in self.entry_dict for search_term. Both strings are converted to lower case. Returns a list of Trove entry objects, where the regular expression search has been successful. It returns a list and not a dictionary, because later the list is sorted by entry names and displayed. The user then picks a result by choosing a number in the menu that shows up. Sorting would be impossible with a dictionary. """ result_list = [] for key in self.entry_dict.keys(): normalized_entry_name = (self.entry_dict[key].name).lower() if re.search(search_term.lower(), normalized_entry_name): result_list.append(self.entry_dict[key]) return result_list def password_search(self, search_term): """ Searches password fields in self.entry_dict for search_term. Returns a list of Trove entry objects, where the regular expression search has been successful. """ result_list = [] for key in self.entry_dict: if re.search(search_term, (self.entry_dict[key].passwd)): result_list.append(self.entry_dict[key]) return result_list def execute(self, command): """ Run the given command in a subprocess. """ proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.wait() return_value = proc.poll() output = proc.communicate()[0] return return_value, output def return_all(self): """ Returns a result list with all entries of the trove. """ result_list = [] for key in self.entry_dict.keys(): result_list.append(self.entry_dict[key]) return result_list