前提保证安装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登陆服务器,向服务器发送指令的类`以上是登陆部分供参考