【发布时间】:2017-05-03 15:26:03
【问题描述】:
我需要检测一个命令是否在它的子命令之一中有sudo 命令,到目前为止我有这个:
public function split_command($command) {
// this regex is not perfect but work
$separators = "/(?:\"[^\"\\\\]*(?:\\\\[\S\s][^\"\\\\]*)*\"|'[^'\\\\]*(?:\\\\[\S\s][^'\\\\]*)*')(*SKIP)(*F)|(\s+(?:&&|\|{1,2}|;)\s+)/";
$flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE;
return preg_split($separators, $command, null, $flags);
}
public function have_sudo($command) {
$re = "!^(sudo|" . shell_exec("which sudo") . ")!";
foreach ($this->split_command($command) as $part) {
if (preg_match($re, trim($part))) {
return true;
}
}
}
但是如果失败是命令看起来像这样:echo `sudo whoami`。如何解析命令以获取子 shell 列表。
它也应该适用于这样的命令:
$(some command; `other command (different command) $(some command)`)
它应该返回数组:
["some command; `other command (different command) $(some command)`",
"`other command (different command) $(some command)",
"different command", "some command"]
所以我可以在数组的每个元素上递归调用 have_sudo,另一个选项是从命令返回大多数外部子shell。
【问题讨论】:
-
Regex cannot possibly be used for (arbitrary and correct) parsing(这适用于 HTML 以及编程语言)。你需要一个解析器。