2014-01-11 76 views
0

晚上好,PHP通過ssh與公鑰連接並切換用戶執行命令

目前我正在開發一個使用PHP的腳本。 PHP使用帶公鑰的「ssh2_connect」作爲連接遠程主機的命令。此外,我使用ssh2_exec來執行與user_a一些命令。我想切換到user_b來執行antoher命令並且可選地返回到user_a 。

$connection = ssh2_connect('192.168.2.100', 22, array('hostkey'=>'ssh-rsa')); 

if (ssh2_auth_pubkey_file($connection, 'user_a', './ssh/id_rsa.pub', './ssh/id_rsa')) 
{ 
    echo "Public Key Authentication Successful\n<br />"; 
} 
else 
{ 
    die('Public Key Authentication Failed'); 
} 



if(!($stream = ssh2_exec($connection, "sudo su user_b ; cd ~ ; ls -la"))) 
{ 
    echo "fail: unable to execute command\n"; 
} 
else 
{ 

    stream_set_blocking($stream, true); 

    echo stream_get_contents($stream); 

} 



ssh2_exec($connection, 'exit'); 
unset($connection); 

的問題是正常的命令效果很好,但在切換超時(sudo的文件被編輯)的用戶的回報......我已經用FWRITE嘗試了發送命令。 ; 有沒有任何解決方案來解決這個幾個命令(自己的PHP代碼)或是否更好地使用http://phpseclib.sourceforge.net/

+0

須藤的要提示輸入密碼。由於你沒有發送一個,連接會等待一個,直到事情超時。 –

回答

0

那麼你很可能做到這一點:

echo password | sudo su user_b ; cd ~ ; ls -la 

這種方法的缺點是,它會在你的bash的歷史顯示。

這裏是一種與phpseclib做到這一點,而不必在你的bash的歷史顯示,而不必在你的bash的歷史顯示:

這裏有一個方法與phpseclib /交互模式來獲得密碼須藤:

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

$rsa = new Crypt_RSA(); 
$rsa->loadKey('./ssh/id_rsa'); 

$ssh = new Net_SSH2('192.168.2.100'); 
if ($ssh->login('user_r', $rsa)) { 
    echo "Public Key Authentication Successful\n<br />"; 
} else { 
    die('Public Key Authentication Failed'); 
} 

echo $ssh->read('[email protected]:~$'); 
$ssh->write("sudo su user_b\n"); 
$output = $ssh->read('#[pP]assword[^:]*:|[email protected]:~\$#', NET_SSH2_READ_REGEX); 
echo $output; 
if (preg_match('#[pP]assword[^:]*:#', $output)) { 
    $ssh->write("password\n"); 
    echo $ssh->read('[email protected]:~$'); 
} 

$ssh->write("cd ~\n"); 
echo $ssh->read('[email protected]:~$'); 

$ssh->write("ls -la\n"); 
echo $ssh->read('[email protected]:~$'); 
?> 

以下是如何與phpseclib做,如果你不關心bash的歷史:

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

$rsa = new Crypt_RSA(); 
$rsa->loadKey('./ssh/id_rsa'); 

$ssh = new Net_SSH2('192.168.2.100'); 
if ($ssh->login('user_r', $rsa)) { 
    echo "Public Key Authentication Successful\n<br />"; 
} else { 
    die('Public Key Authentication Failed'); 
} 

echo $ssh->exec("sudo su user_b ; cd ~ ; ls -la");