Connect to a Unix system using PHP SSH2

Posted: May 22nd, 2009 | Author: admin | Filed under: PHP |

In order to use this class, SSH2 lib must be installed in your PHP configuration. Go here for detailed instructions on how to install and compile SSH2 lib in your web server.

class Ssh {

        private $host = '';
        private $user = '';
        private $port = '22';
        private $password = '';
        private $con = null;
        private $shell_type = 'xterm';
        private $shell = null;
        private $log = '';

        public function __construct($params) {
            if($params['host'] != '') $this->host  = $params['host'];
            if($params['port'] != '') $this->port  = $params['port'];
        }

        public function connectShell() {
            $this->con = @ssh2_connect($this->host, $this->port);

            if(!$this->con) {
                $this->log .= "Connection failed!\n";

                return FALSE;
            } else {
                return TRUE;
            }
        }

        public function authPassword($user = '', $password = '' ) {
            if($user != '') $this->user = $user;

            if($password != '') $this->password = $password;

            if(!@ssh2_auth_password($this->con, $this->user, $this->password) ) {
                $this->log .= "Authorization failed!\n";

                return FALSE;
            } else {
                return TRUE;
            }
        }

        public function execShell($command) {
            if(!($stream = @ssh2_exec($this->con, $command)) ){
                $this->log .= "Fail: Unable to execute command!\n";

                return FALSE;
            } else {
                // collect returning data from command
                stream_set_blocking($stream, true );
                $this->log .= stream_get_contents($stream);
                fclose($stream);                

                return TRUE;
            }
        }

        public function sendFile($local_file, $remote_file, $mode = '0644') {
            if(!ssh2_scp_send($this->con, $local_file, $remote_file)) {
                $this->log .= "Cannot send file to server.\n";

                return FALSE;
            } else {
                return TRUE;
            }
        }

        public function getLog() {
            return $this->log;
        }

    }


Leave a Reply