def test_check_line(): # TODO: Test other modes config.create("~/.hamstall/config") config.add_line("Test Line", "~/.hamstall/config") assert config.check_line("Test Line", "~/.hamstall/config", "fuzzy") is True assert config.check_line("ThisShouldNotBeFound=True", "~/.hamstall/config", "fuzzy") is False
def list_saved_hosts(line_end='\n'): config.create() conf = config.load() aliases = [alias for alias in conf] aliases.sort() for alias in aliases: print(alias, end=line_end)
def show(alias: str): config.create() conf = config.load() if not conf[alias]: print('{} hasn\'t been found'.format(alias)) return print(conf[alias])
def run_ssh(alias: str): config.create() conf = config.load() if alias not in conf: print('{} hasn\'t been found'.format(alias)) return sshrunner.run(conf[alias])
def delete(self, user_id): query = '''DELETE FROM person WHERE id = "{0}"'''.format(user_id) result = create(query) self.write( json.dumps( dict(message="Successfully deleted user with id: {0}".format( user_id))))
def put(self, user_id): params = json.loads(self.request.body) query_params = ",".join('''"{0}"="{1}"'''.format(key, params[key]) for key in params if params[key] is not None) query = ''' UPDATE person SET {0} WHERE id="{1}"'''.format( query_params, user_id) result = create(query) self.write(json.dumps(dict(result="Success")))
def first_time_setup(sym): """First Time Setup. Sets up hamstall for the first time. Args: sym (bool): Used for testing. If True, installed py's will be symlinked to originals, not copied. False means it will be copied and not symlinked. """ if config.exists(config.full('~/.hamstall/hamstall.py')): print('Please don\'t run first time setup on an already installed system!') generic.leave() print('Installing hamstall to your system...') try: os.mkdir(config.full("~/.hamstall")) except FileExistsError: rmtree(config.full("~/.hamstall")) os.mkdir(config.full("~/.hamstall")) try: os.mkdir(config.full("/tmp/hamstall-temp/")) except FileExistsError: rmtree(config.full("/tmp/hamstall-temp")) os.mkdir(config.full("/tmp/hamstall-temp/")) os.mkdir(config.full("~/.hamstall/bin")) config.create("~/.hamstall/database") create_db() config.create("~/.hamstall/.bashrc") # Create directories and files files = os.listdir() for i in files: i_num = len(i) - 3 if i[i_num:len(i)] == '.py': if sym: os.symlink(os.getcwd() + "/" + i, config.full("~/.hamstall/" + i)) else: try: copyfile(i, config.full('~/.hamstall/' + i)) except FileNotFoundError: print("A file is missing that was attempted to be copied! Install halted!") generic.leave(1) config.add_line("source ~/.hamstall/.bashrc\n", "~/{}".format(config.read_config("ShellFile"))) config.add_line("alias hamstall='python3 ~/.hamstall/hamstall.py'\n", "~/.hamstall/.bashrc") # Add bashrc line print('First time setup complete!') print('Please run the command "source ~/{}" or restart your terminal.'.format(config.read_config("ShellFile"))) print('Afterwards, you may begin using hamstall with the hamstall command!') generic.leave()
def post(self): data = json.loads(self.request.body) fname = data.get('firstname') lname = data.get('lastname') phno = data.get('mobilenumber') address = data.get('address') query = ''' INSERT INTO person (firstname,lastname,mobilenumber,address) VALUES ("{0}","{1}","{2}","{3}") '''.format(fname,lname,phno,address) ; result = create(query) self.write(json.dumps(dict(message="successfully added user:{0} {1}".format(fname, lname))))
def add_new_host(host_alias: str, host: str, key_path: str, login: str): if is_argument_missing(host_alias, 'host_alias'): return if is_argument_missing(host, 'host'): return if is_argument_missing(login, 'login'): return config.create() conf = config.load() conf[host_alias] = {'host': host, 'key_path': key_path, 'login': login} print('Added new config for {}'.format(host_alias)) print(conf[host_alias]) config.save(conf)
def post(self): data = json.loads(self.request.body) fname = data.get('firstname') lname = data.get('lastname') phno = data.get('mobilenumber') address = data.get('address') query = ''' INSERT INTO person (firstname,lastname,mobilenumber,address) VALUES ("{0}","{1}","{2}","{3}") '''.format( fname, lname, phno, address) result = create(query) self.write( json.dumps( dict(message="successfully added user:{0} {1}".format( fname, lname))))
def init(): global OPTIONS, ARGS, config_instance OPTIONS, ARGS = parse_cmd_args() setup_logging() LOG.info("Backup session starting...") try: config_instance = config.create(OPTIONS.config) except ImportError, exc: LOG.critical( "Error loading the config module %r! " "This file is required. If you just made a clean checkout, have a " "look at config/config.py.dist for an example." % OPTIONS.config ) LOG.exception(exc) sys.exit(9)
def main(): while True: try: print('attempting to connect to reddit api') cnf = myfile.load('save') reddit_client = praw.Reddit(user_agent=cnf['user_agent']) oauth_helper = init(reddit_client) print('printing hot 5 posts from r/earthporn') download.do_stuff(reddit_client) print('sleeping for 4 hours') time.sleep(14400) except praw.errors.OAuthInvalidToken: print('refreshing access_token') oauth_helper.refresh() tokens = oauth_helper.get_access_codes() cnf = config.create(cnf, tokens['access_token']) myfile.save('save', cnf)
def delete(alias: str): config.create() conf = config.load() conf.pop(alias, None) config.save(conf)
def create_desktop(program_internal_name): """Create Desktop. Walks the user through creating a .desktop file for a program Args: program_internal_name (str): Name of program as stored in the database """ files = os.listdir(config.full('~/.hamstall/bin/' + program_internal_name + '/')) print(' '.join(files)) program_file = '/Placeholder/' config.vprint("Getting user inputs") while program_file not in files: # Get file to binlink from user program_file = input('Please enter a file listed above. If you would like to cancel, type exit: ') if program_file == "exit": return desktop_name = "{}-{}".format(program_file, program_internal_name) if config.exists("~/.local/share/applications/{}.desktop".format(desktop_name)): print("Desktop file already exists!") return exec_path = config.full("~/.hamstall/bin/{}/{}".format(program_internal_name, program_file)) path = config.full("~/.hamstall/bin/{}/".format(program_internal_name)) comment = "/" while not comment.replace(" ", "").isalnum() and comment != "": comment = input("Please input a comment for the application: ") if comment == "": comment = program_internal_name icon = ";" while not icon.replace("-", "").replace("_", "").replace("/", "").isalnum() and icon != "": icon = input("Enter the path to an icon, the name of the icon, or press ENTER for no icon! ") if icon != "": icon = "Icon=" + icon terminal = generic.get_input("Should this program launch a terminal to run it in? [y/N]", ['y', 'n'], 'n') if terminal.lower() == 'y': should_terminal = "True" else: should_terminal = "False" name = "/" while not name.replace(" ", "").isalnum() and name != "": name = input("Please enter a name: ") if name == "": name = program_internal_name ans = " " chosen_categories = [] categories = ["audio", "video", "development", "education", "game", "graphics", "network", "office", "science", "settings", "system", "utility", "end"] while ans.lower() != "end": print("Please enter categories, one at a time, from the list of .desktop categories below (defaults to " "Utility). Type \"end\" to end category selection. \n") print(", ".join(categories)) ans = generic.get_input("", categories, "Utility") if ans.capitalize() in chosen_categories or ans == "end": pass else: ans = ans.capitalize() chosen_categories.append(ans) if ans in ["Audio", "Video"] and not ("AudioVideo" in chosen_categories): chosen_categories.append("AudioVideo") if not chosen_categories: chosen_categories = ["Utility"] cats = ";".join(chosen_categories) + ";" # Get categories for the .desktop to_write = """ [Desktop Entry] Name={name} Comment={comment} Path={path} Exec={exec_path} {icon} Terminal={should_terminal} Type=Application Categories={categories} """.format(name=name, comment=comment, exec_path=exec_path, should_terminal=should_terminal, categories=cats, icon=icon, path=path) os.chdir(config.full("~/.local/share/applications/")) config.create("./{}.desktop".format(desktop_name)) with open(config.full("./{}.desktop".format(desktop_name)), 'w') as f: f.write(to_write) config.db["programs"][program_internal_name]["desktops"].append(desktop_name) print("\nDesktop file created!")
__trace__ = None __result__ = None __config__ = None __valid__ = None __pydoc__ = None if options.doc : # doc generation __trace__ = trace.create(options.trace) __result__ = result.create(options.result, __trace__ ) __config__ = config.create(options.config, __trace__ ) __pydoc__ = pydoc.Pydoc(None, __result__) else : # test execution __trace__ = trace.create(options.trace) __result__ = result.create(options.result, __trace__ ) __config__ = config.create(options.config, __trace__ ) __valid__ = valid.Valid(__config__, __result__) __trace__.set_result(__result__) __trace__.set_config(__config__) __trace__.start() __config__.start()
import datetime import xml.dom.minidom import xml.etree.ElementTree as ElementTree import config timestamp = datetime.datetime.now() config = config.create() def prettify(xmltree): """Return a pretty-printed XML string for the Element. """ rough_string = ElementTree.tostring(xmltree) reparsed = xml.dom.minidom.parseString(rough_string) pretty_xml = reparsed.toprettyxml(indent=' ', encoding='latin_1') pretty_xml_lines = pretty_xml.splitlines() pretty_xml_lines2 = filter(str.strip, pretty_xml_lines) pretty_xml2 = "\n".join(pretty_xml_lines2) return pretty_xml2 def generate_new_name_id(): return 'meos_' + timestamp.strftime('%Y%m%d_%H%M%S_%f') def convert_time_to_seconds(time): segments = time.split(":") return int(segments[0]) * 60 * 60 + int(segments[1]) * 60 + int(segments[2]) def get_current_updated_timestamp(): return timestamp.strftime('%Y%m%d%H%M%S')
def test_create(): config.create("~/.hamstall/test01") assert config.exists("~/.hamstall/test01")
def put(self, user_id): params = json.loads(self.request.body) query_params = ",".join('''"{0}"="{1}"'''.format(key, params[key]) for key in params if params[key]is not None) query = ''' UPDATE person SET {0} WHERE id="{1}"'''.format(query_params,user_id); result = create(query) self.write(json.dumps(dict(result="Success")))
l_idx = 0 log.info("start reading lines") with open(config.loader_path, "r") as fdr: fdr.readline() for line in fdr: log.info("line {}: {}".format(l_idx, line)) l_idx += 1 try: doc = parse_line(line) publisher.send(doc) except: log.exception("{} {}".format(l_idx, line)) log.info("flushing and stopping publisher") publisher.flush() publisher.stop() if __name__ == "__main__": config_path = sys.argv[1] if len(sys.argv) > 1 else "config/config.yaml" config.create(config_path) logging.config.dictConfig(config.log_dict_config) log = logging.getLogger("loader") timer = RepeatedTimer(operation, config.interval_min * 60, start_immediately=True) timer.start() timer.join()
def OnOptionsMenuItem(self, event): optDlg = config.create(self) optDlg.Show() self.Hide()
print( "Another instance of hamstall is probably running! Execution halted!" ) sys.exit(2) else: config.lock() username = getpass.getuser() # Root check if username == 'root': print( 'Note: Running as root user will install programs for the root user to use!' ) if config.db == {"refresh": True}: # Downgrade check print("Hang tight! We're finishing up your downgrade...") config.create("~/.hamstall/database") prog_manage.create_db() config.db = config.get_db() config.write_db() print("We're done! Continuing hamstall execution...") if args.first: # Check if -f or --first is supplied prog_manage.first_time_setup(False) if not (config.exists('~/.hamstall/hamstall.py') ): # Make sure hamstall is installed """Install hamstall if it doesn't exist""" yn = generic.get_input( 'hamstall is not installed on your system. Would you like to install it? [Y/n]', ['y', 'n', 'debug'], 'y') if yn == 'y':
def delete(self, user_id): query = '''DELETE FROM person WHERE id = "{0}"'''.format(user_id); result = create(query) self.write(json.dumps(dict(message="Successfully deleted user with id: {0}".format(user_id))))
# adapted from https://github.com/avinassh/prawoauth2/blob/master/examples/halflife3-bot/onetime.py import praw from prawoauth2 import PrawOAuth2Server import config import myfile user_agent = input("Enter user agent: ") app_key = input("Enter app key: ") app_secret = input("Enter app secret: ") reddit_client = praw.Reddit(user_agent=user_agent) oauthserver = PrawOAuth2Server(reddit_client, app_key=app_key, app_secret=app_secret, state=user_agent, scopes=config.scopes) # start the server, this will open default web browser # asking you to authenticate oauthserver.start() tokens = oauthserver.get_access_codes() c = config.create(user_agent, app_key, app_secret, tokens['access_token'], tokens['refresh_token']) myfile.save('save', c)