使用Mint終端,我的腳本使用ssh2_connect和ssh2_auth-password連接。 當我登錄成功時,我想運行一個命令,它會給我硬件CPU。有沒有一種方法可以用來在腳本中執行命令然後顯示結果。我用系統和exec來執行ping操作。如果我在終端我做登錄。然後在終端會這個樣子「獲得硬件CPU」在php中使用ssh2執行命令php
:
測試〜$獲得硬件CPU
使用Mint終端,我的腳本使用ssh2_connect和ssh2_auth-password連接。 當我登錄成功時,我想運行一個命令,它會給我硬件CPU。有沒有一種方法可以用來在腳本中執行命令然後顯示結果。我用系統和exec來執行ping操作。如果我在終端我做登錄。然後在終端會這個樣子「獲得硬件CPU」在php中使用ssh2執行命令php
:
測試〜$獲得硬件CPU
我不知道這個「獲得硬件」命令來自。如果你想弄清楚什麼是CPU供電的系統,然後
grep 'model name' /proc/cpuinfo
將輸出的CPU ID字符串:
[email protected]:~$ grep 'model name' /proc/cpuinfo
model name : Intel(R) Core(TM)2 CPU 6600 @ 2.40GHz
model name : Intel(R) Core(TM)2 CPU 6600 @ 2.40GHz
我如何將它放在一個php腳本中,命令來自scp – Mervyn
您需要通過SSH在終端上運行它 - 而不是通過SCP。但是你很幸運 - 如果你可以做SCP,這意味着當SCP通過終端時你有SSH終端訪問。 – 2012-11-19 14:12:03
您需要訪問外殼:
$connection = ssh2_connect($ip, $port);
$stream = ssh2_shell($connection);
fputs($stream, $input);
$buffer = fread($stream, 8192);
有一個看看這個例子:
$input = "ls\nexit\n";
$connection = ssh2_connect($host, $port);
ssh2_auth_password($connection, $user, $pass);
$stream = ssh2_shell($connection);
stream_set_blocking($stream, 1);
stream_set_timeout($stream, 2);
fputs($stream, $input);
while (!feof($stream)) {
echo $buffer = fread($stream, $buffersize);
}
您可能必須手動設置sleep()
和fread()
,因爲人們在設置ssh2流阻塞時會遇到問題。
我已經試過想要顯示結果,因爲當我在終端中獲取硬件cpu之後,我已經完成了我的ssh2身份驗證,它在終端中工作,希望將此命令放在我的php腳本中運行。 – Mervyn
這是我的腳本: <?php $ connection = ssh2_connect('100.168.0.3',22); if(ssh2_auth_password($ connection,$ username,$ password)){ echo「Authentication Successful!\ n」; $ stream = ssh2_shell($ connection); $ input ='get hardware cpu'; fputs($ stream,$ input); $ buffer = fread($ stream,8192); echo $ buffer; } else { echo「Authentication failed!\ n」; } ?> – Mervyn
資源ID#5這是我運行我的PHP文件時得到的結果 – Mervyn
你可以試試這個(需要phpseclib, a pure PHP SSH2 implementation):
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
echo $ssh->exec("grep 'model name' /proc/cpuinfo");
?>
你或許在尋找['ssh2_exec'(http://www.php.net/manual/en/function.ssh2-exec。 PHP)?有一個[在該頁面上的評論](http://www.php.net/manual/en/function.ssh2-exec.php#99089),似乎正在做你正在尋找的東西。 – Lix