简体   繁体   中英

Create a zip file on a remote location using PHP SSH2

I'm working on a filemanager and my users should be able to download a .zip file from their entire root directory. I'm using the follow script:

$cmd = "";
    if(count($files) > 0) {
        foreach($files as $file) {
            $cmd .= " ". $file['name'];
        }
    }
    $cmd = "cd /home/product$this->_product$path && zip -r $filename.zip$cmd";
    if(ssh2_exec($this->_con, "cd /home/product1/include && zip -r include.zip gl_spawns.inc gl_common.inc")) {
        return $cmd;
    }       

Anyhow, this script works fine, and it's not much relevant to this problem, Below you see the cmd that is returned by the script you see above:

cd /home/product1/include && zip -r include.zip gl_spawns.inc gl_common.inc 

When I enter this cmd into my ssh screen using putty, it works perfect. But when I run this cmd with ssh2_exec in php it only creates a part of the zip file, which is called a random name, and doesn't has a extension, seems like the zip process is canceled for some reason. This happends everytime.

Anyone knows a way to solve this problem?

Thanks for reading.

You might have better luck with phpseclib, a pure PHP SSH2 implementation . eg.

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

$ssh = new Net_SSH2('website.com');
$ssh->login('user', 'pass');

//$ssh->enablePTY();
$ssh->exec('cd /home/product1/include && zip -r include.zip gl_spawns.inc gl_common.inc');

If that doesn't work try commenting out the $ssh->enablePTY() part.

The reason I mention this is that phpseclib has worked for me in instances where ssh2-exec did not.

Good luck!

I have found a solution, it seems ssh2_exec doesn't really handle multiply commands very well, and that is where ssh2_shell comes in, I converted a part of my script to the following code:

    $cmds[0] = "cd /home/product$this->_product$path;"; 
    $cmds[1] = "zip -r $filename.zip$cmd;"; 

    $out = ''; 
    $shell=ssh2_shell($this->_con); 

    for($i=0; $i<count($cmds); $i++) { 
        fwrite($shell, $cmds[$i] . PHP_EOL); 
        sleep(1); 
        while($buffer = fgets($shell)) { 
            flush(); 
            $out .= $buffer; 
        } 
    }   

And it works great!

You can do it this way:

$ssh->exec("
  cd home/path/anotherpath/
  zip -rv archive.zip ./*
");

Note the linebreaks.

Or this way:

$ssh->exec("
  cd home/path/anotherpath/; zip -rv archive.zip ./*
");

既没有使用ssh2也没有使用phpseclib来解决问题,解决了我的问题的是在静默模式下调用zip命令: zip -uqr container.zip folder所以没有任何输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM