PHP-php如何调用外部交互式命令,比如ssh

PHP-php如何调用外部交互式命令,比如ssh

归属感 发布于 2017-09-06 字数 258 浏览 1312 回复 2

类似php 用system函数来调用shell命令那样
用php ssh到令一台主机,需要执行ssh host命令后,然后输入密码。
尝试用proc_open来运行ssh host,然后往stdin pipe里面写密码,但是无法得到输出。ssh命令应该没能执行成功。不知道php怎么实现执行交互式外部程序。

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泛泛之交 2017-09-28 2 楼

前提保证安装php的ssh扩展

class ssh {
public function __construct($host = "",$port = "",$key=array())
{
$this->sshHost = !empty($host) ? $host : $this->sshHost;
$this->sshPort = !empty($port) ? $port : $this->sshPort;
if(!empty($key)) $parm = $key;
$this->sshConn = ssh2_connect($this->sshHost,$this->sshPort,$parm);
if(! $this->sshConn)
$this->sshMsg = "Connection failed !";
}
/**
* 通过账号与密码登陆ssh
* @param $user 账号
* @param $pwd 密码
* @return NULL
*/
public function authUserPassport($user,$pwd){
$this->sshUser = !empty($user) ? $user : $this->sshUser ;
$this->sshPwd = !empty($pwd) ? $pwd : $this->sshPwd;
if(! ssh2_auth_password($this->sshConn,$this->sshUser,$this->sshPwd))
$this->sshMsg .= "Authorization failed ! ".PHP_EOL ;
}
/**
* 通过公有key和私有key登陆ssh
* @param $publicKey 公有key
* @param $privateKey 私有key
* @param $user 账号
* @param $pwd 密码
*/
public function authPublicKey($publicKey,$privateKey,$user,$pwd){
$this->sshUser = !empty($user) ? $user : $this->sshUser ;
$this->sshPwd = !empty($pwd) ? $pwd : $this->sshPwd;
if(!ssh2_auth_pubkey_file($this->sshConn,$this->sshUser,$publicKey,$privateKey,$this->sshPwd))
$this->sshMsg = "Public Key Authentication Failed";
}
//调用(通过账号密码登陆)
$ssh = new ssh('IP','端口号');
$ssh->authUserPassport("账号","密码");
//调用(通过账号密码跟key登陆)
//$ssh = new ssh('IP','端口号',array('hostkey'=>'ssh-dss'));
//$ssh->authPublicKey("/tmp/xshell.pub.pub","/tmp/xshell.pub.ppk","账号","密码");

}

我之前专门写了个php通过ssh登陆服务器,向服务器发送指令的类`以上是登陆部分供参考

灵芸 2017-09-08 1 楼

PHP 中可以使用EXEC来调用LINUX 下的系统命令。如果您想使用SSH 的话,可以有现成的PHP库使用。SSH2,安装好这个库以后。
<?php
/* Notify the user if the server terminates the connection */
function my_ssh_disconnect($reason, $message, $language) {
printf("Server disconnected with reason code [%d] and message: %sn",

$reason, $message);

}

$methods = array(
'kex' => 'diffie-hellman-group1-sha1',
'client_to_server' => array(

'crypt' => '3des-cbc',
'comp' => 'none'),

'server_to_client' => array(

 'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc',
'comp' => 'none'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

$connection = ssh2_connect('shell.example.com', 22, $methods, $callbacks);
if (!$connection) die('Connection failed');
?>
用这段代码测试一下。您可以参考http://cn.php.net/manual/zh/book.ssh2.php