run a script.sh from php / apache where sftp perform connection and upload

June 17, 2018 984 views
CentOS PHP

Hi All,
assume that I have a script.sh that runs perfectly if launched from a root shell.

#!/usr/bin/sh
sftp -oPort=22 user@localhost<<EOF
put /var/www/html/xml/file.xml /var/www/html/destination/file.xml
exit
EOF

what I need is to run this script from php / apache, I’ve just try a lot and what give me the possibility to see something of what happen is a code like that :

$cmd = '/bin/sh /var/www/html/script.sh';

    if(exec("$cmd  2>&1", $output, $return_var)) {
    print_r($output);
    $upl.= "<br>";
    print_r($return_var);

I receive that :
Array ( [0] => Could not create directory ’/usr/share/httpd/.ssh’. [1] => Host key verification failed. [2] => Couldn’t read packet: Connection reset by peer ) 255

note the my key is just accept from the destination server because I can run the script in shell by root and I’m not sure to make something bad making the .ssh dir onto /usr/share/httpd/ where the sys after can make the know_hosts because in all the case in local continue to not work.

I think this is not the exact approach in CentOS
suggestions ?
always thanks
Gio

1 Answer

Hello,

On Centos the default user that Apache is running with is called httpd that is why when you run the shell script through Apache it tries to create the /usr/share/httpd/.ssh folder.

A quick fix would be to generate a new ssh key and add it in the /usr/share/httpd/.ssh directory, then the Apache user would have access to the key that it needs to authenticate with against the destination server.

Though on another note, I would recommend figuring out a different way to do this as running shell commands with your Apache user is not exactly secure. You could for example create a cronjob and run this command at a specific time.

Regards,
Bobby

Have another answer? Share your knowledge.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!