Skip to content

Instantly share code, notes, and snippets.

@BoredHackerBlog
Created July 17, 2026 15:38
Show Gist options
  • Select an option

  • Save BoredHackerBlog/d70cb44d00be7d36785e5705871d4b59 to your computer and use it in GitHub Desktop.

Select an option

Save BoredHackerBlog/d70cb44d00be7d36785e5705871d4b59 to your computer and use it in GitHub Desktop.
some code for scheduling things to help me with some testing/research stuff
#!/usr/bin/env python3
# Notice: This is my first AI coded project.
# I did research, wrote original python code, and had AI rewrite it because I was tired and wanted to sleep.
# I'd never write code with error handling so you know I didn't write this.
# edit this...
SPLUNK_HOST = '10.0.0.72'
SPLUNK_PORT = '8000'
SPLUNK_USERNAME = 'admin'
SPLUNK_PASSWORD = 'freeneedsnopassword'
WEBHOOK_URL = ''
import os
import yaml
import requests
import urllib3
import time
import sys
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import threading
thread_local = threading.local()
def get_thread_local_session():
return getattr(thread_local, 'session', None)
def set_thread_local_session(session):
thread_local.session = session
def create_new_session():
s = requests.Session()
s.verify = False
login_url = f'http://{SPLUNK_HOST}:{SPLUNK_PORT}/en-US/account/login'
cookies = {'cval': '1'}
headers = {}
data = {
'cval': '1',
'username': SPLUNK_USERNAME,
'password': SPLUNK_PASSWORD,
'return_to': '/en-US/',
'set_has_logged_in': 'true',
}
try:
r = s.post(login_url, cookies=cookies, headers=headers, data=data)
r.raise_for_status()
except Exception as e:
print(f"Login failed: {e}")
return None
try:
splunkweb_csrf_token = s.cookies['splunkweb_csrf_token_8000']
splunkd_8000 = s.cookies['splunkd_8000']
except KeyError as e:
print(f"Failed to extract cookies: {e}")
return None
s.headers.update({
'X-Requested-With': 'XMLHttpRequest',
'X-Splunk-Form-Key': splunkweb_csrf_token
})
s.cookies.update({
'splunkweb_csrf_token_8000': splunkweb_csrf_token,
'splunkd_8000': splunkd_8000
})
return s
def run_splunk_search(search_query, earliest_time):
"""
Run a Splunk search and return the result count and job sid.
Args:
search_query (str): The Splunk search query to execute
earliest_time (str): The earliest time for the search (e.g., "-1h@h")
Returns:
tuple: (result_count, sid) where result_count is an integer and sid is a string
Returns (0, None) on failure
"""
s = get_thread_local_session()
if s is None:
s = create_new_session()
set_thread_local_session(s)
if s is None:
print("Failed to create session")
return 0, None
s.verify = False
# Build search job data
search_data = {
'rf': '*',
'auto_cancel': '62',
'status_buckets': '300',
'output_mode': 'json',
'custom.search': search_query,
'search': search_query,
'earliest_time': earliest_time,
'latest_time': 'now',
'ui_dispatch_app': 'search',
'preview': '1',
'adhoc_search_level': 'smart',
'workload_pool': '',
'indexedRealtime': '',
'sample_ratio': '1',
'check_risky_command': 'false',
'provenance': 'UI%3ASearch'
}
# Create search job
search_url = f'http://{SPLUNK_HOST}:{SPLUNK_PORT}/en-US/splunkd/__raw/servicesNS/admin/search/search/v2/jobs'
try:
r = s.post(search_url, data=search_data)
r.raise_for_status()
sid = r.json()['sid']
except Exception as e:
print(f"Failed to create search job: {e}")
# Try to re-login and retry once
s = create_new_session()
set_thread_local_session(s)
if s is None:
print("Failed to create session after re-login")
return 0, None
try:
r = s.post(search_url, data=search_data)
r.raise_for_status()
sid = r.json()['sid']
except Exception as e2:
print(f"Failed to create search job after re-login: {e2}")
return 0, None
# Wait for job to complete
while True:
job_url = f'http://{SPLUNK_HOST}:{SPLUNK_PORT}/en-US/splunkd/__raw/servicesNS/nobody/search/search/v2/jobs/{sid}'
try:
r = s.get(job_url, params={'output_mode': 'json'})
r.raise_for_status()
job_content = r.json()['entry'][0]['content']
if job_content.get('isDone'):
break
except Exception as e:
print(f"Error checking job status: {e}")
return 0, sid
time.sleep(1)
result_count = int(job_content['resultCount'])
return result_count, sid
def load_yaml_files(directory):
"""
Load all .yaml and .yml files from the given directory.
Args:
directory (str): Path to directory to search
Returns:
list: List of full file paths to YAML files
"""
yaml_files = []
for ext in ('.yaml', '.yml'):
yaml_files.extend([os.path.join(directory, f) for f in os.listdir(directory) if f.endswith(ext)])
return yaml_files
def load_yaml(filepath):
"""
Load a YAML file and return its contents.
Args:
filepath (str): Path to the YAML file
Returns:
dict: Parsed YAML content
"""
with open(filepath, 'r') as f:
return yaml.safe_load(f)
def job_function(rule, search, back):
"""
Job function to run Splunk search and send notification if results > 0.
Args:
rule (str): Name of the rule (for identification)
search (str): Splunk search query to execute
back (str): Earliest time for the search (e.g., "-1h@h")
"""
print(f"Running job for rule: {rule}")
print(f"Search: {search}")
print(f"Earliest time: {back}")
result_count, sid = run_splunk_search(search, back)
print(f"Result count: {result_count}")
if sid:
print(f"Job SID: {sid}")
if result_count > 0 and sid:
splunk_url = f"http://{SPLUNK_HOST}:{SPLUNK_PORT}/en-US/app/search/search?sid={sid}"
payload = {
"rule": rule,
"count": result_count,
"splunk_url": splunk_url
}
try:
response = requests.post(WEBHOOK_URL, json=payload)
print(f"Notification sent to webhook: {response.status_code}")
except Exception as e:
print(f"Failed to send notification: {e}")
else:
print("No results found or SID missing, no notification sent.")
def setup_scheduler(scheduler, directory):
"""
Scan directory for yaml files and schedule jobs.
Args:
scheduler (BackgroundScheduler): The APScheduler instance
directory (str): Directory containing rule YAML files
"""
yaml_files = load_yaml_files(directory)
if not yaml_files:
print("No YAML files found in directory:", directory)
return
for yaml_file in yaml_files:
try:
data = load_yaml(yaml_file)
rule = data.get('rule')
cron_expr = data.get('cron')
back = data.get('back')
search = data.get('search')
if rule is None or cron_expr is None or back is None or search is None:
print(f"Skipping {yaml_file}: missing rule, cron, back, or search field")
continue
job_func = lambda r=rule, s=search, b=back: job_function(r, s, b)
trigger = CronTrigger.from_crontab(cron_expr)
scheduler.add_job(job_func, trigger, id=yaml_file, name=f"Job for {yaml_file}")
print(f"Scheduled job from {yaml_file}: rule='{rule}', search='{search}', back='{back}', cron='{cron_expr}'")
except Exception as e:
print(f"Failed to process {yaml_file}: {e}")
def main():
"""
Main application entry point.
"""
# Look for rules in the rules/ subdirectory
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'rules')
scheduler = BackgroundScheduler()
setup_scheduler(scheduler, directory)
scheduler.start()
print("Scheduler started. Press Ctrl+C to exit.")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
scheduler.shutdown()
print("\nScheduler stopped.")
if __name__ == '__main__':
try:
import yaml
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
except ImportError as e:
print(f"Missing required package: {e}. Please install pyyaml and apscheduler.")
sys.exit(1)
main()
rule: "seven"
cron: "*/1 * * * *"
back: "-1h@h"
search: "|makeresults count=7"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment