Connect to a Unix system using PHP SSH2

Posted: May 22nd, 2009 | Author: | Filed under: PHP | 1 Comment »

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

    }

One Comment on “Connect to a Unix system using PHP SSH2”

  1. 1 Subash said at 4:08 pm on September 2nd, 2010:

    Hello..

    Thanks for the nice tutorial.. I am trying to use phpseclib for making ssh connections with php. I could get partial success by using phpseclib. It would be more interesting if you could provide a simple example of how to use this class. Thanks admin for providing an wonderful tutorial..


Leave a Reply