-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClient.php
134 lines (103 loc) · 3.34 KB
/
Client.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
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
<?php
namespace PhpTelnet;
class Client
{
var $uSleepTime = 1250000;
var $loginSleepTime = 1000000;
var $connection = null;
var $server = null;
var $port = null;
var $username = null;
var $password = null;
var $loginPrompt;
var $connMessage1;
var $connMessage2;
const ERROR_0 = "success";
CONST ERROR_1 = "couldn't open network connection";
const ERROR_2 = "unknown host";
const ERROR_3 = "login failed";
public function __construct($server, $port, $username = null, $password = null)
{
// we need php 5 obviously
if (version_compare(phpversion(), '5.0', '<')) {
throw new \Exception('PhpTelnet\'s Client needs PHP 5+ to work.');
} else {
$this->server = $server;
$this->port = $port;
$this->username = $username;
$this->password = $password;
}
}
function connect()
{
if ($this->connection === NULL) {
$errorNumber = 0;
if ($this->connection = fsockopen($this->server, $this->port, $errno, $errstr, 5)) {
if ($this->username !== null || $this->password !== null) {
$r = $this->getResponse();
$r = explode("\n", $r);
$this->loginPrompt = $r[count($r) - 1];
fputs($this->connection, $this->username . "\r");
$this->sleep();
fputs($this->connection, $this->password . "\r");
$this->sleep($this->loginSleepTime);
$r = $this->getResponse();
$r = explode("\n", $r);
if (($r[count($r) - 1] == '') || ($this->loginPrompt == $r[count($r) - 1])) {
$errorNumber = 3;
$this->disconnect();
}
}
} else {
$errorNumber = 1;
}
if ($errorNumber != 0) {
$this->throwConnectError($errorNumber);
}
} else {
return true;
}
}
function disconnect($exit = 'exit')
{
if ($this->connection) {
if ($exit)
$this->execute($exit);
fclose($this->connection);
$this->connection = NULL;
}
}
public function execute($cmd)
{
$this->connect();
fwrite($this->connection, $cmd . "\r\n");
$this->sleep();
$r = $this->getResponse();
return $r;
}
private function removeNonPrintableCharacters($str)
{
return preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $str);
}
function getResponse()
{
$r = '';
do {
$r .= fread($this->connection, 1000);
$s = socket_get_status($this->connection);
} while ($s['unread_bytes']);
return $this->removeNonPrintableCharacters($r);
}
function sleep($sleepTime = null)
{
if ($sleepTime === null) {
usleep($this->uSleepTime);
} else {
usleep($this->sleepTime);
}
}
function throwConnectError($num)
{
throw new \Exception(constant('ERROR_' . $num));
}
}