1

I have a shell script makedir.sh as given below.

sudo -H sh -c '
    mkdir /usr/local/testdir;
    if [ $? -eq 0 ];then
        echo "Successfull";
    else
        echo "Unsuccessfull";
    fi
'

I have given privileges to a user testuser to execute shell script with sudo, but without asking password.For this I add the below line in /etc/sudoers file,

testuser ALL=(ALL) NOPASSWD: ALL

And it works fine that, I could run commands with sudo, but without asking password. The above shell script also working fine without asking password, creating directory testdir inside /usr/local. My problem starts here. I want to run this shell script from a php file. In the current scenario the shell script is residing in a remote machine with ip address 10.3.2.0. The following is my php code but, while running this php code, it is not creating any directory(testdir) inside /usr/local/ . Please advise as I am very beginner in PHP.

PHP Code

<?php
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
if(!($con = ssh2_connect("10.3.2.0", "22")))
{
    echo "fail: unable to establish connection";
}
else
{
    if(!ssh2_auth_password($con, "testuser", "abcdef"))
    {
        echo "fail: unable to authenticate ";
    }
    else
    {
        $stream = ssh2_exec($con, "./makedir.sh");
            stream_set_blocking($stream, true);
        $item = "";
        while ($input = fread($stream,4096)) {
               $item .= $input;
        }
        echo $item;
    }
}

?>

SHELL SCRIPT - makedir.sh (residing at 10.3.2.0 - the same above shell script)

#!/bin/sh
sudo -H sh -c '
    mkdir /usr/local/testdir;
    if [ $? -eq 0 ];then
        echo "Successfull";
    else
        echo "Unsuccessfull";
    fi
'

Thanks.

  • Some part of shell script is there. – Uvais Ibrahim Jul 30 '13 at 12:38
  • Well, you said that the shell script it works fine. I think that your problem is on this line: ssh2_exec($con, "./makedir.sh"). You should give the full path for the script. – Radu Rădeanu Jul 30 '13 at 12:43
  • I gave full path, but still is not working :( – Uvais Ibrahim Jul 30 '13 at 13:04
1

phpseclib, a pure PHP SSH implementation, is generally better than libssh2. Better at diagnostics and reliability too. In your case... I'd try this:

<?php
include('Net/SSH2.php');

define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX);

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('./makedir.sh');

echo $ssh->getLog();
?>

And see what it says.

  • Now it is getting error sudo: sorry, you must have a tty to run sudo while running php script from terminal as php test.php – Uvais Ibrahim Aug 1 '13 at 5:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.