PX : code

Telnet Script by Marc Ennaji by Andrew Fox
Download this code


<?php
/*
$Id: telnet.class.php,v 1.3 17th July 2005 16:31:35 mb Exp $

Modified by Andrew Fox <alias.zero2097@gmail.com)
- translated remaining function and variable names from french to english

Originally written by Marc Ennaji (in french),
modified by Matthias Blaser <mb@adfinis.ch>

- translated most function- and variable names from french to english
- added get_buffer-method to get results of the last command
  sent to server
- added hack to get socket_strerror working on old systems

You can find the original class which this translation is based on
on this url: http://px.sklar.com/code.html?id=634

The original class includes a small documentation about using it
in your own applications, but be aware, all functions are in french there, this
one is partly translated.
*/

// Hack to get socket_strerror working on old systems
if(!function_exists("socket_strerror")){
    function 
socket_strerror($sh){
        if(
function_exists("strerror")){
            return 
strerror($sh);
        } else {
            return 
false;
        }
    }
}

// telnet class
define ("TELNET_ERROR"0);
define ("TELNET_OK"1);
define ("TELNET_ASK_CONFIRMATION"2);
define ("LIBELLE_CONFIRMATION""[confirm]");

class 
telnet {

    var 
$socket  NULL;
    var 
$host "";
    var 
$port "23";
    var 
$error "";
    var 
$codeError "";
    var 
$prompt "\$ ";
    var 
$log NULL;  // file handle
    
var $LogDirectory"";
    var 
$LogDate "";
    var 
$test;

    var 
$buffer "";

    
//------------------------------------------------------------------------
    
function connect(){
        
$this->socket fsockopen($this->host,$this->port);

        if (!
$this->socket){
            
$this->error "unable to open a telnet connection: " socket_strerror($this->socket) . "\n";
            return 
TELNET_ERROR;
        }

        
socket_set_timeout($this->socket,10,0);
        return 
TELNET_OK;
    }

    
//------------------------------------------------------------------------
    
function read_to($chaine){
        
$NULL chr(0);
        
$IAC chr(255);
        
$buf '';

        if (!
$this->socket){
            
$this->error "telnet socket is not open";
            return 
TELNET_ERROR;
        }

        while (
1){
            
$c $this->getc();

            if (
$c === false){
             
// Read more characters from the socket
                
if ($this->ContainsError($buf)){
                    return 
TELNET_ERROR;
                }

                
$this->error " Couldn't find the requested : '" $chaine "', it was not in the data returned from server : '" $buf "'" ;
                
$this->logger($this->error);
                return 
TELNET_ERROR;
            }

            if (
$c == $NULL || $c == "\021"){
                continue;
            }

            if (
$c == $IAC){
                
// Interpreted As Command
                
$c $this->getc();

                if (
$c != $IAC){
                    
// car le 'vrai' caractere 255 est doublé pour le differencier du IAC
                    
if (! $this->NegotiateTelnetOption($c)){
                        return 
TELNET_ERROR;
                    } else {
                        continue;
                    }
                }

            }

            
$buf .= $c;

            
// Append current char to global buffer
            
$this->buffer .= $c;

            
// Indicate to the user of the class that it has a request for confirmation
            
if (substr($buf,strlen($buf)-strlen(LIBELLE_CONFIRMATION)) == LIBELLE_CONFIRMATION){
                echo 
$this->RemoveLastLine($buf);
                
$this->logger($this->RemoveLastLine($buf));
                return 
TELNET_ASK_CONFIRMATION;
            }

            if ((
substr($buf,strlen($buf)-strlen($chaine))) == $chaine){
                
// on a trouve la chaine attendue

                
$this->logger($this->RemoveLastLine($buf));

                if (
$this->ContainsError($buf)){
                    return 
TELNET_ERROR;
                } else {
                    return 
TELNET_OK;
                }
            }
        }
    }

    
//------------------------------------------------------------------------
    
function getc(){
        return 
fgetc($this->socket);
    }

    
//------------------------------------------------------------------------
    
function get_buffer(){
        
$buf $this->buffer;

        
// Cut last line (It is always a prompt)
        
$buf explode("\n"$buf);
        unset(
$buf[count($buf)-1]);
        
$buf join("\n",$buf);
        return 
trim($buf);
    }

    
//------------------------------------------------------------------------
    
function NegotiateTelnetOption($command){
        
// Negotiate the options

        
$IAC chr(255);
        
$DONT chr(254);
        
$DO chr(253);
        
$WONT chr(252);
        
$WILL chr(251);

        if ((
$command == $DO) || ($command == $DONT)){
            
$opt $this->getc();
            
//echo "wont ".ord($opt)."\n";
            
fwrite($this->socket,$IAC.$WONT.$opt);
        } else if ((
$command == $WILL) || ($command == $WONT)) {
            
$opt fgetc($this->socket);
            
//echo "dont ".ord($opt)."\n";
            
fwrite($this->socket,$IAC.$DONT.$opt);
        } else {
            
$this->error "Error : unknown command ".ord($command)."\n";
            return 
false;
        }

        return 
true;
    }

    
//------------------------------------------------------------------------
    
function write($buffer$LogValue ""$ajouterfinline true){

        
// Clear buffer from last command
        
$this->buffer "";

        if (! 
$this->socket){
            
$this->error "Telnet socket is not open";
            return 
TELNET_ERROR;
        }

        if (
$ajouterfinline){
            
$buffer .= "\n";
        }

        if (
fwrite($this->socket,$buffer) < 0){
            
$this->error "Error writing to socket";
            return 
TELNET_ERROR;
        }

        if (
$LogValue != ""){
            
// Hide confidential values in the log (passwords...)
            
$buffer $LogValue "\n";
        }

        if (! 
$ajouterfinline){
            
// In the log (but not on the socket) add the newline character to the end of each line
            
$buffer .= "\n";
        }

        
$this->logger("> " .$buffer);

        return 
TELNET_OK;
    }

    
//------------------------------------------------------------------------
    
function disconnect(){
        if (
$this->socket){
            if (! 
fclose($this->socket)){
                
$this->error "Error while closing telnet socket";
                return 
TELNET_ERROR;
            }

            
$this->socket NULL;
        }

        
$this->setLog(false,"");
        return 
TELNET_OK;
    }

    
//------------------------------------------------------------------------
    
function ContainsError($buf){
        
$messagesErreurs[] = "nvalid";       // Invalid input, ...
        
$messagesErreurs[] = "o specified";  // No specified atm, ...
        
$messagesErreurs[] = "nknown";       // Unknown profile, ...
        
$messagesErreurs[] = "o such file or directory"// Directory does not exist
        
$messagesErreurs[] = "llegal";       // illegal file name, ...

        
foreach ($messagesErreurs as $erreur){
            if (
strpos ($buf$erreur) === false)
                continue;

                
// An error was detected
                
$this->error =  "An error message was detected in the answer of the remote host: " .
                    
"<BR><BR>" $this->RemoveLastLine($buf,"<BR>") . "<BR>";

                return 
true;
            }

        return 
false;
    }

    
//------------------------------------------------------------------------
    
function wait_prompt(){
        return 
$this->read_to($this->prompt);
    }

    
//------------------------------------------------------------------------
    
function set_prompt($s){
        
$this->prompt $s;
        return 
TELNET_OK;
    }

    
//------------------------------------------------------------------------
    
function set_host($s){
        
$this->host $s;
    }

    
//------------------------------------------------------------------------
    
function set_port($s){
        
$this->port $s;
    }

    
//------------------------------------------------------------------------
    
function get_last_error(){
        return 
$this->error;
    }

    
//------------------------------------------------------------------------
    
function setLog($LogActive$LogName){

        if (
$this->log && $LogActive){
            return 
TELNET_OK;
        }

        if (
$LogActive){
            
$this->LogDirectory =  "/log/" date("m");

            
// Does log folder exist?
            
if (! file_exists($this->LogDirectory)){
                if (
mkdir($this->LogDirectory0700) === false){
                    
$this->error "Unable to create log file folder " .  $this->LogDirectory;
                    return 
TELNET_ERROR;
                }
            }

            global 
$HTTP_SERVER_VARS;

            
$this->LogDate date("d") . "_" .date("H:i:s") . "_" .

            
$LogName "_" $HTTP_SERVER_VARS["PHP_AUTH_USER"] . ".log";

            
$this->log fopen($this->LogDirectory "/" $this->LogDate,"a");

            if (empty(
$this->log)){
                
$this->error "Unable to create log file " $this->LogDate;
                return 
TELNET_ERROR;
            }

            
$this->logger("----------------------------------------------\r\n");
            
$this->logger("Start of log file for user " $HTTP_SERVER_VARS["PHP_AUTH_USER"] .
                
", IP Address " $HTTP_SERVER_VARS["REMOTE_ADDR"] . "\r\n");

            
$this->logger("Telnet connected to " $this->host ", port " $this->port "\r\n");
            
$this->logger("Date : " date("d-m-Y").  "  ŕ " date("H:i:s") . "\r\n");
            
$this->logger("Log File : " $LogName "\r\n");
            
$this->logger("----------------------------------------------\r\n");
            return 
TELNET_OK;

        } else {
            if (
$this->log){
                
$this->logger("----------------------------------------------\r\n");
                
$this->logger("End of log\r\n");

                
fflush($this->log);

                if (! 
fclose($this->log)){
                    
$this->error "Error resulted in the log file being closed";
                    return 
TELNET_ERROR;
                }

                
$this->log NULL;
            }

            return 
TELNET_OK;
        }
    }

    
//------------------------------------------------------------------------
    
function logger($s){
        if (
$this->log){
            
fwrite($this->log$s);
        }
    }

    
//------------------------------------------------------------------------
    
function RemoveLastLine($s$seperator="\n"){

                
// The last line of an answer from the telnet protocol contains (in theory) the command of the user.
        // This method returns all except the last line in order to avoid flooding the log files

        
$lines split("\n",$s);
        
$result "";
        
$EndOfLine true;

        while(list(
$key$data) = each($lines)){
            if (
$EndOfLine){
                
$EndOfLine false;
            } else {
                if (
$data != ""){
                    
$result .= $data $seperator;
                }
            }
        }

        
$result == substr($result,strlen($result)-1); // Remove the last character of line

        
return $result;
    }

    
//------------------------------------------------------------------------
}   //    End of class
?>

Comments or questions?
PX is running PHP 5.2.17
Thanks to Miranda Productions for hosting and bandwidth.
Use of any code from PX is at your own risk.