-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchroot.py
101 lines (73 loc) · 2.77 KB
/
chroot.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from tarfile import open, is_tarfile
from subprocess import Popen, PIPE, call
from os import popen, system
from pathlib import Path
import distro
# Chroot for packaging
class chroot:
def __init__(self):
self.banana = "0"
self.distro = {
"name":distro.linux_distribution()[0],
"version":distro.linux_distribution()[1],
"release":distro.linux_distribution()[2],
}
self.home = str(Path.home())
self.chroot_home = self.home+"/.spark_chroot"
def cprint(self,msg=None,trace=None):
if not trace and msg:
print("[Chroot]",msg)
else:
print("[Chroot] Chroot trace:\n",trace)
def run_in_chroot(self,cmd):
# Mount points
run_command("sudo mount -t proc /proc proc".split(" "),self.chroot_home)
run_command("sudo mount --rbind /sys sys".split(" "),self.chroot_home)
run_command("sudo mount --rbind /dev dev".split(" "),self.chroot_home)
# Enter chroot
system(f'''cd $HOME/.spark_chroot && sudo chroot . /bin/bash -c "{cmd}" ''')
self.close_chroot()
def shell_chroot(self):
# export PS1='\\e[0;32m(Chroot)[\\u@\\h \\W]\\$ \\e[0m'
# Mount points
run_command("sudo mount -t proc /proc proc".split(" "),self.chroot_home)
run_command("sudo mount --rbind /sys sys".split(" "),self.chroot_home)
run_command("sudo mount --rbind /dev dev".split(" "),self.chroot_home)
# Enter chroot
run_command("sudo chroot . /bin/bash".split(" "),self.chroot_home)
self.close_chroot()
def build_chroot(self):
run_command(f"mkdir -p .spark_chroot".split(" "),self.home)
# Check distro
if self.distro['name'] == "Ubuntu":
# Create an ubuntu chroot
run_command(f"sudo debootstrap --variant=buildd {self.distro['release']} .spark_chroot".split(" "),self.home)
self.cprint("Done, validating...")
def close_chroot(self):
run_command("sudo umount sys dev".split(" "),self.home)
"""
Clean chroot [Later tm]
rm -fr chroot/root/.bash_history
rm -fr chroot/var/log/*
rm -fr chroot/var/cache/apt/archives/*
rm -fr chroot/tmp/*
"""
def run_command(command, dir):
"""A daemon, runs the command and gives output\n
Will parse stuff
Args:
command (string): What command to run
Returns:
String: Realtime output to the inputted command
"""
process = Popen(command, stdout=PIPE, cwd=dir)
alive = True
while alive:
output = process.stdout.readline()
print(output.strip().decode("utf-8")) if output else None
alive = process.poll() is None
rc = process.poll()
return rc
chroot = chroot()
chroot.build_chroot()
chroot.shell_chroot()