Python的子进程模块可以替换crontab中shell中的脚本吗?

2024-05-28 18:53:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个任务,如果用户的主目录属于某个组,则应该将其更新为某个值。所以,假设一个用户被添加到某个组X,现在他/她的主目录应该是/home/X。我应该把它放到crontab上,我的问题是:

这样更安全吗?或者我应该总是喜欢用shell脚本编写这种任务吗?我仍然不清楚是否可以始终使用python来替换shell,因为处理它更简单。你知道吗

如果有人与在shell上使用python的专业人士有联系,并且在高效集群中真正推荐使用python,我将非常感谢。你知道吗


Tags: 用户脚本home集群shell主目录crontab专业人士
1条回答
网友
1楼 · 发布于 2024-05-28 18:53:46

the python subprocess page

Unlike some other popen functions, this implementation will never implicitly call a system shell. This means that all characters, including shell metacharacters, can safely be passed to child processes. If the shell is invoked explicitly, via shell=True, it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection vulnerabilities.

When using shell=True, the shlex.quote() function can be used to properly escape whitespace and shell metacharacters in strings that are going to be used to construct shell commands.

是否需要使用shell取决于如何调用它。从the subprocess popen info

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

因此,如果您可以使用元素列表调用子流程,而不是构建字符串,那么在python中这样做比在shell脚本中更容易,这应该不是问题。你知道吗

抱歉,这些链接是不同版本的python,看起来更清楚,但他们说了类似的事情,所以请检查您的python版本的正确的一个。你知道吗

相关问题 更多 >

    热门问题