use standards-compliant tags php
[mdv_bs_web.git] / ssh.inc.php
blobe529f8e44632325d26d215205266044c9b4e8f99
1 <?php
3 class SSH {
4 private $connection;
5 private $shell;
6 private $host;
7 private $cmdstart = '[cmdstartline]';
8 private $cmdend = '[cmdendline]';
10 function __construct($host) {
11 $this->host = $host;
14 function connect() {
15 // $this->connection = ssh2_connect($this->host, 22);
16 $this->connection = ssh2_connect($this->host, 22, array('hostkey'=>'ssh-dss'));
17 if (!$this->connection) {
18 return 1;
21 if (!@ssh2_auth_password($this->connection, 'mandrake', 'mandrake')) {
23 if (!@ssh2_auth_pubkey_file ($this->connection, 'mandrake',
24 '/home/mandrake/.ssh/id_dsa.pub',
25 '/home/mandrake/.ssh/id_dsa.bs')) {
26 return 2;
28 $this->shell = ssh2_shell($this->connection, 'vanilla', array('HISTFILE' => ''));
30 // Wait for the login
31 $start_time = time();
32 $max_time = 20; //time in seconds
33 while (((time() - $start_time) < $max_time)) {
34 $buf = fgets ($this->shell);
35 if (strstr ($buf, '$')) {
36 return 0;
38 usleep (100000);
40 // Timeout
41 return 3;
44 function exec($cmd) {
45 flush();
46 $realcmd = "echo '".$this->cmdstart."'; ". $cmd ."; echo '".$this->cmdend."'\n";
47 if (fwrite ($this->shell, $realcmd) != strlen($realcmd)) {
48 return False;
50 flush();
51 $output = "";
52 $start = False;
53 $start_time = time();
54 $max_time = 30; //time in seconds
55 while (((time() - $start_time) < $max_time)) {
56 $line = fgets($this->shell);
57 if (!$line) {
58 # Avoid CPU 100% usage.
59 usleep (100000);
60 continue;
62 if (!strstr ($line, $cmd)) {
63 if (preg_match('/'.escapeshellcmd($this->cmdstart).'/',$line)) {
64 $start = True;
66 elseif (preg_match('/'.escapeshellcmd($this->cmdend).'/',$line)) {
67 if ($output) {
68 return array_map("trim", split("\n", $output));
70 else {
71 return False;
74 elseif ($start) {
75 $output .= $line;