简体   繁体   English

如何从PHP脚本执行Shell

[英]How to execute shell from php script

I want to execute this command from a php script 我想从php脚本执行此命令

scrapy crawl example -a siteid=100

i tried this : 我尝试了这个:

<?php
$id = 100;
exec('scrapy crawl example -a siteid= $id' $output, $ret_code);
?>

try this: 尝试这个:

<?php
$id = 100;
exec('scrapy crawl example -a siteid=$id 2>&1', $output);
return $output;
?>

You actually need to redirect output in order to get it. 实际上,您需要重定向输出以获得它。

If you don't need the output, and just to execute the command, you only need the first part, like this: 如果不需要输出,而只是执行命令,则只需要第一部分,如下所示:

exec('scrapy crawl example -a siteid=' . $id);

because you don't put the parameter inside the ' ', you put it outside, read about text concat in PHP. 因为您没有将参数放在''内,所以将其放在外面,请阅读有关PHP中的文本concat的信息。

Depending on if you need the output of the script there are different approaches. 根据您是否需要脚本的输出,有不同的方法。

  • exec executes a command and return output to the caller. exec执行命令并将输出返回给调用方。

  • passthru function should be used in place of exec when the output from the Unix command is binary data which needs to be passed directly back to the browser. 当Unix命令的输出是二进制数据,需要直接传递回浏览器时,应该使用passthru函数代替exec。

  • system executes an external program and displays the output, but only the last line. system执行外部程序并显示输出,但仅显示最后一行。

  • popen — creates a new process that is unidirectional read/writable popen创建一个单向可读/可写的新进程

  • proc_open — creates a new process that supports bi-directional read/writable proc_open —创建一个支持双向可读写的新进程

For your scrapy script I would use a combination of popen and pclose as I don't think you need the script output. 对于您的脚本,我会结合使用popenpclose因为我认为您不需要脚本输出。

pclose(popen("scrapy crawl example -a siteid=$id > /dev/null &", 'r'));

From the PHP Manual - shell_exec() PHP手册-shell_exec()

$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";

So in short, there is a native PHP command to do what you want. 简而言之,有一个本地PHP命令可以执行您想要的操作。 You can also google for exec() which is a similiar function. 您也可以在Google上搜索exec() ,这是一个类似的函数。

phpseclib - Download from http://phpseclib.sourceforge.net/ and include it in your project. phpseclib-http://phpseclib.sourceforge.net/下载,并将其包含在您的项目中。

include('Net/SSH2.php');

$ssh = new Net_SSH2("Your IP Here");
if (!$ssh->login('Your User', 'Your Password')) {
    exit('Login Failed');
}
$id = 100;
echo "<pre>";
print_r($ssh->exec('scrapy crawl example -a siteid= $id'));

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM