Archive

Archive for January 17th, 2009

Clase para Conexion SSH con PHP

January 17th, 2009

Esta es una clase tomada de PHP.NET que nos ayuda a la Manejar una conexion SSH con PHP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
< ?php
 
// ssh protocols
// note: once openShell method is used, cmdExec does not work
 
class ssh2 {
 
  private $host = 'host';
  private $user = 'user';
  private $port = '22';
  private $password = 'password';
  private $con = null;
  private $shell_type = 'xterm';
  private $shell = null;
  private $log = '';
 
  function __construct($host='', $port=''  ) {
 
     if( $host!='' ) $this->host  = $host;
     if( $port!='' ) $this->port  = $port;
 
     $this->con  = ssh2_connect($this->host, $this->port);
     if( !$this->con ) {
       $this->log .= "Connection failed !";
     }
 
  }
 
  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 !";
     }
 
  }
 
  function openShell( $shell_type = '' ) {
 
        if ( $shell_type != '' ) $this->shell_type = $shell_type;
    $this->shell = ssh2_shell( $this->con,  $this->shell_type );
    if( !$this->shell ) $this->log .= " Shell connection failed !";
 
  }
 
  function writeShell( $command = '' ) {
 
    fwrite($this->shell, $command."\n");
 
  }
 
  function cmdExec( ) {
 
        $argc = func_num_args();
        $argv = func_get_args();
 
    $cmd = '';
    for( $i=0; $i< $argc ; $i++) {
        if( $i != ($argc-1) ) {
          $cmd .= $argv[$i]." && ";
        }else{
          $cmd .= $argv[$i];
        }
    }
    echo $cmd;
 
        $stream = ssh2_exec( $this->con, $cmd );
    stream_set_blocking( $stream, true );
    return fread( $stream, 4096 );
 
  }
 
  function getLog() {
 
     return $this->log;
 
  }
 
}
 
?>

General, Programacion , ,