NewsRhzhi | 先创资讯 | 旧版入口
rhzhi.net
网站首页 | NewsRhzhi | 先创资讯 | 操作系统 | 工具软件 | 办公软件 | 网站设计 | 组网专栏 | 平面设计 | 多 媒 体 | 程序开发 | 硬件资料 | 聊天软件
您现在的位置: 先创网 >> 网络应用 >> 网络安全 >> 文章正文
将SSH与PHP相连接确保数据安全
51CTO
2008-3-21 16:03:01文/佚名
    

  第二种方法:外壳

  同样道理,你也可以为如下的代码编写函数或者一个类。不过,本文仅仅提供基本观念:

  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);

   }

   }

  }

  小提示:

  有时服务器忙碌,或者一个连接出错,缓冲区没有数据,PHP脚本就会停止从一个命令输出(即使命令并没有完成!)中收集数据。你可以为此进行如下的操作:

  ssh2_exec($con, 'ls -al; echo "__COMMAND_FINISHED__"' );

  现在,在你不断地检查缓冲区的循环中,只需要看一下COMMAND_FINISHED。因为你就可以知道你拥有了所有的数据。为了避免无限循环(死循环),可以用一个10秒的超时限制:

  $time_start = time();

  $data = "";

  while( true ){

   $data .= fread($stream, 4096);

   if(strpos($data,"__COMMAND_FINISHED__") !== false){

   echo "okay: command finished\n";

   break;

   }

   if( (time()-$time_start) > 10 ){

   echo "fail: timeout of 10 seconds has been reached\n";

   break;

   }

  }

  在上面的例子中,你最好将stream_set_blocking设为false。

  通过SSH发送文件

  ssh2_scp_send($con, "/tmp/source.dat", "/tmp/dest.dat", 0644);

  如果不能正常工作

  请检查如下的几个方面:

  依照本文检查你操作的每一步

  在服务器端,在sshd_config 中必须启用“PasswordAuthentication yes”。在大多数服务器上默认值是yes,不过有些情况下,你可能需要将下面的一行加入到文件中,即亲自动手打开这个功能:

  /etc/ssh/sshd_config:

  # Change to yes to enable tunnelled clear text passwords

  PasswordAuthentication yes

   如果作了改变,就需要重新启动SSH:

  /etc/init.d/ssh restart

上一页  [1] [2] 

打印此页 投稿与建议 返回顶部
栏 目 索 引
软件应用 SOFTWARE
Win XP | NT/2003
Win2000 | DOS/Win9x
PowerPoint | Office
Excel | Word
网络软件 | 实用软件
媒体软件 | 系统软件
常用软件 | 办公软件
聊天软件 | 网络安全
新软试用 | Vista
设计在线 DESIGN
Dreamweaver | 3DMax
Photoshop | Flash
平面设计 | 网页设计
多 媒 体 | 精品画廊
精彩专区 SPECIAL
Q Q 专区 | 热门专题
组网玩网 | 程序开发
应用集锦 |
相关文章
关于我们 - 联系方式 - 合作伙伴 - 网站大事记 - 网站地图 - 我要投稿
Copyright ©1997-2008 先创网 All Rights Reserved.
先创科技 版权所有