def deleteTaggedCronjob(tag): """ Delete a tagged cronjob from the existing user's crontab :param tag: tag of existing entry :type tag: str|int :return: whether it succeeded :rtype: bool """ try: if isinstance(tag, int): tag = str(tag) cron = CronTab(user=True) matching_jobs = tuple(cron.find_comment(tag)) if len(matching_jobs) == 0: return True job = tuple(cron.find_comment(tag))[0] cron.remove(job) cron.write() return True except: return False
def linux_createCronJobs(): #start cronjob cron_client = CronTab() iter = cron_client.find_comment("Desktop Image Changer client") try: print "Client Cron Task Found" iter.next() except StopIteration: print 'Installing Client Cron Task' job = cron_client.new(scriptDirectory+ "/client.py dailyUpdate", comment="Desktop Image Changer client") job.every().dom() cron_client.write() cron_daemon = CronTab() iter = cron_daemon.find_comment("Desktop Image Changer daemon") try: print "Daemon Cron Task Found" iter.next() except StopIteration: print 'Installing Daemon Cron Task' job = cron_daemon.new(scriptDirectory+ "/daemon.py &", comment="Desktop Image Changer daemon") job.every_reboot() cron_daemon.write()
def test_scheduleUpdatedCorrectly(self): expectedSchedule = '0 7 1 1 * /bin/sh /replylater/src/core/runmessage.sh --id=1 --data=sqllite # 1' tz = timezone(timedelta(hours=5, minutes=30)) d = datetime(year=2022, month=1, day=1, hour=12, minute=30, tzinfo=tz) Scheduler.scheduleReply(1, d) c = CronTab(user=True) iter = c.find_comment('1') jobs = [i for i in iter] self.assertEqual(len(jobs), 1) self.assertEqual(str(jobs[0]), expectedSchedule) d = datetime(year=2022, month=2, day=1, hour=12, minute=30, tzinfo=tz) expectedSchedule = '0 7 1 2 * /bin/sh /replylater/src/core/runmessage.sh --id=1 --data=sqllite # 1' Scheduler.updateReply(1, d) c = CronTab(user=True) iter = c.find_comment('1') jobs = [i for i in iter] self.assertEqual(len(jobs), 1) self.assertEqual(str(jobs[0]), expectedSchedule) tz = timezone(timedelta(hours=4, minutes=0)) d = datetime(year=2022, month=2, day=1, hour=12, minute=30, tzinfo=tz) expectedSchedule = '30 8 1 2 * /bin/sh /replylater/src/core/runmessage.sh --id=1 --data=sqllite # 1' Scheduler.updateReply(1, d) c = CronTab(user=True) iter = c.find_comment('1') jobs = [i for i in iter] self.assertEqual(len(jobs), 1) self.assertEqual(str(jobs[0]), expectedSchedule)
def setcron(timearray, sunevent, script_path, user): #timearray input is an array in the form [hour, minute] hour = timearray[0] minute = timearray[1] user_cron = CronTab(user) if sunevent == "Sunset": list = user_cron.find_comment('sunon') if not list: cmd_string = 'python %sfadeupall.py' % script_path job = user_cron.new(command=cmd_string, comment='sunon') else: job = list[0] else: #Sunrise list = user_cron.find_comment('sunoff') if not list: cmd_string = 'python %sfadedownall.py' % script_path job = user_cron.new(command=cmd_string, comment='sunoff') else: job = list[0] job.minute.clear() job.hour.clear() job.minute.on(minute) job.hour.on(hour) job.enable() user_cron.write()
def install_poly_startup_task(self): from crontab import CronTab print "poly_start configuration starting..." command = "/home/pi/poly9.0/linux/raspi/bin/rtrdb -r data_service=8001 db" comment = "poly_start" cron = CronTab(user='******') if not cron.find_comment('poly_start'): print "Installing poly_start crontab..." job = cron.new(command=command, comment=comment) job.every_reboot() cron.write() if job.is_valid(): print "poly_start crontab successfully installed." else: print "poly_start crontab failed to install" else: print "poly_start crontab already installed" print "removing old job" oldjob = cron.find_comment('poly_start') print ('OldJob', oldjob) # cron.remove(oldjob) print "Installing poly_start crontab..." job = cron.new(command=command, comment=comment) job.every_reboot() cron.write() if job.is_valid(): print "poly_start crontab successfully installed." else: print "poly_start crontab failed to install" print "Listing all crontab jobs:" for cronjob in cron: print cronjob print "poly_start configuration finished"
def select_shutdown(self): try: resp = errcode.get_error_result() cron = CronTab(user=True) cron_name = self.task.get("data").get("task_name") jobs = cron.find_comment( 'front_end_controller:{}'.format(cron_name)) jobs_cnt = len(list(jobs)) if jobs_cnt == 1: jobs = cron.find_comment( 'front_end_controller:{}'.format(cron_name)) resp['data'] = {} for job in jobs: job_cmd = str(job).split('#')[0].strip() resp['data']['exec_minute'] = job_cmd.split(' ')[0] resp['data']['exec_hour'] = job_cmd.split(' ')[1] resp['data']['exec_weekly'] = str(job_cmd.split(' ')[4]) elif jobs_cnt >= 1: resp = errcode.get_error_result( error="FoundMultipleCrontabRecord") return resp else: resp = errcode.get_error_result(error="NotFoundCrontabRecord") return resp current_app.logger.debug( 'select crontab: {} success'.format(cron_name)) return resp except Exception as err: current_app.logger.error(err) current_app.logger.error(''.join(traceback.format_exc())) resp = errcode.get_error_result(error="OtherError") return resp
def post(self,env_id,prod_id,ver_id): user_cron=CronTab(user=True) timepub=self.session.query(Timepub).filter(Timepub.ver_id==ver_id).one() timepub.time=self.get_argument('time') timepub.min=self.get_argument('min') timepub.hour=self.get_argument('hour') timepub.day=self.get_argument('day') timepub.mon=self.get_argument('mon') timepub.week=self.get_argument('week') self.session.commit() ver=self.session.query(Ver).get(ver_id) upload_path=os.path.join(os.path.dirname(__file__),'files/'+env_id+'/'+prod_id) if int(timepub.time) == 1: iter = user_cron.find_comment('autoops_'+ver.name+'_'+ver_id) for job in iter: if job: user_cron.remove(job) user_cron.write_to_user(user=True) job = user_cron.new(command="cd "+upload_path+"&&ansible-playbook "+prod_id+".yml -i "+prod_id+".host -e \"ver="+ver.file+"\" | tee cronlogs/cron_"+ver.name+"_$(date +\%Y\%m\%d\%H\%M\%S).log", comment='autoops_'+ver.name+'_'+ver_id) job.setall(timepub.min+' '+timepub.hour+' '+timepub.day+' '+timepub.mon+' '+timepub.week) job.enable() user_cron.write_to_user(user=True) else: iter = user_cron.find_comment('autoops_'+ver.name+'_'+ver_id) for job in iter: user_cron.remove(job) user_cron.write_to_user(user=True) self.redirect("/ver/"+env_id+'/'+prod_id+'/0')
def delete_shutdown(self): try: resp = errcode.get_error_result() cron = CronTab(user=True) cron_name = self.task.get("data").get("task_name") jobs = cron.find_comment( 'front_end_controller:{}'.format(cron_name)) jobs_cnt = len(list(jobs)) if jobs_cnt >= 1: jobs = cron.find_comment( 'front_end_controller:{}'.format(cron_name)) for job in jobs: job.delete() cron.write() else: resp = errcode.get_error_result(error="NotFoundCrontabRecord") return resp current_app.logger.debug( 'del crontab: {} success'.format(cron_name)) return resp except Exception as err: current_app.logger.error(err) current_app.logger.error(''.join(traceback.format_exc())) resp = errcode.get_error_result(error="OtherError") return resp
def _schedule(config): """ Setups up a cron job to make sure the print job process is running. Run this every minute on workdays between 7am and 9pm """ crontab = CronTab(user=getpass.getuser()) cmd = "{} {} {} {} {}".format( " ".join( "{}={}".format(key, value) for key, value in os.environ.items() if key in ENV_VARS_TO_PASS_TO_COMMAND ), "LOG_LEVEL={}".format(config[CRON_CONFIG_SECTION]["default_log_level"]), "/usr/bin/env python2", config[CRON_CONFIG_SECTION]["executable_path"], config[CRON_CONFIG_SECTION]["cmd"], ) LOGGER.info("Adding command: '{}'".format(cmd)) try: job = next(crontab.find_comment("print-job")) LOGGER.info("Cron exists. Updating.") job.command = cmd except StopIteration: LOGGER.info("Adding new cron job.") crontab.new(comment="print-job", command=cmd) job = next(crontab.find_comment("print-job")) job.setall("* 7-21 * * *") crontab.write()
class CrontabJob: def __init__(self): self.cron = CronTab(user=True) def setTemperature(self, temperature): job = self.cron.new(command=script +' '+ temperature, comment='Termostaati') job.minute.every(1) self.cron.write() def getTemperature(self): job = self.cron.find_comment('Termostaati') if job : for jobs in job: print jobs return jobs.render()[68:70] else: return 0 def deleteCronoJobs(self): self.cron.remove_all(comment='Termostaati') self.cron.write() def areCronoJobs(self): return self.cron.find_comment('Termostaati')
class CrontabJob: def __init__(self): self.cron = CronTab(user=True) def setTemperature(self, temperature): job = self.cron.new(command=script + ' ' + temperature, comment='Termostaati') job.minute.every(1) self.cron.write() def getTemperature(self): job = self.cron.find_comment('Termostaati') if job: for jobs in job: print jobs return jobs.render()[68:70] else: return 0 def deleteCronoJobs(self): self.cron.remove_all(comment='Termostaati') self.cron.write() def areCronoJobs(self): return self.cron.find_comment('Termostaati')
def crontab(l, r, action): """Allow the user to manage crontab entries for the compranet tracker. The -l option lists the compranet tracker crontab entries and -r removes them. Two actions are supported, ADD and REMOVE. \b To ADD a crontab entry use the following syntax: compranet-cli crontab add [time] -- [command] where the time argument is a CRON expression (e.g. "0 0 * * 0" or weekly) and command is the compranet-cli command to execute. Example: compranet-cli crontab add "0 2 * * *" -- "--email-log pull_xlsx" \b To REMOVE a crontab entries use the following syntax: compranet-cli crontab remove [command] All crontab entries which contain the command argument will be removed. Example: compranet-cli crontab remove pull_xlsx """ cron = CronTab(user=True) if l: for job in cron.find_comment('compranet_tracker'): print(job) if r: for job in cron.find_comment('compranet_tracker'): cron.remove(job) cron.write() if len(action) == 0 and not l and not r: print(click.get_current_context().get_help()) if len(action) > 0: if action[0].upper() == 'ADD': venv_path = settings.VIRTUALENV_PATH cli_path = os.path.join(venv_path, 'bin', 'compranet-cli') if len(action) != 3: raise click.BadParameter("Wrong number of arguments", param_hint='ACTION') time = action[1] if not CronSlices.is_valid(time): raise click.BadParameter("Invalid CRON expression", param_hint='ACTION') cli_opts = ' '.join(action[2:]) command = ' '.join([cli_path, cli_opts]) job = cron.new(command=command, comment='compranet_tracker') job.setall(time) cron.write() elif action[0].upper() == 'REMOVE': if len(action) != 2: raise click.BadParameter("Wrong number of arguments", param_hint='ACTION') cmd = ' '.join(action[1:]) for job in cron.find_command(cmd): print("Removing entry {}".format(job)) cron.remove(job) cron.write() else: raise click.BadParameter("Unrecognized action argument", param_hint='ACTION')
def read_cron(): user_cron = CronTab(user=True) if list(user_cron.find_comment('Hawkeye')): page = int(list(user_cron.find_comment('Hawkeye')) [0].command.split(' ')[-1]) - 1 every = int(str(list(user_cron.find_comment('Hawkeye')) [0].minutes).replace('*/', '')) return {'every': every, 'page': page} else: return {'every': 15, 'page': 1}
def main(): module = AnsibleModule( argument_spec=dict( # default value for user to bypass required_one_of check # incase of validate_cron_time user=dict(default="dpal"), tabfile=dict(), use_regex=dict(default=False), match_string=dict(), schedule=dict(), list_all_crons=dict(type=bool), get_crons_by_command=dict(type=bool), get_crons_by_comment=dict(type=bool), get_crons_by_time=dict(type=bool), validate_cron_time=dict(type=bool), ), required_one_of=(("user", "tabfile"), ), required_if=( ("get_crons_by_command", True, ["match_string", "use_regex"]), ("get_crons_by_comment", True, ["match_string", "use_regex"]), ("get_crons_by_time", True, ["match_string", "use_regex"]), ("validate_cron_time", True, ["schedule"]), )) cron = CronTab(user=module.params["user"], tabfile=module.params["tabfile"]) if module.params['list_all_crons']: crons = cron.lines elif module.params['get_crons_by_command']: if module.params["use_regex"]: crons = cron.find_command( re.compile(r"{}".format(module.params["match_string"]))) else: crons = cron.find_command(module.params["match_string"]) elif module.params['get_crons_by_comment']: if module.params["use_regex"]: crons = cron.find_comment( re.compile(r"{}".format(module.params["match_string"]))) else: crons = cron.find_comment(module.params["match_string"]) elif module.params['get_crons_by_time']: crons = cron.find_time(module.params["match_string"]) elif module.params['validate_cron_time']: module.exit_json(valid=CronSlices.is_valid(module.params["schedule"])) else: module.fail_json(msg="unknown parameters") module.exit_json(crons=cron_items_to_list(crons))
def remove_job(job_name): cron = CronTab(user=USERNAME) job_iter = cron.find_comment(job_name) jobs = [] for job in job_iter: jobs.append(job) job_iter = cron.find_comment(job_name) for job in job_iter: cron.remove(job) cron.write() if len(jobs) > 1: logging.error('More then 1 job found matching {}'.format(job_name)) raise Exception('More then 1 job found matching {}'.format(job_name))
def _generar_tarea_limpieza_diaria_queuelog(self): """Adiciona una tarea programada para limpiar la tabla queue_log diariamente """ # conectar con cron crontab = CronTab(user=getpass.getuser()) ruta_psql = os.popen('which psql').read()[:-1] # adicionar nuevo cron job para esta tarea si no existe anteriormente job = crontab.find_comment(self.tareas_programadas_ids[1]) crontab.remove_all(comment=self.tareas_programadas_ids[1]) if list(job) == []: postgres_user = settings.POSTGRES_USER postgres_host = settings.POSTGRES_HOST postgres_database = settings.POSTGRES_DATABASE postgres_password = '******'.format( os.getenv('PGPASSWORD')) job = crontab.new( command= '{0} {1} -U {2} -h {3} -d {4} -c \'DELETE FROM queue_log\''. format(postgres_password, ruta_psql, postgres_user, postgres_host, postgres_database), comment=self.tareas_programadas_ids[1]) # adicionar tiempo de periodicidad al cron job job.hour.on(2) crontab.write_to_user(user=getpass.getuser())
def write_cron(time, page): if isinstance(time, int): cron_command = '{0}/venv/bin/python {0}/spider.py 1 {1}'.format( base_path, page) my_user_cron = CronTab(user=True) if list(my_user_cron.find_comment('Hawkeye')): for cron in my_user_cron.find_comment('Hawkeye'): cron.delete() job = my_user_cron.new(command=cron_command) job.setall('*/{} * * * *'.format(time)) job.set_comment("Hawkeye") job.enable() my_user_cron.write() return True else: return False
def create_alarm(user, action, minute, hour, days, id): comment = create_cron_comment(user, action, minute, hour, days, id) # If alarm already exists return True cron = CronTab(user=True) iter = cron.find_comment(comment) try: job = iter.next() if len(job) > 0: if DEBUG: print job return True, 'alarm already exists' except StopIteration: pass # print comment if action == 'on': job = cron.new(command='/home/pi/projects/light_switch/light_on.py') elif action == 'off': job = cron.new(command='/home/pi/projects/light_switch/light_off.py') else: return False, 'Invalid action ' + action job.set_comment(comment) job.minute.on(minute) job.hour.on(hour) daysList = days.split(",") job.dow.on(*daysList) if DEBUG: print job if job.is_valid(): cron.write() return True, 'success' else: return False, 'Invalid cron job ' + str(job)
def addTaggedCronjob(tag, interval, cmd): """ Adds a tagged cronjob to current user's crontab :param tag: tag for new entry :type tag: str|int :param interval: crontab interval :type interval: str :param cmd: crontab cmd to run :type cmd: str :return: whether it succeeded :rtype: bool """ try: if isinstance(tag, int): tag = str(tag) if not CronSlices.is_valid(interval): return False cron = CronTab(user=True) matching_jobs = tuple(cron.find_comment(tag)) if len(matching_jobs) == 0: job = cron.new(command=cmd, comment=tag) else: job = matching_jobs[0] job.set_command(cmd) job.setall(interval) if not job.is_valid(): return False cron.write() return True except: return False
def servicesStart(): cron = CronTab(user=True) for job in cron.find_comment('polis'): if job.comment == 'polis': print("**WARNING: Polis services already running -- run 'polis stop'", file=sys.stderr) sys.exit(2) for i in range(len(SOURCES)): root_dir = ROOT_DIR logfile = SOURCES[i]["LOGFILE"] daemon = SOURCES[i]["DAEMON"] freq = SOURCES[i]["FREQ"] command_string = "python " + root_dir + "/python/" + daemon + " > " + logfile + " 2>&1" job = cron.new(command=command_string, comment='polis') try: # first entry set to 0 -- otherwise a new script spawns every minute job.setall("0 %s * * *" % freq) except: print("**ERROR: Could not set %s" % daemon, file=sys.stderr) print("Check config.py for invalid frequency settings", file=sys.stderr) sys.exit(3) for job in cron: if job.is_valid(): print(job.command) else: print("**ERROR: Invalid job: %s" % job.command) sys.exit(4) # assuming all goes well: cron.write()
def get(self, request): cron = CronTab(user=getpass.getuser()) it = cron.find_comment(re.compile(r'sp(\d+)')) arr = [] for item in it: try: js = json.loads(item.command.split(' ', 2)[2].strip("'")) try: sourcetable = js['dbconfig']['sourcetable'] except Exception as e: sourcetable = '' try: schedule = item.schedule(date_from=datetime.now()) lasttime = schedule.get_prev() nexttime = schedule.get_next() outtable = js['args']['outtable']['value'] except Exception as e: outtable = '' arr.append({ 'name': js['name'], 'description': item.description(locale_code='zh_CN'), 'enabled': item.is_enabled(), 'detail': item.command, 'sourcetable': sourcetable, 'outtable': outtable, 'pk': item.comment[2:], 'lasttime': lasttime, 'nexttime': nexttime, }) except Exception as e: print(e) return Response(arr)
def add_cronjob(): if not is_existing_cronjob(): cmd = 'ipgates --dnat -s {} -d'.format(args.service) msg = 'Adding cron job to automatically remove rule for {} service'.format( args.service.upper()) print('[+] {}'.format(msg)) logging.info(msg, extra={'username': USERNAME}) cron = CronTab(tabfile='/etc/crontab', user=False) for job in cron.find_comment(args.service): job.enable() cron.write() msg = 'Execute "{}" {}'.format( cmd, job.description(use_24hour_time_format=True).lower()) print('\t{}'.format(msg).expandtabs(4)) logging.info(msg, extra={'username': USERNAME}) return job = cron.new(command=cmd, comment=args.service, user='******') job.setall('{} 18 * * *'.format(randint(0, 59))) job.enable() cron.write() msg = 'Execute "{}" {}'.format( cmd, job.description(use_24hour_time_format=True).lower()) print('\t{}'.format(msg).expandtabs(4)) logging.info(msg, extra={'username': USERNAME})
def get_jobs(finger): cron = CronTab(user=True) iter = cron.find_comment(finger) list = [] for i in iter: list.append(i) return list
def init_uwsgi_log(self): import os from crontab import CronTab cron = CronTab(user=True) comment = 'uwsgilogrotat' res = list(cron.find_comment(comment)) if not res: is_dev = os.environ.get('ITM_CONFIG') if is_dev == 'test': job = cron.new( command='sh /home/share/itpserver/bean/logbackups.sh') else: job = cron.new( command='sh /opt/skyguard/itpserver/logbackups.sh') job.setall('0 0 * * *') job.set_comment(comment) cron.write() print('Uwsgi log rotat init success!') elif len(res) == 1: print('Uwsgi log rotat has init!') else: print('Uwsgi log rotat has error!')
def test_insert(self): '''Insert a job, It should insert a job and return it with id''' result = self.schedule.insert({ "enable": 1, "alias": "reboot", "command": "uptime && test_insert", "schedule": "0 0 * * *", "executer": True }) self.assertDictEqual({ "id": 2, "enable": 1, "alias": "reboot", "command": "uptime && test_insert", "schedule": "0 0 * * *", "executer": True, "comment": "sanji_schedule_2" }, result) jobs = [] cron = CronTab(user=True) for job in cron.find_comment("sanji_schedule_2"): jobs.append(job) self.assertEqual(len(jobs), 1)
def delete_job(): cron = CronTab(user=True) list = cron.find_comment('ALERTBONCOIN') for job in list: print(job) job.clear() cron.remove(job)
def uninstall(service): cron = CronTab() comment = 'cmu-grades-%s' % service job = cron.find_comment(comment) cron.remove(job[0]) cron.write() print 'Uninstalled cmu-grades %s service!' % service
def time_change(message): hour, minute = message["data"].split(":") print("New wake up time: {}-{}".format(hour, minute)) TEST = True if TEST: cron = CronTab(tabfile="test.CronTab") else: cron = CronTab(user=True) # get already created crontab for job in cron.find_comment("clock weekday"): print(job) if job.hour == hour and job.minute == minute: pass else : #remove old cron cron.remove_all(comment="clock weekday") job = cron.new(command="python /home/pi/sunlight_alarm_clock/light/python/transition.py", comment='clock weekday') job.hour.on(hour) job.minute.on(minute) schedule = job.schedule(date_from=datetime.now()) if TEST: cron.write("test.CronTab") else: cron.write()
def search_for_cron_jobs_and_remove(comment_to_search_for): # Buscamos y eliminamos los cron jobs que contengan el comment especificado por parámetro if comment_to_search_for: cron = CronTab('www-data') jobs_with_specified_comment = cron.find_comment(comment_to_search_for) cron.remove(jobs_with_specified_comment) cron.write()
def test_update(self): '''Update a job, It should update a job and return it''' added = self.schedule.get()[0] result = self.schedule.update({ "id": added["id"], "enable": 1, "alias": "uptime", "command": "uptime && test_update", "schedule": "1 1 1 * *", "executer": True }) self.assertNotEqual(result, None) self.assertDictEqual( { "id": added["id"], "enable": 1, "alias": "uptime", "command": "uptime && test_update", "schedule": "1 1 1 * *", "executer": True, "comment": added["comment"] }, result) jobs = [] cron = CronTab(user=True) for job in cron.find_comment(result["comment"]): jobs.append(job) self.assertEqual(job.slices, result["schedule"]) self.assertEqual(job.command, result["command"]) self.assertEqual(len(jobs), 1)
class BasicTestCase(unittest.TestCase): """Test basic functionality of crontab.""" def setUp(self): self.crontab = CronTab(tab=INITAL_TAB) def test_01_presevation(self): """All Entries Re-Rendered Correctly""" self.crontab.write() results = RESULT_TAB.split('\n') line_no = 0 for line in self.crontab.intab.split('\n'): self.assertEqual(str(line), results[line_no]) line_no += 1 def test_02_simple_enum(self): """Simple Enumerations""" e = list(self.crontab.find_command('enums'))[0] self.assertEqual(e.month, 'JAN') self.assertEqual(e.month.render(True), '1') self.assertEqual(e.dow, 'SAT') self.assertEqual(e.dow.render(True), '6') def test_03_enum_range(self): """Enumeration Ranges""" e = list(self.crontab.find_command('ranges'))[0] self.assertEqual(e.month, 'MAR-APR') self.assertEqual(e.month.render(True), '3-4') def test_04_sets(self): """Enumeration Sets""" e = list(self.crontab.find_command('multiples'))[0] self.assertEqual(e.dow, 'MON,WED,FRI') self.assertEqual(e.dow.render(True), '1,3,5') def test_05_create(self): """Create by Enumeration""" job = self.crontab.new(command='new') job.month.on('JAN') job.dow.on('SUN') self.assertEqual(str(job), '* * * JAN SUN new') def test_06_create_range(self): """Created Enum Range""" job = self.crontab.new(command='new2') job.month.during('APR', 'NOV').every(2) self.assertEqual(str(job), '* * * APR-NOV/2 * new2') def test_07_create_set(self): """Created Enum Set""" job = self.crontab.new(command='new3') job.month.on('APR') job.month.also.on('NOV', 'JAN') self.assertEqual(str(job), '* * * JAN,APR,NOV * new3') def test_08_find_comment(self): """Comment Set""" jobs = list(self.crontab.find_comment('Comment One')) self.assertEqual(len(jobs), 2) for job in jobs: self.assertEqual(job.comment, 'Comment One')
def setup_shutdown(self): try: resp = errcode.get_error_result() cron = CronTab(user=True) cron_name = self.task.get("data").get("task_name") cron_time_minute = int(self.task.get("data").get("exec_minute")) cron_time_hour = int(self.task.get("data").get("exec_hour")) cron_weekly = str(self.task.get("data").get("exec_weekly")) cron_weekly = [ x for x in re.findall('\d', cron_weekly) if x in list("01234567") ] cron_weekly = ','.join(cron_weekly) jobs = cron.find_comment( 'front_end_controller:{}'.format(cron_name)) for job in jobs: job.delete() job = cron.new(command='shutdown now', comment='front_end_controller:{}'.format(cron_name)) job.setall(cron_time_minute, cron_time_hour, '*', '*', cron_weekly) cron.write() current_app.logger.debug( 'add crontab: {} success'.format(cron_name)) return resp except Exception as err: current_app.logger.error(err) current_app.logger.error(''.join(traceback.format_exc())) resp = errcode.get_error_result(error="OtherError") return resp
def test_update(self): '''Update a job, It should update a job and return it''' added = self.schedule.get()[0] result = self.schedule.update({ "id": added["id"], "enable": 1, "alias": "uptime", "command": "uptime && test_update", "schedule": "1 1 1 * *", "executer": True }) self.assertNotEqual(result, None) self.assertDictEqual({ "id": added["id"], "enable": 1, "alias": "uptime", "command": "uptime && test_update", "schedule": "1 1 1 * *", "executer": True, "comment": added["comment"] }, result) jobs = [] cron = CronTab(user=True) for job in cron.find_comment(result["comment"]): jobs.append(job) self.assertEqual(job.slices, result["schedule"]) self.assertEqual(job.command, result["command"]) self.assertEqual(len(jobs), 1)
def autoupdate_cron(os_family, remove=False): """ Enable/remove Akroma Auto-update cron """ cron = CronTab('root') if remove: print_cmd('Removing Akroma MasterNode auto-update...') cron.remove_all(comment='Akroma MasterNode Auto-Update') cron.write() elif not sum(1 for _ in cron.find_comment('Akroma MasterNode Auto-Update')): res = input_bool('Auto-update Akroma MasterNode? [Y/n]', 'Y') if res == 'Y': print_cmd('Enabling Akroma MasterNode auto-update...') job = cron.new(command='/usr/sbin/akroma-mn-setup', comment='Akroma MasterNode Auto-Update') job.setall('%d %d * * *' % (random.randint(0, 59), random.randint(0, 23))) cron.write() print_cmd('Enabling and starting cron service...') if os_family == 'RedHat': ret, _ = timed_run('/usr/bin/yum -d1 -y install cronie') else: ret, _ = timed_run('/usr/bin/apt-get install cron -y') if ret is None or int(ret) != 0: raise Exception("ERROR: Failed to install cron") service = 'cron' if os_family != 'RedHat' else 'crond' for status in ('enable', 'start'): service_status(service, status)
def running_schedule_count(self, repository_name, schedule_name): cron_tab = CronTab(user=True) matching_jobs = cron_tab.find_comment( self._cron_tag_for_schedule(repository_name, schedule_name) ) return len(list(matching_jobs))
class EnumTestCase(unittest.TestCase): """Test basic functionality of crontab.""" def setUp(self): self.crontab = CronTab(tab=INITAL_TAB) def test_01_presevation(self): """All Entries Re-Rendered Correctly""" self.crontab.write() results = RESULT_TAB.split('\n') line_no = 0 for line in self.crontab.intab.split('\n'): self.assertEqual(str(line), results[line_no]) line_no += 1 def test_02_simple_enum(self): """Simple Enumerations""" e = list(self.crontab.find_command('enums'))[0] self.assertEqual(e.month, 'JAN') self.assertEqual(e.month.render(True), '1') self.assertEqual(e.dow, 'SAT') self.assertEqual(e.dow.render(True), '6') def test_03_enum_range(self): """Enumeration Ranges""" e = list(self.crontab.find_command('ranges'))[0] self.assertEqual(e.month, 'MAR-APR') self.assertEqual(e.month.render(True), '3-4' ) def test_04_sets(self): """Enumeration Sets""" e = list(self.crontab.find_command('multiples'))[0] self.assertEqual(e.dow, 'MON,WED,FRI') self.assertEqual(e.dow.render(True), '1,3,5' ) def test_05_create(self): """Create by Enumeration""" job = self.crontab.new(command='new') job.month.on('JAN') job.dow.on('SUN') self.assertEqual(str(job), '* * * JAN SUN new') def test_06_create_range(self): """Created Enum Range""" job = self.crontab.new(command='new2') job.month.during('APR', 'NOV').every(2) self.assertEqual(str(job), '* * * APR-NOV/2 * new2') def test_07_create_set(self): """Created Enum Set""" job = self.crontab.new(command='new3') job.month.on('APR') job.month.also.on('NOV','JAN') self.assertEqual(str(job), '* * * JAN,APR,NOV * new3') def test_08_find_comment(self): """Comment Set""" jobs = list(self.crontab.find_comment('Comment One')) self.assertEqual(len(jobs), 2) for job in jobs: self.assertEqual(job.comment, 'Comment One')
def test_insert(self): '''Insert a job, It should insert a job and return it with id''' result = self.schedule.insert({ "enable": 1, "alias": "reboot", "command": "uptime && test_insert", "schedule": "0 0 * * *", "executer": True }) self.assertDictEqual( { "id": 2, "enable": 1, "alias": "reboot", "command": "uptime && test_insert", "schedule": "0 0 * * *", "executer": True, "comment": "sanji_schedule_2" }, result) jobs = [] cron = CronTab(user=True) for job in cron.find_comment("sanji_schedule_2"): jobs.append(job) self.assertEqual(len(jobs), 1)
def updateTaggedCronjob(tag, interval='', cmd='', new_tag=''): """ Update a tagged cronjob in the current user's crontab :param tag: tag of existing entry :type tag: str|int :param interval: new crontab interval :type interval: str :param cmd: new crontab cmd to run :type cmd: str :param new_tag: new tag for entry :type new_tag: str|int :return: whether it succeeded :rtype: bool """ try: if isinstance(tag, int): tag = str(tag) if isinstance(new_tag, int): new_tag = str(new_tag) cron = CronTab(user=True) matching_jobs = tuple(cron.find_comment(tag)) if len(matching_jobs) == 0: job = cron.new(comment=tag) else: job = tuple(cron.find_comment(tag))[0] if len(interval) > 0: if not CronSlices.is_valid(interval): return False job.setall(interval) if len(cmd) > 0: job.set_command(cmd) if len(new_tag) > 0: job.set_comment(new_tag) if not job.is_valid(): return False cron.write() return True except: return False
def DeleteCronJob(self, description): tab = CronTab(user=self.user) for item in tab.find_comment(description): tab.remove(item) # writes content to crontab tab.write()
def install_cron_job(tab:crontab.CronTab, command:str, comment:str): jobs_by_comment = tab.find_comment(comment) for job in jobs_by_comment: if job.comment == comment: return job return tab.new(command=command, comment=comment)
def test_09_removal_during_iter(self): crontab = CronTab() for x in range(0, 5, 1): job = crontab.new(command="cmd", comment="SAME_ID") job.setall("%d * * * *" % (x + 1)) for item in crontab.find_comment("SAME_ID"): crontab.remove(item) self.assertEqual(len(crontab), 0)
def delete(self): '''remove one spider''' name = self.get_argument('name') cron = CronTab(user=True) jobs = cron.find_comment(name) [job.delete() for job in jobs] cron.write() remove_service(name) self.write('{}')
def get(self): '''status of spider''' name = self.get_argument('name') if not SpiderHelper(name).exists(): self.write(status_code(Status.service_not_found)) return cron = CronTab(user=True) jobs = cron.find_comment(name) job_list = [format_job(job) for job in jobs] if len(job_list) == 0: self.write(status_code(Status.service_not_found)) return log = status_service(name) msg_list = log.split('\n')[-2].split() if msg_list[1] != 'RUNNING': self.write(status_code(more_msg='Service not running now.', obj = job_list[0])) return pid = int(msg_list[3][:-1]) pro = psutil.Process(pid) times = pro.cpu_times() create_time = time.localtime(pro.create_time()) pmem = pro.memory_info() job = { "job_msg" : job_list[0], "cmdline" : pro.cmdline(), "cpu_percent" : pro.cpu_percent(), "cpu_times" : { "children_system" : times.children_system, "children_user" : times.children_user, "system" : times.system, "user" : times.user }, "is_running" : pro.is_running(), "pid" : pid, "running_time" : msg_list[5], "create_time" : time.strftime('%Y-%m-%d %H:%M:%S', create_time), "memory_info" : { "rss" : pmem.rss, "vms" : pmem.vms, "shared" : pmem.shared, "text" : pmem.text, "lib" : pmem.lib, "data" : pmem.data, "dirty" : pmem.dirty }, "status" : pro.status(), "username" : pro.username() } self.write(status_code(obj=job))
def _clock_out(): """ This method will open a chrome window, log the user in to okta with their workiva email, open ADP Workforce, and clock the user out. """ driver = webdriver.Chrome() driver.get(se.ADP["okta"]) wait = WebDriverWait(driver, 10) wait.until(EC.element_to_be_clickable((By.ID, "signin-button"))) username = driver.find_element_by_id("user-signin") username.send_keys(se.ADP["username"]) password = driver.find_element_by_id("pass-signin") password.send_keys(se.ADP["password"]) sign_in = driver.find_element_by_id("signin-button") sign_in.click() driver.get("%shome/adp_workforce_now/" % se.ADP["okta"] + \ "0oac91hvcoOAQQBOYUYZ/3311") element = wait.until(EC.element_to_be_clickable((By.ID, "Myself_navItem"))) nav_item = driver.find_element_by_id("Myself_navItem") # Hover to show menu buttons. action = ActionChains(driver) action.move_to_element(nav_item) action.perform() driver.find_element_by_id("Myself_ttd_Time&Attendance_MyTimeEntry").click() driver.implicitly_wait(7) try: driver.find_element_by_id("btnClockIn") except NoSuchElementException: action.move_by_offset(-20, 350) action.click() action.perform() alert = driver.switch_to_alert() alert.accept() # driver.quit() # Check for cron and disable. try: tab = CronTab() iter = tab.find_comment('ClockOutAuto') iter.enable(False) iter.clear() tab.remove(iter) tab.write() except: pass
def destroyJob(): cron = CronTab() iter = cron.find_comment(cmt) try: job = iter.next() while len(job) > 0: cron.remove(job) job = iter.next() except StopIteration: pass cron.write()
def setup_cron(): """ Sets up a cron job in the user's crontab in order to run the scan every minute. """ cron = CronTab(user=VINZ_USER) num_jobs = sum(1 for _ in cron.find_comment(VINZ_COMMENT)) if not num_jobs: job = cron.new(command=SCAN_COMMAND, comment=VINZ_COMMENT) job.minute.every(1) job.enable() cron.write()
def set_alarm(hour, minute, on): cron = CronTab('pi') job = cron.find_comment('Alarm').next() job.clear() job.hour.on(hour) job.minute.on(minute) if on: job.enable() else: job.enable(False) cron.write() return
def delete_reminder(id): id = ObjectId(id) ret = ReminderDao(None).delete(id) # Delete Cron Job tab = CronTab(user=True) jobs = tab.find_comment(str(id)) for j in jobs: tab.remove(j) #writes content to crontab tab.write() return ret
def get(self): '''create one spider''' name = self.get_argument('name') mins = self.get_argument('mins', '0') hour = self.get_argument('hour', '0') days = self.get_argument('days', '*') month = self.get_argument('month', '*') cron = CronTab(user=True) for job in cron.find_comment(name): job.setall('%s %s %s %s *' % (mins, hour, days, month)) cron.write() self.write(status_code(obj=format_job(job)))
def stop(self, provider="gce"): try: os.environ["KUBERNETES_PROVIDER"] = provider subprocess.check_call(['kube-down.sh']) # start the inactive app removal cron job cron = CronTab() jobs = cron.find_comment("binder-stop") for job in jobs: job.enable(False) cron.remove(job) cron.write_to_user(user=True) except subprocess.CalledProcessError as e: error_log(self.TAG, "Could not destroy the Kubernetes cluster")
def get(self,env_id,prod_id,ver_id): ver=self.session.query(Ver).get(ver_id) upload_path=os.path.join(os.path.dirname(__file__),'files/'+env_id+'/'+prod_id) filepath=os.path.join(upload_path,ver.file) if os.path.exists(filepath): os.remove(filepath) user_cron=CronTab(user=True) iter = user_cron.find_comment('autoops_'+ver.name+'_'+ver_id) for job in iter: user_cron.remove(job) user_cron.write_to_user(user=True) timepub=self.session.query(Timepub).filter(Timepub.ver_id==ver_id).one() self.session.delete(timepub) self.session.commit() self.session.delete(ver) self.session.commit() self.redirect("/ver/"+env_id+'/'+prod_id+'/0')
class _CrontabConfig(object): __comment = "Package Backup push tool" def __init__(self): from crontab import CronTab self.__cron = CronTab() def __get_existing(self): list_ = list(self.__cron.find_comment(self.__class__.__comment)) if len(list_) == 0: raise LookupError() return list_[0] def clear_existing(self): try: job = self.__get_existing() except LookupError: pass else: print("Removing existing crontab job: %s" % (self.__comment)) self.__cron.remove(job) self.__cron.write() def install(self): self.clear_existing() pushtool_filepath = _get_full_filepath(_TOOL_PUSHLIST_FILENAME) print("Installing tool [%s] as crontab job [%s]." % (pushtool_filepath, self.__comment)) job = self.__cron.new(command=pushtool_filepath) job.comment = self.__class__.__comment job.special = "@daily" self.__cron.write()
def alarm_time(crontab, line2): proc = subprocess.Popen(['crontab', '-lu', 'pi'], stdout=subprocess.PIPE) output = proc.stdout.read() if output == crontab: return [output, line2] else: cron = CronTab('pi') job = cron.find_comment('Alarm').next() alarm_hour = add_zero(str(job.hour)) alarm_min = add_zero(str(job.minute)) alarm_on = job.is_enabled() alarm_string = alarm_hour + ':' + alarm_min if alarm_on: line2 = "Alarm: " + alarm_string else: line2 = "Alarm off" line2 = line2 return [output, line2]
def write_crons(jobsmap): """Write crons related to the project (if missing). :param jobsmap: A mapping of job names to commands and schedules, like so: {"job1_name": ("cd /foobar; ./foo.bar", ("0", "0", "*", "*", "*"))} :type jobsmap: dict """ if CronTab is None: return crontab = CronTab(user=True) changes = 0 for name, (command, schedule) in jobsmap.items(): found_jobs = tuple(crontab.find_comment(name)) if not found_jobs: changes = 1 j = crontab.new(command=command) j.set_comment(name) j.setall(*schedule) elif len(found_jobs) > 1: print "WARNING: Found duplicate jobs for {} (command: '{}')"\ .format(name, command) if changes: crontab.write()
def _setup_crontab(): """Sets up the crontab if it hasn't already been setup.""" from crontab import CronTab #Since CI works out of a virtualenv anyway, the `ci.py` script will be #installed in the bin already, so we can call it explicitly. command = '/bin/bash -c "source ~/.cron_profile; workon {}; ci.py -cron"'.format(settings.venv) user = _get_real_user() if args["nolive"]: vms("Skipping cron tab configuration because 'nolive' enabled.") return cron = CronTab(user=user) #We need to see if the cron has already been created for this command. existing = False possible = cron.find_comment("pyci_cron") if len(list(possible)) > 0: if args["rollback"]: vms("Removing {} from cron tab.".format(command)) cron.remove_all(command) cron.write() db["cron"] = False _save_db() else: existing = True if not existing and not args["rollback"]: job = cron.new(command=command, comment="pyci_cron") #Run the cron every minute of every hour every day. if args["cronfreq"] == 1: vms("New cron tab configured *minutely* for {}".format(command)) job.setall("* * * * *") else: vms("New cron tab configured every {} minutes for {}.".format(args["cronfreq"], command)) job.setall("*/{} * * * *".format(args["cronfreq"])) cron.write() db["cron"] = True _save_db()
def getPolicyStatus(id, debug): """ Get the status of the enforcement of a policy @type id: string @param id: The policy id @type debug: boolean @param debug: If True the debug is enabled @rtype: string @return: The status of the enforcement of the policy: [QUEUED | RUNNING | DONE | WAITING] """ # define the paths where to find the irods rules and the related output rulePath = os.path.join(os.path.dirname(sys.path[0]), 'rules') ruleFiles = glob.glob(rulePath + '/replicate.' + id + '*') resPath = os.path.join(os.path.dirname(sys.path[0]), 'output') resFiles = glob.glob(resPath + '/response.' + id + '*') if ruleFiles is not None and len(ruleFiles) > 0: # the policy has been translated to a rule, but not executed status = 'QUEUED' if resFiles is not None and len(resFiles) > 0: cron = CronTab(user=True) cronJob_iter = cron.find_comment(id) if sum(1 for _ in cronJob_iter) == 0: # the rule has been executed status = 'DONE' else: # the rule has been executed, but it is still scheduled status = 'RUNNING' else: # the policy is not currently translated to a rule status = 'WAITING' if resFiles is not None and len(resFiles) > 0: # the rule has been executed and it is not scheduled status = 'DONE' return status
newconfig.set(config_section_name, 'serial_port', conf_inv.serial_port) newconfig.set(config_section_name, 'slave_number', conf_inv.slave_number) #except: # print sys.exc_info()[0] # continue if raw_input('Really write configuration file with %d inverters? (\'y\' to write): ' % len(inverters_alive)) == 'y': with open(CONFIGFILE, 'wb') as configfile: newconfig.write(configfile) raise SystemExit() elif sys.argv[1] == '--cron': job_comment = 'gavazzireader_identifier_comment__do_not_delete' if conf.read_cycle == None or conf.read_cycle not in ('5', '10', '15', '30'): raise SystemExit('No read cycle defined (%s). Configure with --configure' % conf.read_cycle) ct = CronTab() existingjob = ct.find_comment(job_comment) if len(existingjob) > 0: for ej in existingjob: ct.remove(ej) newjob = ct.new(command='%s %s'%(sys.executable, sys.argv[0]),comment=job_comment) newjob.minute.every(conf.read_cycle) ct.write() raise SystemExit() elif sys.argv[1] == '--pvoutputonly': send_batch_to_pvoutput() raise SystemExit() elif sys.argv[1] != None: print 'Unknown argument: ', sys.argv[1:] # if not os.path.exists(CONFIGFILE):