f.ardelian
f.ardelian

Reputation: 6956

How to execute remote SSH command in background using PHP exec()?

Is there a simple way to execute SSH commands in the background on remote machines from PHP without using ssh2_*? The PHP script is executed by the user from bash (no Apache involved), so it's not an issue of rights. I've tried doing this:

exec("ssh -f -o UnknownHostsFile=/dev/null -o StrictHostKeyChecking=no -i {$keyFile} {$user}@{$ip} {$remoteCommand} 2>&1 >/dev/null </dev/null");

For example:

exec("ssh -f -o UnknownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /home/data/id_rsa [email protected] '/home/user/script.sh ; exit' 2>&1 >/dev/null </dev/null");

All PHP variables have been escaped with escapeshellarg() and $remoteCommand is a bash script on the remote machine that sleeps for a few minutes and then starts executing some commands.

My problem is that if I execute that SSH command from bash, it gives control back to bash immediately. If I execute it from php using exec() it waits until the remote command executes. I've tried adding 2>&1 >/dev/null </dev/null after /home/user/script.sh, but the execution still doesn't return control to the PHP script.

Upvotes: 0

Views: 1635

Answers (1)

macjohn
macjohn

Reputation: 1803

I think you are missing an & at the end of your command for sending the execution to the background.

Upvotes: 1

Related Questions