403Webshell
Server IP : 74.91.139.10  /  Your IP : 10.45.147.122
Web Server : Apache/2.4.67 (Unix)
System : Linux prod-iad-shwpweb1001e 5.14.0-687.26.1.el9_8.x86_64 #1 SMP PREEMPT_DYNAMIC Tue Jul 14 16:32:02 EDT 2026 x86_64
User : FAsyXTyKGY ( 3004)
PHP Version : 8.2.30
Disable Function : passthru,shell_exec,system
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /usr/share/oracle-cloud-agent/plugins/osms/osms/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /usr/share/oracle-cloud-agent/plugins/osms/osms/utils.py
#   Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
#   Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.org/licenses/UPL.

import errno
import logging
import logging.handlers
import os
import re
import subprocess
import time
try:  # python2
    from urllib2 import urlopen, Request
except ImportError:  # python3
    from urllib.request import urlopen, Request

from osms import config


# File used to keep track of the next time to update the package list on the server
PACKAGES_LAST_UPDATE_TIMESTAMP_FILE = "/var/lib/oracle-cloud-agent/plugins/osms/dbtimestamp"


def run_cmd(args, success_return_code=(0,), logargs=None):
    logargs = logargs or args
    logging.debug('run_cmd args: %s', logargs)
    proc = subprocess.Popen(
        args,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        close_fds=True,
    )
    stdoutdata, stderrdata = proc.communicate()
    if proc.returncode not in success_return_code:
        raise Exception(
            'Command: %s failed (%s): stderr: %s stdout: %s'
            % (logargs, proc.returncode, stderrdata, stdoutdata)
        )
    logging.debug('run_cmd returncode: %s, stdout: %s, stderr: %s', proc.returncode, stdoutdata, stderrdata)
    return stdoutdata.decode("utf-8")


def is_alx():
    try:
        run_cmd(['rpm', '-q', 'alx-utils'])
    except Exception:
        return False
    return True


def needs_restarting():
    '''
    needs-restarting may return 1 on failure. Parsing output is safer than
    checking return code to determine whether restarting is needed.
    '''
    try:
        output = run_cmd(['needs-restarting', '-r'], success_return_code=(0, 1))
        if 'Reboot is required' in output:
            return True
        return False
    except Exception as err:
        logging.debug('needs-restarting failed: %s', err)
        return False


def get_effective_kernel():
    try:
        return run_cmd(['ksplice', 'kernel', 'uname', '-r']).strip()
    except Exception as err:
        logging.debug('failed to get effective kernel: %s', err)
        return ''


def get_uptime():
    try:
        uptime = open("/proc/uptime", "r").read().split()
        try:
            result = [int(float(a)) for a in uptime]
        except (TypeError, ValueError):
            result = [a[:-3] for a in uptime]
        # We need to fit into xmlrpc's integer limits
        if result[1] > int(2) ** 31 - 1:
            result[1] = -1
        return result
    except Exception as err:
        logging.debug('get uptime failed: %s', err)
        return []


def touch_packages_last_update_timestamp():
    try:
        file_d = open(PACKAGES_LAST_UPDATE_TIMESTAMP_FILE, "w+")
        file_d.close()
        t = time.time()
        os.utime(PACKAGES_LAST_UPDATE_TIMESTAMP_FILE, (t, t))
    except Exception as err:
        logging.debug(
            "Unable to touch the packages last update timestamp file %s: %s",
            PACKAGES_LAST_UPDATE_TIMESTAMP_FILE,
            err
        )


def check_packages_last_update_timestamp():
    """Return True if package list was updated within 60 seconds
    """
    try:
        last = os.stat(PACKAGES_LAST_UPDATE_TIMESTAMP_FILE)[8]
        if int(time.time()) - last <= 60:
            return True
        return False
    except Exception as err:
        logging.debug(
            "Unable to check the packages last update timestamp file %s: %s",
            PACKAGES_LAST_UPDATE_TIMESTAMP_FILE,
            err
        )
        return False


def init_log(log_file, log_level):
    logger = logging.getLogger()
    logger.propagate = 0
    handler = logging.handlers.RotatingFileHandler(
        filename=log_file,
        maxBytes=5242880,  # 5 MiB
        backupCount=5
    )
    formatter = logging.Formatter(
        '[%(asctime)s %(process)d] %(levelname)s (%(module)s:%(lineno)d) %(message)s',
        '%Y-%m-%d %H:%M:%S'
    )
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.getLevelName(log_level))


def remove_file(filepath):
    try:
        os.unlink(filepath)
    except OSError as err:
        if err.errno != errno.ENOENT:
            raise


def update_file(filepath, old_entry, new_entry):
    if os.path.exists(filepath):
        with open(filepath, 'r+') as fobj:
            fcontent = fobj.read()
            if re.search(old_entry, fcontent, flags=re.MULTILINE):
                entry_re = re.compile(old_entry, flags=re.MULTILINE)
                fcontent = entry_re.sub(new_entry, fcontent)
                fobj.seek(0)
                fobj.truncate(0)
                fobj.write(fcontent)


def create_file(filepath, content):
    with open(filepath, 'w') as fobj:
        os.chmod(filepath, int('0600', 8))
        fobj.write(content)


def get_instance_ocid():
    cfg = config.initUp2dateConfig()
    instance_ocid = cfg['ocid']
    if not instance_ocid:
        request = Request('http://169.254.169.254/opc/v2/instance/id', headers={'Authorization': 'Bearer Oracle'})
        response = urlopen(request, timeout=10)
        if response.getcode() == 200:
            instance_ocid = response.read().strip()
        else:
            response = urlopen('http://169.254.169.254/opc/v1/instance/id', timeout=10)
            if response.getcode() == 200:
                instance_ocid = response.read().strip()
    if isinstance(instance_ocid, bytes):
        instance_ocid = instance_ocid.decode()
    if not instance_ocid:
        raise Exception('Could not retrieve instance OCID')
    return instance_ocid


def set_default_server_url():
    update_file(
        '/etc/oracle-cloud-agent/plugins/osms/up2date',
        r'serverURL=.*',
        'serverURL=https://enter.your.server.url.here/XMLRPC'
    )


def remove_system_id_file():
    remove_file('/etc/oracle-cloud-agent/plugins/osms/systemid')

Youez - 2016 - github.com/yon3zu
LinuXploit