Created
February 6, 2024 08:21
-
-
Save litnimax/ce69757f7b6fb4aaa18fe94594113c25 to your computer and use it in GitHub Desktop.
Fetch Asterisk Plus SIP peers script (with caching)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse | |
import logging | |
import logging.config | |
import os | |
import sys | |
import yaml | |
from datetime import datetime | |
import requests | |
LOG_FILE = '/var/log/asterisk/get_odoo_conf.log' | |
LOG_CONFIG = """version: 1 | |
formatters: | |
default: | |
format: '%(asctime)s - %(name)s:%(lineno)s - %(levelname)s - %(message)s' | |
handlers: | |
file: | |
class: logging.FileHandler | |
filename: {} | |
formatter: default | |
root: | |
level: {} | |
handlers: [file] | |
""".format(LOG_FILE, os.environ.get('LOG_LEVEL', 'INFO').upper()) | |
log_config = yaml.safe_load(LOG_CONFIG) | |
logging.config.dictConfig(log_config) | |
logger = logging.getLogger(__name__) | |
CACHE_DIR = '/etc/asterisk/conf_cache' | |
try: | |
if not os.path.isdir(CACHE_DIR): | |
os.mkdir(CACHE_DIR) | |
except Exception: | |
logger.error('Cannot create %s', CACHE_DIR) | |
sys.exit(1) | |
def get_conf(url, token): | |
try: | |
response = requests.request("GET", url, | |
headers={'x-security-token': token}) | |
response.raise_for_status() | |
return response.text | |
except Exception as e: | |
logger.error('Odoo connection error: %s', e) | |
return False | |
def main(): | |
arg_parser = argparse.ArgumentParser() | |
arg_parser.add_argument("-t", "--token", help="Server Token: 'xxxxxxxx-xxxxxxxx-xxxxxxxx'", required=True) | |
arg_parser.add_argument("-u", "--url", help="Server URL: 'http://localhost:8069'", required=True) | |
args = arg_parser.parse_args() | |
conf = get_conf(token=args.token, url=args.url) | |
file_name = os.path.join( | |
CACHE_DIR, | |
'{}.conf'.format(args.url.split('/')[-1]), | |
) | |
try: | |
if conf: | |
with open(file_name, "w") as file: | |
file.write(conf) | |
file.close() | |
print(conf) | |
else: | |
timestamp = os.path.getmtime(file_name) | |
date = datetime.fromtimestamp(timestamp) | |
conf = open(file_name, "r").read() | |
logger.warning('Using cached conf.') | |
print(conf) | |
except Exception as e: | |
logger.error('Error: %s', e) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment