Warning: array_merge(): Argument #2 is not an array in /hsphere/local/home/magistr/codeismy.name/wp-content/plugins/wp-pagenavi/scb/Options.php on line 46

SSH и PHP

Дата: Сентябрь 22, 2009

(0) комментариев

Недавно возникла такая задача, написать скрипт управления сервером. Первым что мне пришло на ум — это ssh и он к моей радости поддерживается PHP. Я быстренько накидал скриптик для подключения к серверу по ssh и хочу им поделиться с вами :)
Команды для ssh вы можете найти в инете, я же приведу только сам класс работы и распишу что за что отвечает.
Вот текст класса:

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
<?php

class SSH {

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

  public 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 !";
     }

  }

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

  }

  public 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 !";

  }
ssh2_exec()
  public function writeShell( $command = '' ) {

    fwrite($this->shell, $command."\n");

  }

  public 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 );

  }

  public function getLog() {

     return $this->log;

  }

}

А теперь как пользоваться :)
конечно как всегда сначала мы инициируем класс

1
$ssh=new SSH;

далее коннектимся

1
$ssh->__construct(сервер,

авторизируемся на сервере

1
$ssh->authPassword(логин, п

теперь мы можем например например написать чтонить через openShell writeShell и выполнить команду cmdExec( )

1
$ssh->cmdExec()
a




    Нет комментариев на "SSH и PHP"

    Нет комментариев.


    Вы можете продолжить обсуждение этой статьи на форуме


    Имя : 
    Почта : 
    Сайт : 
    Комментарий : 

    Проверка комментариев включена. Прежде чем Ваши комментарии будут опубликованы пройдет какое-то время.

    Создание сайта - Echo-group Раскрутка сайтов