php ssh2_connect,PHP: ssh2_connect - Manual

Due to a lack of complete examples, here's a simple SSH2 class for connecting to a server, authenticating with public key authentication, verifying the server's fingerprint, issuing commands and reading their STDOUT and properly disconnecting.  Note: You may need to make sure you commands produce output so the response can be pulled.  Some people suggest that the command is not executed until you pull the response back.

public functionconnect() {

if (!($this->connection=ssh2_connect($this->ssh_host,$this->ssh_port))) {

throw newException('Cannot connect to server');

}$fingerprint=ssh2_fingerprint($this->connection,SSH2_FINGERPRINT_MD5|SSH2_FINGERPRINT_HEX);

if (strcmp($this->ssh_server_fp,$fingerprint) !==0) {

throw newException('Unable to verify server identity!');

}

if (!ssh2_auth_pubkey_file($this->connection,$this->ssh_auth_user,$this->ssh_auth_pub,$this->ssh_auth_priv,$this->ssh_auth_pass)) {

throw newException('Autentication rejected by server');

}

}

public functionexec($cmd) {

if (!($stream=ssh2_exec($this->connection,$cmd))) {

throw newException('SSH command failed');

}stream_set_blocking($stream,true);$data="";

while ($buf=fread($stream,4096)) {$data.=$buf;

}fclose($stream);

return$data;

}

public functiondisconnect() {$this->exec('echo "EXITING" && exit;');$this->connection=null;

}

public function__destruct() {$this->disconnect();

}

}?>

[EDIT BY danbrown AT php DOT net: Contains two bugfixes suggested by 'AlainC' in user note #109185 (removed) on 26-JUN-2012.]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值