-
Notifications
You must be signed in to change notification settings - Fork 13
/
envcp
executable file
·43 lines (38 loc) · 1.37 KB
/
envcp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python3
# envcp -- read environment of a running process
import argparse
import os
import subprocess
parser = argparse.ArgumentParser()
parser.description = "Get environment variables from a running process."
# This is different from `sudo envcp` as it allows the command to still be run
# with the invoker's privileges.
parser.add_argument("-s", "--sudo",
action="store_true",
help="read environment with root privileges")
parser.add_argument("pid",
metavar="<pid>",
type=int,
help="process to copy environment from")
parser.add_argument("command",
metavar="<command>",
nargs="*",
default=["/usr/bin/env"],
help="command to run with the new environment")
args = parser.parse_args()
try:
file = "/proc/%d/environ" % args.pid
with open(file, "rb") as fd:
buf = fd.read()
except PermissionError as e:
if args.sudo:
res = subprocess.run(["sudo", "cat", file], stdout=subprocess.PIPE)
buf = res.stdout
else:
exit("envcp: %s" % e)
env = dict(kv.split(b"=", 1)
for kv in buf.split(b"\0")
if kv != b"")
if not env:
exit("envcp: environment was empty")
os.execvpe(args.command[0], args.command, env)