我正在尝试通过PHP使用SSH连接来运行Bash脚本。

我编写了一个脚本来为MySQL数据库进行备份和还原,但我仍在测试以实现此目的。我在尝试时遇到问题
运行两个不同的简单命令。我的代码是:

<?php 
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist"); 
 
if(!($con = ssh2_connect("server.hosting.com", 22))){ 
    echo "fail: unable to establish connection\n"; 
} else { 
 
    if(!ssh2_auth_password($con, "username", "password")) { 
        echo "fail: unable to authenticate\n"; 
    } else { 
        // allright, we're in! 
        echo "okay: logged in...\n"; 
 
 
 
 
        if (!($stream = ssh2_exec($con, "cd directory " ))) { 
            echo "fail: unable to execute command\n"; 
        } else { 
            // collect returning data from command 
            stream_set_blocking($stream, true); 
            $data = ""; 
            while ($buf = fread($stream,4096)) { 
                $data .= $buf; 
            } 
            fclose($stream); 
        } 
if (!($stream = ssh2_exec($con, "mkdir directiry2" ))) { 
            echo "fail: unable to execute command\n"; 
        } else { 
            // collect returning data from command 
            stream_set_blocking($stream, true); 
            $data = ""; 
            while ($buf = fread($stream,4096)) { 
                $data .= $buf; 
            } 
            fclose($stream); 
        } 
    } 
} 
?> 

它仍然创建另一个目录,但不在“目录”内!
请帮忙!!!

请您参考如下方法:

问题是,当您执行cd时,“状态”将立即丢失。 phpseclib文档详细说明:

http://phpseclib.sourceforge.net/ssh/examples.html#chdir,

如果您希望能够CD到一个目录,然后在该目录中执行操作,则可以将内容链接起来。例如。 $ssh->exec('cd directory; mkdir directiry2');


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!