php+telnet при считывании команд пропадает пробел мжд словами
Команд несколько:
display vlan all
[display vlan N/B] N получим из предыдущего запроса
display adsl line-profile
display board N
display board N/N перебираются порты на плате
Т.к. через функции типа socket_... не получилось, решила пойти по-другому.
В инете нашла работающий скрипт. Правда его тестировали только с командой ping.
Код:
Display your own error messages
<?php
require_once "PHPTelnet.php";
$telnet = new PHPTelnet();
$telnet->show_connect_error=0;
// if the first argument to Connect is blank,
// PHPTelnet will connect to the local host via 127.0.0.1
$result = $telnet->Connect('www.somewhere.com','login name','password');
switch ($result) {
case 0:
$telnet->DoCommand('enter command here', $result);
// NOTE: $result may contain newlines
echo $result;
$telnet->DoCommand('another command', $result);
echo $result;
// say Disconnect(0); to break the connection without explicitly logging out
$telnet->Disconnect();
break;
case 1:
echo '[PHP Telnet] Connect failed: Unable to open network connection';
break;
case 2:
echo '[PHP Telnet] Connect failed: Unknown host';
break;
case 3:
echo '[PHP Telnet] Connect failed: Login failed';
break;
case 4:
echo '[PHP Telnet] Connect failed: Your PHP version does not support PHP Telnet';
break;
}
?>
<?php
require_once "PHPTelnet.php";
$telnet = new PHPTelnet();
$telnet->show_connect_error=0;
// if the first argument to Connect is blank,
// PHPTelnet will connect to the local host via 127.0.0.1
$result = $telnet->Connect('www.somewhere.com','login name','password');
switch ($result) {
case 0:
$telnet->DoCommand('enter command here', $result);
// NOTE: $result may contain newlines
echo $result;
$telnet->DoCommand('another command', $result);
echo $result;
// say Disconnect(0); to break the connection without explicitly logging out
$telnet->Disconnect();
break;
case 1:
echo '[PHP Telnet] Connect failed: Unable to open network connection';
break;
case 2:
echo '[PHP Telnet] Connect failed: Unknown host';
break;
case 3:
echo '[PHP Telnet] Connect failed: Login failed';
break;
case 4:
echo '[PHP Telnet] Connect failed: Your PHP version does not support PHP Telnet';
break;
}
?>
Код:
<?php
/*
PHPTelnet 1.1.1 by Antone Roundy
adapted from code found on the PHP websitepublic domain
*/
class PHPTelnet {
var $show_connect_error=1;
var $use_usleep=0; // change to 1 for faster execution-изменить на 1 для более быстрого исполнения
// don't change to 1 on Windows servers unless you have PHP 5-не изменять на 1 на серверах Windows, если у Вас нет PHP 5
var $sleeptime=125000;
var $loginsleeptime=1000000;
var $fp=NULL;
var $loginprompt;
var $conn1;
var $conn2;
/*
0 = success
1 = couldn't open network connection
2 = unknown host
3 = login failed
4 = PHP version too low
*/
function Connect($server,$user,$pass) {
$rv=0;
$vers=explode('.',PHP_VERSION);
$needvers=array(4,3,0);
$j=count($vers);
$k=count($needvers);
if ($k<$j) $j=$k;
for ($i=0;$i<$j;$i++) {
if (($vers[$i]+0)>$needvers[$i]) break;
if (($vers[$i]+0)<$needvers[$i]) {
$this->ConnectError(4);
return 4;
}
}
$this->Disconnect();
if (strlen($server)) {
if (preg_match('/[^0-9.]/',$server)) {
$ip=gethostbyname($server);
if ($ip==$server) {
$ip='';
$rv=2;
}
} else $ip=$server;
} else $ip='127.0.0.1';
if (strlen($ip)) {
if ($this->fp=fsockopen($ip,23)) {
fputs($this->fp,$this->conn1);
$this->Sleep();
fputs($this->fp,$this->conn2);
$this->Sleep();
$this->GetResponse($r);
$r=explode("\n",$r);
$this->loginprompt=$r[count($r)-1];
fputs($this->fp,"$user\r");
$this->Sleep();
fputs($this->fp,"$pass\r");
if ($this->use_usleep) usleep($this->loginsleeptime);
else sleep(1);
$this->GetResponse($r);
$r=explode("\n",$r);
if (($r[count($r)-1]=='')||($this->loginprompt==$r[count($r)-1])) {
$rv=3;
$this->Disconnect();
}
} else $rv=1;
}
if ($rv) $this->ConnectError($rv);
return $rv;
}
function Disconnect($exit=1) {
if ($this->fp) {
if ($exit) $this->DoCommand('exit',$junk);
fclose($this->fp);
$this->fp=NULL;
}
}
function DoCommand($c,&$r) {
if ($this->fp) {
fputs($this->fp,"$c\r");
$this->Sleep();
$this->GetResponse($r);
$r=preg_replace("/^.*?\n(.*)\n[^\n]*$/","$1",$r);
}
return $this->fp?1:0;
}
function GetResponse(&$r) {
$r='';
do {
$r.=fread($this->fp,1000);
$s=socket_get_status($this->fp);
} while ($s['unread_bytes']);
}
function Sleep() {
if ($this->use_usleep) usleep($this->sleeptime);
else sleep(1);
}
function PHPTelnet() {
$this->conn1=chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).
chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).
chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).
chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).
chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).
chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).
chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x58).chr(0x54).
chr(0x45).chr(0x52).chr(0x4D).chr(0xFF).chr(0xF0);
$this->conn2=chr(0xFF).chr(0xFC).chr(0x01).chr(0xFF).chr(0xFC).
chr(0x22).chr(0xFF).chr(0xFE).chr(0x05).chr(0xFF).chr(0xFC).chr(0x21);
}
function ConnectError($num) {
if ($this->show_connect_error) switch ($num) {
case 1: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/fsockopen.php">
Connect failed: Unable to open network connection</a><br />';
break;
case 2: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/unknown-host.php">
Connect failed: Unknown host</a><br />';
break;
case 3: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/login.php">
Connect failed: Login failed</a><br />';
break;
case 4: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/php-version.php">
Connect failed: Your server\'s PHP version is too low for PHP Telnet</a><br />';
break;
}
}
}
return;
?>
/*
PHPTelnet 1.1.1 by Antone Roundy
adapted from code found on the PHP websitepublic domain
*/
class PHPTelnet {
var $show_connect_error=1;
var $use_usleep=0; // change to 1 for faster execution-изменить на 1 для более быстрого исполнения
// don't change to 1 on Windows servers unless you have PHP 5-не изменять на 1 на серверах Windows, если у Вас нет PHP 5
var $sleeptime=125000;
var $loginsleeptime=1000000;
var $fp=NULL;
var $loginprompt;
var $conn1;
var $conn2;
/*
0 = success
1 = couldn't open network connection
2 = unknown host
3 = login failed
4 = PHP version too low
*/
function Connect($server,$user,$pass) {
$rv=0;
$vers=explode('.',PHP_VERSION);
$needvers=array(4,3,0);
$j=count($vers);
$k=count($needvers);
if ($k<$j) $j=$k;
for ($i=0;$i<$j;$i++) {
if (($vers[$i]+0)>$needvers[$i]) break;
if (($vers[$i]+0)<$needvers[$i]) {
$this->ConnectError(4);
return 4;
}
}
$this->Disconnect();
if (strlen($server)) {
if (preg_match('/[^0-9.]/',$server)) {
$ip=gethostbyname($server);
if ($ip==$server) {
$ip='';
$rv=2;
}
} else $ip=$server;
} else $ip='127.0.0.1';
if (strlen($ip)) {
if ($this->fp=fsockopen($ip,23)) {
fputs($this->fp,$this->conn1);
$this->Sleep();
fputs($this->fp,$this->conn2);
$this->Sleep();
$this->GetResponse($r);
$r=explode("\n",$r);
$this->loginprompt=$r[count($r)-1];
fputs($this->fp,"$user\r");
$this->Sleep();
fputs($this->fp,"$pass\r");
if ($this->use_usleep) usleep($this->loginsleeptime);
else sleep(1);
$this->GetResponse($r);
$r=explode("\n",$r);
if (($r[count($r)-1]=='')||($this->loginprompt==$r[count($r)-1])) {
$rv=3;
$this->Disconnect();
}
} else $rv=1;
}
if ($rv) $this->ConnectError($rv);
return $rv;
}
function Disconnect($exit=1) {
if ($this->fp) {
if ($exit) $this->DoCommand('exit',$junk);
fclose($this->fp);
$this->fp=NULL;
}
}
function DoCommand($c,&$r) {
if ($this->fp) {
fputs($this->fp,"$c\r");
$this->Sleep();
$this->GetResponse($r);
$r=preg_replace("/^.*?\n(.*)\n[^\n]*$/","$1",$r);
}
return $this->fp?1:0;
}
function GetResponse(&$r) {
$r='';
do {
$r.=fread($this->fp,1000);
$s=socket_get_status($this->fp);
} while ($s['unread_bytes']);
}
function Sleep() {
if ($this->use_usleep) usleep($this->sleeptime);
else sleep(1);
}
function PHPTelnet() {
$this->conn1=chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).
chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).
chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).
chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).
chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).
chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).
chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x58).chr(0x54).
chr(0x45).chr(0x52).chr(0x4D).chr(0xFF).chr(0xF0);
$this->conn2=chr(0xFF).chr(0xFC).chr(0x01).chr(0xFF).chr(0xFC).
chr(0x22).chr(0xFF).chr(0xFE).chr(0x05).chr(0xFF).chr(0xFC).chr(0x21);
}
function ConnectError($num) {
if ($this->show_connect_error) switch ($num) {
case 1: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/fsockopen.php">
Connect failed: Unable to open network connection</a><br />';
break;
case 2: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/unknown-host.php">
Connect failed: Unknown host</a><br />';
break;
case 3: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/login.php">
Connect failed: Login failed</a><br />';
break;
case 4: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/php-version.php">
Connect failed: Your server\'s PHP version is too low for PHP Telnet</a><br />';
break;
}
}
}
return;
?>
Это 4 и 5 в списке (в начале вопроса). А первые три команды выдают ошибки.
Оказалось при считывании fputs() теряется пробел мжд словами, нпр считывается display vlanall, а не display vlan all.
То же самое и с двумя следующими командами.
Подскажите, в чем тут дело?
Fputs ничего не считывает же. Стоит проверить, сколько байт fputs записал в сокет и сколько должен был записать. Если числа сойдутся, нужен пример того, как и что именно передаётся в метод DoCommand.
Код:
$result = $telnet-Connect($ip,$login,$pass);
switch ($result) {
case 0
$telnet-DoCommand("display vlan all", $result);
sleep (20);
fputs ($fp, $result);
$telnet-DoCommand( n, $result);
sleep (30);
fputs ($fp, $result);
$telnet-DoCommand( n, $result);
sleep (20);
fputs ($fp, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
$telnet-DoCommand(quitn, $result);
fputs ($fp, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
$telnet-DoCommand(yn, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
break;
}
switch ($result) {
case 0
$telnet-DoCommand("display vlan all", $result);
sleep (20);
fputs ($fp, $result);
$telnet-DoCommand( n, $result);
sleep (30);
fputs ($fp, $result);
$telnet-DoCommand( n, $result);
sleep (20);
fputs ($fp, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
$telnet-DoCommand(quitn, $result);
fputs ($fp, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
$telnet-DoCommand(yn, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
break;
}
Код:
$result = $telnet-Connect($ip,$login,$pass);
switch ($result) {
case 0
$telnet-DoCommand("display vlan all", $result);
sleep (20);
fputs ($fp, $result);
$telnet-DoCommand( n, $result);
sleep (30);
fputs ($fp, $result);
$telnet-DoCommand( n, $result);
sleep (20);
fputs ($fp, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
$telnet-DoCommand(quitn, $result);
fputs ($fp, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
$telnet-DoCommand(yn, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
break;
}
switch ($result) {
case 0
$telnet-DoCommand("display vlan all", $result);
sleep (20);
fputs ($fp, $result);
$telnet-DoCommand( n, $result);
sleep (30);
fputs ($fp, $result);
$telnet-DoCommand( n, $result);
sleep (20);
fputs ($fp, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
$telnet-DoCommand(quitn, $result);
fputs ($fp, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
$telnet-DoCommand(yn, $result);
echo p style='text-align left;'.str_replace(n, br,$result).p;
break;
}
Когда смотрю файл, то вижу
display adslline-profile
^
% Unknown command, the error locates at '^'
Код:
$telnet-DoCommand( n, $result);
Из консоли на сервере этак команда выполняется?
Простые команды, такие как ls или mkdir выполняются?
Исправляюсь, часть кода -
Код:
<?
switch ($result) {
case 0:
$telnet->DoCommand("display vlan all", $result);
sleep (20);
fputs ($fp, $result);
$telnet->DoCommand(" \n", $result);
sleep (30);
fputs ($fp, $result);
$telnet->DoCommand(" \n", $result);
sleep (20);
fputs ($fp, $result);
/*
$telnet->DoCommand("display board 0/1 ", $result);
sleep(20);
fputs ($fp, $result);
$telnet->DoCommand(" ", $result);
sleep (20);
fputs ($fp, $result);
$telnet->DoCommand(" ", $result);
sleep (20);
fputs ($fp, $result);
sleep (5);
$telnet->DoCommand("display board 0 ", $result);
sleep(10);
fputs ($fp, $result);
sleep (5);
$telnet->DoCommand("display adsl line-profile", $result);
sleep (20);
fputs ($fp, $result);
$telnet->DoCommand(" ", $result);
sleep (20);
fputs ($fp, $result);
$telnet->DoCommand(" ", $result);
sleep (20);
fputs ($fp, $result);
$telnet->DoCommand("\n", $result);
sleep (20);
$telnet->DoCommand('display vlan 1 ', $result);
sleep (5);
fputs ($fp, $result);
$telnet->DoCommand(" ", $result);
sleep (5);
fputs ($fp, $result);
sleep (5);
*/
echo "<p style='text-align: left;'>".str_replace("\n", "<br/>",$result)."</p>";
$telnet->DoCommand("quit\n", $result);
fputs ($fp, $result);
echo "<p style='text-align: left;'>".str_replace("\n", "<br/>",$result)."</p>";
$telnet->DoCommand("y\n", $result);
echo "<p style='text-align: left;'>".str_replace("\n", "<br/>",$result)."</p>";
break;
}
$telnet->Disconnect();
?>
switch ($result) {
case 0:
$telnet->DoCommand("display vlan all", $result);
sleep (20);
fputs ($fp, $result);
$telnet->DoCommand(" \n", $result);
sleep (30);
fputs ($fp, $result);
$telnet->DoCommand(" \n", $result);
sleep (20);
fputs ($fp, $result);
/*
$telnet->DoCommand("display board 0/1 ", $result);
sleep(20);
fputs ($fp, $result);
$telnet->DoCommand(" ", $result);
sleep (20);
fputs ($fp, $result);
$telnet->DoCommand(" ", $result);
sleep (20);
fputs ($fp, $result);
sleep (5);
$telnet->DoCommand("display board 0 ", $result);
sleep(10);
fputs ($fp, $result);
sleep (5);
$telnet->DoCommand("display adsl line-profile", $result);
sleep (20);
fputs ($fp, $result);
$telnet->DoCommand(" ", $result);
sleep (20);
fputs ($fp, $result);
$telnet->DoCommand(" ", $result);
sleep (20);
fputs ($fp, $result);
$telnet->DoCommand("\n", $result);
sleep (20);
$telnet->DoCommand('display vlan 1 ', $result);
sleep (5);
fputs ($fp, $result);
$telnet->DoCommand(" ", $result);
sleep (5);
fputs ($fp, $result);
sleep (5);
*/
echo "<p style='text-align: left;'>".str_replace("\n", "<br/>",$result)."</p>";
$telnet->DoCommand("quit\n", $result);
fputs ($fp, $result);
echo "<p style='text-align: left;'>".str_replace("\n", "<br/>",$result)."</p>";
$telnet->DoCommand("y\n", $result);
echo "<p style='text-align: left;'>".str_replace("\n", "<br/>",$result)."</p>";
break;
}
$telnet->Disconnect();
?>
display adslline-profile
^
% Unknown command, the error locates at '^'.
или
display vlanall
^
% Unknown command, the error locates at '^'.
или
display vlan1
^
% Unknown command, the error locates at '^'.
А из консоли все ок. Я там смотрела, что должна получить в ответ - данные в виде таблиц.
Две таблицы получаю, а остальные никак.
Какая версия PHP?
PHP v 5.2.1
Можно попробова создать для команды строковую переменную. Сначала присваивать "display vlan all" переменной, а переменную уже передавать в DoCommand.
Когда ты тестировал ввод команд через консоль, ты ведь подключался по telnet с клиента и передавал команды, а не на сервере же?
Если есть возможность, стоит попробовать на более новой версии PHP, если нет, то попробую у себя.
Что-то про пропадающие спейсы в PHP мне ничего не удалось найти в сети. Видимо, либо что-то не так с telnet, либо одной из двух.