简体   繁体   中英

How to execute shell from php script

I want to execute this command from a php script

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.

Depending on if you need the output of the script there are different approaches.

  • exec executes a command and return output to the caller.

  • 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.

  • system executes an external program and displays the output, but only the last line.

  • popen — creates a new process that is unidirectional read/writable

  • proc_open — creates a new process that supports bi-directional read/writable

For your scrapy script I would use a combination of popen and pclose as I don't think you need the script output.

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

From the PHP Manual - 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. You can also google for exec() which is a similiar function.

phpseclib - Download from http://phpseclib.sourceforge.net/ and include it in your project.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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