废话不说,show you my code,自己看。

这些公共方法可以直接用于执行sudo指令、验证用户密码、以及执行普通命令

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
def sudo_verify(password:str):
"""
在使用sudo命令之前最好调用一次该程序验证sudo密码的正确性。
:param password: 需要验证的密码
:return: 布尔类型 表示通过与否,字符串类型表示返回信息。(密码正确时返回空串)
"""
test_str = 'sudo test'

echo = subprocess.Popen(['echo', password], stdout=subprocess.PIPE, )

sudo = subprocess.Popen(['sudo', '-S', 'echo', test_str],
stdin=echo.stdout,
stdout=subprocess.PIPE,
# stderr=subprocess.PIPE
)

return_str = sudo.stdout.read().decode().replace("\n","")
if return_str == test_str:
return True,""
else:
return False,return_str.replace("\n","")


def sudo_do_something(password:str,command:list):
"""
调用此方法以执行需要加sudo的命令。
:param password: 密码
:param command: 列表,如:['./run.sh', test_type, debpkg]
:return:
"""
is_pass,rtstring=sudo_verify(password)
if is_pass:
echo = subprocess.Popen(['echo', password], stdout=subprocess.PIPE, )
sudo = subprocess.Popen(['sudo', '-S'] + command,
stdin=echo.stdout,
stdout=subprocess.PIPE,
# stderr=subprocess.PIPE
)

rtstring = sudo.stdout.read().decode()
return is_pass,rtstring

def command(command):
p = subprocess.Popen(command,
# stdin=echo.stdout,
stdout=subprocess.PIPE,
# stderr=subprocess.PIPE
)

rtstring = p.stdout.read().decode()
return rtstring