PHP to implement Telnet connection, pass command, get return value and other functions!
- Error_reporting (-1);
- Class Telnet {
- var $sock = NULL;
- function Telnet ($host, $port) {
- $this->sock = Fsockopen ($host, $port);
- Socket_set_timeout ($this->sock,2,0);
- }
- function Close () {
- if ($this->sock) fclose ($this->sock);
- $this->sock = NULL;
- }
- function Write ($buffer) {
- $buffer = Str_replace (Chr (255), Chr (255). chr (255), $buffer);
- Fwrite ($this->sock, $buffer);
- }
- function getc () {
- Return fgetc ($this->sock);
- }
- function Read_till ($what) {
- $buf = ";
- while (1) {
- $IAC = Chr (255);
- $DONT = Chr (254);
- $DO = Chr (253);
- $WONT = Chr (252);
- $WILL = chr (251);
- $theNULL = chr (0);
- $c = $this->getc ();
- if ($c = = = False) return $buf;
- if ($c = = $theNULL) {
- Continue
- }
- if ($c = = "1") {
- Continue
- }
- if ($c! = $IAC) {
- $buf. = $c;
- if ($what = = (substr ($buf, strlen ($buf)-strlen ($what)))) {
- return $buf;
- }
- else {
- Continue
- }
- }
- $c = $this->getc ();
- if ($c = = $IAC) {
- $buf. = $c;
- }
- else if (($c = = $DO) | | ($c = = $DONT)) {
- $opt = $this->getc ();
- echo "We wont". Ord ($opt). " \ n ";
- Fwrite ($this->sock, $IAC. $WONT. $opt);
- }
- ElseIf (($c = = $WILL) | | ($c = = $WONT)) {
- $opt = $this->getc ();
- echo "We dont". Ord ($opt). " \ n ";
- Fwrite ($this->sock, $IAC. $DONT. $opt);
- }
- else {
- echo "Where are we?" C= ". Ord ($c). \ n ";
- }
- }
- }
- }
- /*
- $telnet = new Telnet ("192.168.0.1", 23);
- echo $telnet->read_till ("Login:");
- $telnet->write ("kongxx\r\n");
- echo $telnet->read_till ("Password:");
- $telnet->write ("kongxx\r\n");
- echo $telnet->read_till (":>");
- $telnet->write ("ls\r\n");
- echo $telnet->read_till (":>");
- echo $telnet->close ();
- */
Copy Code
|
function, to implement, return value