phplinuxbashcgi-bin

Executing rsync via web server bash script not working


I have a simple web php script that triggers a bash script

<?php
 if(isset($_POST['submit']))
 {
   $output=shell_exec('sh /usr/lib/cgi-bin/script.sh');
   echo $output;
 }
?>

<form action="" method="post">
<input type="submit" name="submit" value="Call my Shell Script">
</form>

I tried simple commands in script like rename and touch and it seemed to work fine.

rsa keys are set up and rsync works from terminal but I am getting the following:

Host key verification failed.^M
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at io.c(226) [sender=3.1.1]
Could not create directory '/var/www/.ssh'.^M
Host key verification failed.^M
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at io.c(226) [sender=3.1.1]

Contents of the script:

rsync -azv -e 'ssh -p 2222' /home/downloads/ user@ip:/home/downloads

I could be wrong but this seems to be a permission issue?


Solution

  • Your problem comes from "Host key verification failed".

    The script is executed with your www user (apache, www-data, ...). In your /etc/passwd, you have probably defined the home directory of that user to /var/www.

    If that user doesn't have the permission in that directory, it cannot create the .ssh folder to store the host key of the remote machine.

    So, you can manually create the folder :

    sudo mkdir /var/www/.ssh
    sudo chmod 600 /var/www/.ssh
    sudo chown <your-www-user> .ssh
    

    That's the first step, but the rsync will still fail because you have to accepte the remote host key.

    So, the second step is to connect from with SSH to the remote host to get the remote host key :

    su - <your-www-user>
    ssh -p 2222 user@ip
    

    Third problem, the login. you should configure a SSH connection per key to avoid having to type a password at each connection (either way, your rsync will fail).

    So, to generate the ssh key:

    su - <your-www-user>
    ssh-keygen -t rsa
    

    Copy your ssh public key to the remote host:

    su - <your-www-user>    
    ssh-copy-id user@ip
    

    That should do the trick.