SSH Won't Work Via Shell Command in PHP
Problem
I ran into a situation where I wanted to run a shell command from a web page to ssh into another server and run a script that gathered system stats. It simply wasn't working, and I didn't know why. After a couple hours of troubleshooting, I discovered the problem was with accepting the ssh key fingerprint for the user www-data.
First, I installed a program called sshpass. It allows you to use ssh non-interactively.
sudo apt-get install sshpassYour command will be different depending on the package manager used by your Linux distro.
In PHP, I wrote something like this:
if ($output = shell_exec(escapeshellcmd('sshpass -p "Pa$$w0rd" ssh username@hostname "/scripts/status.sh"')))
{
echo "<pre>$output</pre></br></br>";
}
else
{
echo "Failed to load stats.";
}
I was only getting the message "Failed to load stats." because the shell command was simply producing no output.
Solution
First, take note of the current shell for the www-data user. Also take note of the home folder:
cat /etc/passwd | grep www-data
On my system, I see this:
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
the default shell is /usr/sbin/nologin and the home folder is /var/www.
Now change the shell to something else:
sudo usermod www-data -s /bin/bash
Create a new folder in the www-data user's home folder and change the ownership:
sudo mkdir /var/www/.ssh sudo chown www-data:www-data /var/www/.ssh
Now, login as www-data:
sudo su www-data
As the www-data user, individually ssh into every host that you want to be able to ssh into via web and enter "yes" to accept the key fingerprint:
ssh username@hostname The authenticity of host 'hostname (10.0.0.2)' can't be established. ECDSA key fingerprint is ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff. Are you sure you want to continue connecting (yes/no)? yes
The fingerprint is now stored in /var/www/.ssh/known_hosts (on my system /var/www is the home folder for the www-data user).
Log out www-data:
exit
And change the www-data user's shell back to the way it was:
sudo usermod www-data -s /usr/sbin/nologin
The shell command in PHP now works!
Another Way
You can also copy the "known_hosts" file from another user into /var/www/.ssh and change the permissions.