-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSsh2.php
More file actions
112 lines (92 loc) · 2.6 KB
/
Ssh2.php
File metadata and controls
112 lines (92 loc) · 2.6 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
namespace gud3\executor;
/**
* Class Ssh2
*/
class Ssh2 extends ExecuteAbstract implements ExecuteInterface
{
/**
* @var resource
*/
private $_connection;
/**
* Ssh2 constructor.
*
* @param $ip
* @param $login
* @param $password
* @param int $port
*/
public function __construct($ip, $login, $password, $port = 22)
{
$this->_connection = ssh2_connect($ip, $port);
ssh2_auth_password($this->_connection, $login, $password);
}
/**
* @param $command
* @param bool $async
* @param bool $returnStream
*
* @return array|mixed
* @throws \Exception
*/
public function exec($command, $async = false, $returnStream = false)
{
if (is_array($command)) {
if ($returnStream === true) {
throw new \Exception('Function not return stream from array');
}
foreach ($command as $cmd) {
$this->exec($cmd, $async);
}
} else {
$this->getCommandFlag($command, $async);
$stream = ssh2_exec($this->_connection, $command);
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$this->result[] = stream_get_contents($stream_out);
fclose($stream);
}
if (count($this->result) <= 1) {
if ($returnStream) {
return [end($this->result), $stream];
}
return end($this->result);
} else {
return $this->result;
}
}
/**
* @param $path
*/
public function getFile($path, $fileName)
{
$sftp = ssh2_sftp($this->_connection);
$file = @fopen("ssh2.sftp://" . intval($sftp) . "/{$path}{$fileName}", 'r');
if (!$file) {
return [];
}
$filesize = filesize("ssh2.sftp://{$sftp}/{$path}{$fileName}");
$read = 0;
$string = '';
while ($read < $filesize && ($buffer = fread($file, $filesize - $read))) {
$read += strlen($buffer);
$string .= $buffer;
}
fclose($file);
return $this->result[] = $string;
}
/**
* @param $path
* @param $fileName
* @param $content
*/
public function setFile($path, $fileName, $content)
{
$sftp = ssh2_sftp($this->_connection);
$file = fopen("ssh2.sftp://" . intval($sftp) . "{$path}{$fileName}", 'w+');
$write = fwrite($file, $content);
fclose($file);
return $write;
}
}