close

轉自http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/

平台是centos 64bit

先下

安裝lamp等軟體及pear

1、$yum install httpd mysql mysql-server php php-mysql php5-dev php5-cli php-pear build-essential openssl-dev zlib1g-dev

2、下載及編譯libssh2

wget http://www.libssh2.org/download/libssh2-1.3.0.tar.gz
tar -zxvf libssh2-0.14.tar.gz
cd libssh2-0.14/
./configure
make all install

3、安裝ssh

pecl install -f ssh2

最後將使用元件新增至php.ini檔

"extension=ssh2.so" to php.ini

重啟apache,就可以在phpinfo內抓到

$service httpd restart

Method 1: Execute

if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
// log in at server1.example.com on port 22
if(!($con = ssh2_connect("server1.example.com", 22))){
    echo "fail: unable to establish connection\n";
} else {
    // try to authenticate with username root, password secretpassword
    if(!ssh2_auth_password($con, "root", "secretpassword")) {
        echo "fail: unable to authenticate\n";
    } else {
        // allright, we're in!
        echo "okay: logged in...\n";
 
        // execute a command
        if (!($stream = ssh2_exec($con, "ls -al" ))) {
            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);
        }
    }
}


Method 2: Shell

if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
// log in at server1.example.com on port 22
if (!($con = ssh2_connect("server1.example.com", 22))) {
    echo "fail: unable to establish connection\n";
} else {
    // try to authenticate with username root, password secretpassword
    if (!ssh2_auth_password($con, "root", "secretpassword")) {
        echo "fail: unable to authenticate\n";
    } else {
        // allright, we're in!
        echo "okay: logged in...\n";
 
        // create a shell
        if (!($shell = ssh2_shell($con, 'vt102', null, 80, 40, SSH2_TERM_UNIT_CHARS))) {
            echo "fail: unable to establish shell\n";
        } else {
            stream_set_blocking($shell, true);
            // send a command
            fwrite($shell, "ls -al\n");
            sleep(1);
 
            // & collect returning data
            $data = "";
            while ($buf = fread($shell,4096)) {
                $data .= $buf;
            }
            fclose($shell);
        }
    }
}

 

arrow
arrow
    文章標籤
    php tar pear httpd ssh
    全站熱搜

    mming 發表在 痞客邦 留言(0) 人氣()