Search code examples
phpsshrsync

Change rsync port with php exec


With PHP, I am trying to connect to a remote server and exec an rsync command :

$rsync_cmd = 'rsync -P -azv -e "ssh -p 1234" /dir/file.jpg root@remoteserver2:/dir/file.jpg';

exec('sudo ssh -tt root@remoteserver1 '.$rsync_cmd.' 2>&1', $output);

The remote connection is working fine but then when I am including my rsync command I got a port error "ssh: connect to host remoteserver2 port 22: Connection refused"

The correct port to use is 1234 and this command is working fine on the Terminal (shell) but php "exec" function dont want to take it ("ssh -p 1234"), any idea ?


Solution

  • Did you test it in Terminal by sshing into remoteserver1, and then executing the rsync command, or by executing the entire ssh-to-rsync command on one line? Because I'm pretty sure doing it in two steps will work, but one step won't. This is because when it's done as one step, the command string is parsed by the local shell (including doing quote and escape interpretation and removal) before it's passed over ssh to the remote shell (which then does another pass of quote and escape interpretation and removal). Those double-quotes in "ssh -p 1234" get parsed and removed by the local shell, so they don't have the intended effect of being parsed and applied by the remote shell.

    If I'm right about the problem, the solution is pretty simple: escape the double-quotes. That way the local shell will parse and remove the escapes, and pass the double-quotes through unmolested so the remote shell can see and apply them:

    $rsync_cmd = 'rsync -P -azv -e \"ssh -p 1234\" /dir/file.jpg root@remoteserver2:/dir/file.jpg';
    
    exec('sudo ssh -tt root@remoteserver1 '.$rsync_cmd.' 2>&1', $output);