示例#1
0
def worker():
    print("Filename corresponding to the  controlling terminal:")
    print(os.ctermid())

    print("ID do processo:")
    print(os.getppid())

    print("ID of the current process group:")
    print(os.getpgrp())

    print("Old Priority:")
    print(os.getpriority(os.PRIO_PROCESS, os.getpid()))

    os.setpriority(os.PRIO_PROCESS, os.getpid(), 2)

    print("New Priority:")
    print(os.getpriority(os.PRIO_PROCESS, os.getpid()))

    print("Information identifying the current operating system:")
    print(os.uname())

    print("The round-robin quantum in seconds for the process with PID pid")
    print(os.sched_rr_get_interval(0))

    return
示例#2
0
def about_user():
    """Show information about the user"""
    if parameters["User"]:
        print("[User]")
        user = getpass.getuser()
        print("getpass.getuser()={}".format(user))
        print("os.getlogin()={}".format(os.getlogin()))
        if sys_type() == "Unix":
            print('pwd.getpwnam("{}")={}'.format(user, pwd.getpwnam(user)))
            print("os.getgroups()={}".format(os.getgroups()))
            for group_id in os.getgroups():
                print("grp.getgrgid({})={}".format(group_id,
                                                   grp.getgrgid(group_id)))
        elif sys_type() == "Windows":
            if os.environ["USERNAME"]:
                print('os.environ["USERNAME"]={}'.format(
                    os.environ["USERNAME"]))
            if os.environ["USERPROFILE"]:
                print('os.environ["USERPROFILE"]={}'.format(
                    os.environ["USERPROFILE"]))
            if os.environ["USERDOMAIN"]:
                print('os.environ["USERDOMAIN"]={}'.format(
                    os.environ["USERDOMAIN"]))
            if os.environ["USERDOMAIN_ROAMINGPROFILE"]:
                print('os.environ["USERDOMAIN_ROAMINGPROFILE"]={}'.format(
                    os.environ["USERDOMAIN_ROAMINGPROFILE"]))
            if os.environ["HOME"]:
                print('os.environ["HOME"]={}'.format(os.environ["HOME"]))
            if os.environ["HOMEDRIVE"]:
                print('os.environ["HOMEDRIVE"]={}'.format(
                    os.environ["HOMEDRIVE"]))
            if os.environ["HOMEPATH"]:
                print('os.environ["HOMEPATH"]={}'.format(
                    os.environ["HOMEPATH"]))
        print()

        print("[User/Process]")
        if sys_type() == "Unix":
            print("os.getuid()={}".format(os.getuid()))
            print("os.getgid()={}".format(os.getgid()))
            print("os.geteuid()={}".format(os.geteuid()))
            print("os.getegid()={}".format(os.getegid()))
            print("os.getresuid()={}".format(os.getresuid()))
            print("os.getresgid()={}".format(os.getresgid()))
        print()

        print("[Process]")
        pid = os.getpid()
        print("os.getpid()={}".format(pid))
        print("os.getppid()={}".format(os.getppid()))
        if sys_type() == "Unix":
            print("os.getpgid({})={}".format(pid, os.getpgid(pid)))
            print("os.getpgrp()={}".format(os.getpgrp()))
            print("os.getpriority(os.PRIO_PROCESS, 0)={}".format(
                os.getpriority(os.PRIO_PROCESS, 0)))
            print("os.getpriority(os.PRIO_PGRP, 0)={}".format(
                os.getpriority(os.PRIO_PGRP, 0)))
            print("os.getpriority(os.PRIO_USER, 0)={}".format(
                os.getpriority(os.PRIO_USER, 0)))
        print()
 def test_set_process_priority(self):
     old_nice = os.getpriority(os.PRIO_PROCESS, 0)
     prio_set = set_process_priority(ionice=True)
     new_nice = os.getpriority(os.PRIO_PROCESS, 0)
     self.assertEqual(old_nice, 0)  # a == b
     self.assertTrue(isinstance(prio_set, bool))  # bool(x) is True
     self.assertTrue(prio_set)  # bool(x) is True
     self.assertEqual(new_nice, 19)  # a == b
def test_set_process_priority():
    old_nice = os.getpriority(os.PRIO_PROCESS, 0)
    prio_set = set_process_priority(ionice=True)
    new_nice = os.getpriority(os.PRIO_PROCESS, 0)
    assert old_nice == 0
    assert isinstance(prio_set, bool)
    assert prio_set
    assert new_nice == 19
示例#5
0
def test_notification_resp_success() -> None:
    filt = pyseccomp.SyscallFilter(pyseccomp.ALLOW)
    filt.add_rule(pyseccomp.NOTIFY, "setpriority")

    pid = os.fork()
    if pid == 0:
        try:
            if cov_init is not None:
                cov_init()

            filt.load()

            pid = os.fork()
            if pid == 0:
                try:
                    os.setpriority(os.PRIO_PROCESS, 0, os.getpriority(os.PRIO_PROCESS, 0))
                except BaseException:  # pylint: disable=broad-except
                    traceback.print_exc()
                    os._exit(1)  # pylint: disable=protected-access
                finally:
                    os._exit(0)  # pylint: disable=protected-access

            notif = filt.receive_notify()

            assert notif.syscall == pyseccomp.resolve_syscall(pyseccomp.Arch.NATIVE, "setpriority")
            assert notif.syscall_arch == pyseccomp.system_arch()
            assert notif.syscall_args[:3] == [
                os.PRIO_PROCESS,
                0,
                os.getpriority(os.PRIO_PROCESS, 0),
            ]

            filt.respond_notify(pyseccomp.NotificationResponse(0, 0, notif.id, 1))

            _, wstatus = os.waitpid(pid, 0)
            assert os.WIFEXITED(wstatus)
            assert os.WEXITSTATUS(wstatus) == 0

            if cov_cleanup is not None:
                cov_cleanup()

        except BaseException:  # pylint: disable=broad-except
            traceback.print_exc()
            os._exit(1)  # pylint: disable=protected-access
        finally:
            os._exit(0)  # pylint: disable=protected-access

    _, wstatus = os.waitpid(pid, 0)
    assert os.WIFEXITED(wstatus)
    assert os.WEXITSTATUS(wstatus) == 0
示例#6
0
def test_getpriority_pid_1() -> None:
    filt = pyseccomp.SyscallFilter(pyseccomp.ALLOW)

    filt.add_rule(pyseccomp.ERRNO(errno.EPERM), "getpriority",
                  pyseccomp.Arg(1, pyseccomp.EQ, 1))

    pid = os.fork()
    if pid == 0:
        try:
            os.getpriority(os.PRIO_PROCESS, 0)
            os.getpriority(os.PRIO_PROCESS, 1)

            filt.load()

            os.getpriority(os.PRIO_PROCESS, 0)

            with pytest.raises(PermissionError):
                os.getpriority(os.PRIO_PROCESS, 1)

        except Exception:  # pylint: disable=broad-except
            traceback.print_exc()
            os._exit(1)  # pylint: disable=protected-access
        finally:
            os._exit(0)  # pylint: disable=protected-access

    _, wstatus = os.waitpid(pid, 0)
    assert os.WIFEXITED(wstatus)
    assert os.WEXITSTATUS(wstatus) == 0
示例#7
0
def set_process_priority(nice: bool = True,
                         ionice: bool = False,
                         cpulimit: int = 0) -> bool:
    """Set process name and cpu priority."""
    w = " may delay I/O Operations, not recommended on user-facing GUI!."
    try:
        if nice:
            _old = os.getpriority(os.PRIO_PROCESS, 0)
            os.nice(19)  # smooth cpu priority
            log.debug(f"Process CPUs Priority set: from {_old} to 19.")
        elif ionice and which("ionice"):
            log.warning("ionice" + w)
            cmnd = f"{which('ionice')} --ignore --class 3 --pid {os.getpid()}"
            call(cmnd, shell=True)  # I/O nice,should work on Linux and Os X
            log.debug(f"Process PID {os.getpid()} I/O Priority set to: {cmnd}")
        elif cpulimit and which("cpulimit"):
            log.warning("cpulimit" + w)
            log.debug("Launching 1 background 'cpulimit' child subprocess...")
            cpulimit = int(cpulimit if cpulimit > 4 else 5)  # makes 5 the min.
            command = "{0} --include-children --pid={1} --limit={2}".format(
                which("cpulimit"), os.getpid(), cpulimit)
            proces = Popen(command, shell=True)  # This launch a subprocess.
            atexit.register(proces.kill)  # Force Kill subprocess at exit.
            log.debug(f"Process CPUs Max Limits capped to: {command}.")
    except Exception as error:
        log.warning(error)
        return False  # this may fail on windows and its normal, so be silent.
    else:
        return True
示例#8
0
def increase_my_priority(increase):
    # Set the reader process to high priority to reduce frame processing latency,
    # we lose frames under load otherwise, hopefully this will reduce the lossage
    # TODO Handle windows if necessary
    curpriority = os.getpriority(os.PRIO_PROCESS, 0)
    logger.debug("Reader default priority is {}".format(curpriority))
    try:
        os.setpriority(os.PRIO_PROCESS, 0, (curpriority - increase))
        logger.warn("Increased priority to: {}".format(curpriority-increase))
    except PermissionError:
        logger.warn(
            "Inadequate permissions to increase the reader priority,consider running with sudo, priority is: {}".
            format(curpriority))

    newpriority = os.getpriority(os.PRIO_PROCESS, 0)
    logger.debug("Reader new priority is {}".format(newpriority))
示例#9
0
def proc_getpriority(proc: "Process") -> int:
    pid = proc.pid

    if pid == 0:
        raise PermissionError

    return os.getpriority(os.PRIO_PROCESS, pid)
示例#10
0
def ql_syscall_getpriority(ql, getpriority_which, getpriority_who, null1,
                           null2, null3, null4):
    base = os.getpriority(getpriority_which, getpriority_who)
    regreturn = base
    ql.nprint("getpriority(0x%x, 0x%x) = %d" %
              (getpriority_which, getpriority_who, regreturn))
    ql_definesyscall_return(ql, regreturn)
示例#11
0
def worker():
    """worker function"""
    print("Bloco de Controle |", os.getegid())
    print("Status:           |")
    print("Group:            |", os.getpgrp())
    print("ID:               |", os.getpid())
    print("Hierarquia        |", )
    print("pai:              |", os.getppid())
    print("prioridade:       |", os.getpriority(os.PRIO_PROCESS, os.getpid()))
    print('-----------------------')
    return
示例#12
0
def log_sysinfo(app: Flask, config: Config):
    app.logger.info("ZMQ:")
    app.logger.info("  zmq version: %s", zmq.zmq_version())
    app.logger.info("  pyzmq version: %s", zmq.pyzmq_version())
    app.logger.info("  zmq includes: %s", zmq.get_includes())
    app.logger.info("  zmq library dirs: %s", zmq.get_library_dirs())
    app.logger.info("  has: %s", [c for c in ZMQ_CAPABILITIES if zmq.has(c)])
    app.logger.info("socket:")
    app.logger.info("  fqdn: %s", socket.getfqdn())
    app.logger.info("  has_ipv6: %s", socket.has_ipv6)
    app.logger.info("  hostname: %s", socket.gethostname())
    app.logger.info("  interfaces: %s", [i[1] for i in socket.if_nameindex()])
    app.logger.info("os:")
    app.logger.info("  ctermid: %s", os.ctermid())
    app.logger.info("  cwd: %s", os.getcwd())
    app.logger.info("  groups: %s", os.getgroups())
    app.logger.info("  pgid: %d", os.getpgid(0))
    app.logger.info("  pgrp: %d", os.getpgrp())
    app.logger.info("  pid: %d", os.getpid())
    app.logger.info("  ppid: %d", os.getppid())
    app.logger.info("  priority_process: %d",
                    os.getpriority(os.PRIO_PROCESS, 0))
    app.logger.info("  priority_pgrp: %d", os.getpriority(os.PRIO_PGRP, 0))
    app.logger.info("  priority_user: %d", os.getpriority(os.PRIO_USER, 0))
    app.logger.info("  resuid: ruid=%d, euid=%d, suid=%d", *os.getresuid())
    app.logger.info("  resgid: rgid=%d, egid=%d, sgid=%d", *os.getresgid())
    app.logger.info("  sid: %d", os.getsid(0))
    app.logger.info("  supports_bytes_environ: %s", os.supports_bytes_environ)
    app.logger.info("  uname: %s", os.uname())
    app.logger.info("  cpu_count: %d", os.cpu_count())
    app.logger.info("platform:")
    app.logger.info("  %s", platform.platform())
    app.logger.info("  python_build: %s", platform.python_build())
    app.logger.info("  python_compiler: %s", platform.python_compiler())
    app.logger.info("  python_branch: %s", platform.python_branch())
    app.logger.info("  python_implementation: %s",
                    platform.python_implementation())
    app.logger.info("  python_revision: %s", platform.python_revision())
    app.logger.info("  python_version: %s", platform.python_version())
    app.logger.info("getpass:"******"  user: %s", getpass.getuser())
示例#13
0
def test_process_priority(get_configuration, configure_environment,
                          restart_syscheckd, wait_for_fim_start):
    """Check if the wazuh-syscheckd service priority is updated correctly using
       <process_priority> tag in ossec.conf.
    """
    check_apply_test({'ossec_conf'}, get_configuration['tags'])

    priority = int(get_configuration['metadata']['process_priority'])
    process_name = 'wazuh-syscheckd'
    syscheckd_process = get_process(process_name)

    assert syscheckd_process is not None, f'Process {process_name} not found'
    assert (os.getpriority(os.PRIO_PROCESS, syscheckd_process.pid)) == priority, \
        f'Process {process_name} has not updated its priority.'
def set_process_priority(nice=True, ionice=False):
    """Set process name and cpu priority."""
    w = "IONice may delay I/O Operations, not recommended on user-facing GUI!."
    try:
        if nice:
            old = os.getpriority(os.PRIO_PROCESS, 0)
            os.nice(19)  # smooth cpu priority
            log.debug("Process CPUs Priority set: from {0} to 19.".format(old))
        elif ionice and which("ionice"):
            log.warning(w)
            command = "{0} --ignore --class 3 --pid {1}".format(
                which("ionice"), os.getpid())
            call(command, shell=True)  # I/O nice,should work on Linux and Os X
            log.debug("Process I/O Priority set to: {0}.".format(command))
    except Exception as error:
        log.warning(error)
        return False  # this may fail on windows and its normal, so be silent.
    else:
        return True
示例#15
0
 def nice(self):
     return os.getpriority(os.PRIO_PROCESS, self.tpid)
示例#16
0
 def nice(self):
     return os.getpriority(os.PRIO_PROCESS, self.tpid)
示例#17
0
def ql_syscall_getpriority(ql: Qiling, which: int, who: int):
    try:
        regreturn = os.getpriority(which, who)
    except:
        regreturn = -1
    return regreturn
示例#18
0
p(os.supports_dir_fd)
p(os.supports_effective_ids)  # Builtins that support effective ids
p(os.supports_fd)  # Builtins that support fd
p(os.supports_follow_symlinks)  # Builtins that support following symlinks

# PROCESS, GROUP, and USER IDS
p(os.getegid())  # Get he effective group id f the current process.
p(os.geteuid())  # Return the current process's effective user id.
p(os.getgid())  # Get the current processes real group id
p(os.getgrouplist(os.getlogin(), os.getgid()))
p(os.getgroups(
))  # return list of supplemental group ids associated with the current process
p(
    os.getlogin()
)  # Return the name of the user logged in on the controlling terminal of the process

# PROCESS ID
p(os.getpgid(os.getpid()))
p(os.getpid())
p(os.getpgrp())
p(os.getppid())

# PROCESS SCHEDULING PRIORITY
p(os.getpriority(os.PRIO_PROCESS, os.getpid()))
p(os.getpriority(os.PRIO_PGRP, os.getpid()))
# p(os.getpriority(os.PRIO_USER, os.getpid()))

p(os.getuid())  # get the current processes real user id
# p(os.umask(mask)) # Set umask, return the prev

# FILE OBJECT CREATION
示例#19
0
def ql_syscall_getpriority(ql: Qiling, getpriority_which: int,
                           getpriority_who: int):
    return os.getpriority(getpriority_which, getpriority_who)
def check_prio(pid):
    # try to retrieve scheduling prio
    os.getpriority(os.PRIO_PROCESS, pid)