Run Linux shell command with nonapache user
How to install expect extension for php-
Example-
function run_shell_command($command,$username,$password)
{
ini_set ("expect.timeout", 3);
ini_set("expect.loguser", "Off");
$stream = fopen("expect://su - $username -c '$command'","r");
// In case su not work then use this
//$stream = fopen("expect://ssh - $username@localhost '$command'","r");
$cases = array (
array(0=> "Password:", 1=> 'PASSWORD'),
array (0 => "password:", 1 => 'PASSWORD'),
array (0 => "keyboard-interactive).", 1 => 'FAIL'),
array (0 => "password).", 1 => 'FAIL'),
array (0 => "Too many authentication failures for $username", 1 => 'FAIL'),
array (0 => "yes/no)?", 1 => 'YESNO')
);
while (true)
{
switch (expect_expectl ($stream, $cases))
{
case 'PASSWORD':
fwrite ($stream, "$password\n");
break;
case 'FAIL':
fwrite ($stream, "Authentication Fail \n");
break 2;
case 'YESNO':
fwrite ($stream, "yes\n");
break;
case EXP_TIMEOUT:
case EXP_EOF:
break 2;
default:
fwrite($stream,"Error has occurred!\n");
}
}
$i=1;
while (!feof($stream)) {
$buffer = fgets($stream, 4096);
$arr[$i] = trim($buffer);
$i++;
}
fclose ($stream);
return $arr;
}
Require packages-
a) php-pear and php-devel- (for phpize)
b) Expect and expect-devel (there is no use of extension if original language is not available)
c) make (package)
d) Now simply run command
Pear install http://pecl.php.net/get/expect-0.2.4.tgz
Or
Pecl install http://pecl.php.net/get/expect-0.2.4.tgz
Or you should install latest version of extension from site http://pecl.php.net/get/
e) Now add following line in /etc/php.ini (or location of your php.ini ) file.
extension = expect.so
Example-
function run_shell_command($command,$username,$password)
{
ini_set ("expect.timeout", 3);
ini_set("expect.loguser", "Off");
$stream = fopen("expect://su - $username -c '$command'","r");
// In case su not work then use this
//$stream = fopen("expect://ssh - $username@localhost '$command'","r");
$cases = array (
array(0=> "Password:", 1=> 'PASSWORD'),
array (0 => "password:", 1 => 'PASSWORD'),
array (0 => "keyboard-interactive).", 1 => 'FAIL'),
array (0 => "password).", 1 => 'FAIL'),
array (0 => "Too many authentication failures for $username", 1 => 'FAIL'),
array (0 => "yes/no)?", 1 => 'YESNO')
);
while (true)
{
switch (expect_expectl ($stream, $cases))
{
case 'PASSWORD':
fwrite ($stream, "$password\n");
break;
case 'FAIL':
fwrite ($stream, "Authentication Fail \n");
break 2;
case 'YESNO':
fwrite ($stream, "yes\n");
break;
case EXP_TIMEOUT:
case EXP_EOF:
break 2;
default:
fwrite($stream,"Error has occurred!\n");
}
}
$i=1;
while (!feof($stream)) {
$buffer = fgets($stream, 4096);
$arr[$i] = trim($buffer);
$i++;
}
fclose ($stream);
return $arr;
}
Comments
Post a Comment