2016-05-06 78 views
0

我在远程使用ssh2_exec在服务器上运行命令时出现问题。为什么使用ssh2_exec的命令不会结束?

当我使用wget或解压缩时,该命令应该执行,但我得不到结果或只有几个文件。

我需要知道的是,在继续执行我的其他PHP代码之前,我可以确定我的ssh2_exec脚本将完全执行。

$stream =ssh2_exec($connection, 'cd /home; wget http://domain.com/myfile.zip; unzip myfile.zip; rm myfile.zip'); 

在此先感谢!

编辑:我发现脚本,如何得到命令的结果?

<?php 
$ip = 'ip_address'; 
$user = 'username'; 
$pass = 'password'; 

$connection = ssh2_connect($ip); 
ssh2_auth_password($connection,$user,$pass); 
$shell = ssh2_shell($connection,"bash"); 

//Trick is in the start and end echos which can be executed in both *nix and windows systems. 
//Do add 'cmd /C' to the start of $cmd if on a windows system. 
$cmd = "echo '[start]';your commands here;echo '[end]'"; 
$output = user_exec($shell,$cmd); 

fclose($shell); 

function user_exec($shell,$cmd) { 
    fwrite($shell,$cmd . "\n"); 
    $output = ""; 
    $start = false; 
    $start_time = time(); 
    $max_time = 2; //time in seconds 
    while(((time()-$start_time) < $max_time)) { 
    $line = fgets($shell); 
    if(!strstr($line,$cmd)) { 
     if(preg_match('/\[start\]/',$line)) { 
     $start = true; 
     }elseif(preg_match('/\[end\]/',$line)) { 
     return $output; 
     }elseif($start){ 
     $output[] = $line; 
     } 
    } 
    } 
} 

?> 
+0

你能提供你正在使用的命令吗?我们需要更多信息才能提供帮助。 – mtrueblood

+0

我已经编辑帖子,:) – SarahG

+0

我认为你的命令可能是异步运行的,这就是为什么你没有得到你正在寻找的结果。 – mtrueblood

回答

0

的Debian可能认为包是很好的,因为它是很稳定(根据official site没有改变自2012年10月15日)。但我会说这不好。我会使用以下方法:

$command = "ls -l"; 
$user = "user"; 
$host = "host"; 

if (! my_ssh_exec($command, $user, $host)) { 
    fprintf(STDERR, "my_ssh_exec failed\n"); 
} 


function my_ssh_exec($cmd, $host, $user) { 
    $result = true; 

    $desc = [ 
    1 => ['pipe', 'w'], 
    2 => ['pipe', 'w'], 
    ]; 

    // -tt forces TTY allocation 
    $ssh_cmd = "ssh -tt [email protected]$host -- $cmd"; 

    $proc = proc_open($cmd, $desc, $pipes); 

    if (! is_resource($proc)) { 
    return false; 
    } 

    if ($error = stream_get_contents($pipes[2])) { 
    fprintf(STDERR, "Error: %s\n", $error); 
    $result = false; 
    } 
    fclose($pipes[2]); 

    if ($output = stream_get_contents($pipes[1])) { 
    printf("Output: %s\n", $output); 
    } 
    fclose($pipes[1]); 

    if ($exit_status = proc_close($proc)) { 
    fprintf(STDERR, "Command exited with non-zero status %d: %s\n", 
     $exit_status, $cmd); 
    $result = false; 
    } 

    return $result; 
} 

该脚本应该在命令行界面中运行。

+0

好,但我的服务器有一个密码来连接root。 – SarahG

+0

@SarahG,您可以使用[SSH密钥](https://help.ubuntu.com/community/SSH/OpenSSH/Keys)设置无密码访问。 –

相关问题