使用php远程登录到远程设备,运行show命令,然后将输出保存到文件中

使用php远程登录到远程设备,运行show命令,然后将输出保存到文件中,php,Php,我们的程序员最近离开了,所以我的老板叫我帮忙做日常维护工作。我不是一个程序员,但我在这个行业已经有很长的时间了,通常我能找到解决大多数问题的方法 在他离开之前,我们的程序员为我们编写了一个脚本,它可以登录到我们所有的Adtran设备并运行一些show命令。然后它获取数据的某些部分并将其添加到数据库中。不幸的是,我们现在需要的一部分数据没有被提取出来。他的脚本运行显示此数据的命令,但该特定信息列不是他标记要提取的信息列之一 所以现在我有两个选择: 我可以浏览他的代码并尝试找出如何使用现有的内容来

我们的程序员最近离开了,所以我的老板叫我帮忙做日常维护工作。我不是一个程序员,但我在这个行业已经有很长的时间了,通常我能找到解决大多数问题的方法

在他离开之前,我们的程序员为我们编写了一个脚本,它可以登录到我们所有的Adtran设备并运行一些show命令。然后它获取数据的某些部分并将其添加到数据库中。不幸的是,我们现在需要的一部分数据没有被提取出来。他的脚本运行显示此数据的命令,但该特定信息列不是他标记要提取的信息列之一

所以现在我有两个选择:

  • 我可以浏览他的代码并尝试找出如何使用现有的内容来提取我需要的数据(因为他的脚本已经运行了该命令)
  • 使用一个新脚本重新开始,该脚本只运行命令,然后从该命令中提取所有数据,而不仅仅是某些列/行
这是他写的剧本。我需要信息的命令是:“显示系统清单”。我正试图从这些盒子里的卡片中提取零件号,因为其中一些是EOL,一些实际上正在被召回

<?php
set_time_limit(0);

/**
* main class that performs the inventory
*/
class system_inventory
{
  static $cubbyData = array();
  var $ci; //CI variable, CI = cubby inventory?
  var $jobId; // variable for JOB ID

  function __construct() //construct function that
  {
    $this->ci =& get_instance(); // $this-> is access the propery of CI to get the instance of it
    $this->ci->load->library( array('ptelv2') ); //after accessing the instance of CI and load it calls the array ptelv2 for telnet for the function
  }

  static function cubbySet($vars,$arg=NULL) //function called cubbySet
  {
    if(is_string($vars)): //checks to see if $vars is a string
     $vars = array($vars=>$arg); // if $vars is a string it adds it to the array by indicating that $vars is greater than null
   endif;  //ends the if statement

    foreach($vars as $k => $v): // $vars is the array that is the $k (key) to that is equal to or greater than $v (value) IE K points to VARS and v iteration of it
      self::$cubbyData[$k] = $v; // points back to the array cubbyData with the var $k that is references as $vars which is = to the interation of v
    endforeach; //ends for each statement
  }

  static function cubbyGet($i) //function called cubbyGet that is stored in the variable of $i
  {
    return isset(self::$cubbyData[$i]) ? self::$cubbyData[$i] : NULL; // returns to to see if cubbyData index is = to itsself (error checking?)
  }

  static function isolate($nodeIp,$treeIp,$data) //function named isolate that stores varaibles nodeIp,treeIp,and data.
  {
    $targetStr   = $data['topology_tree_detail']; //targetStr is pointing to varaible $data and looking for 'topology_tree_detail'
    $nodeIp      = trim($nodeIp); //trims data to nodeIP
    $needle      = 'Path to Tree Node'; //needle varaible is set to 'Path to Tree Node'
    $pathToPos   = strpos($targetStr,$needle); //resets the path of the POS (position?) to strpos (starting position?) by referencing $targetStr, and $needle
    $targetFound = FALSE; // varaible targetFound set to FALSE?

    while($pathToPos !== FALSE) //while loop that stores $pathToPos (path to position?) as NOT EQUAL TO FALSE
    {
      $targetStr = trim(substr($targetStr,$pathToPos)); //the variable of targetStr is trimming the substrings of targetSttr and pathToPos

      $tmpPos    = strpos($targetStr, "\n"); //the tmpPos (temporary position?) is set equal to the strpos (starting position?) referencing the targetStr, and looking for the character "n"?
      $tmpStr    = substr($targetStr,0,$tmpPos); // the tmpStr (temporary string) is set to the substring of the targetStr (target string), 0, and tmpPos (temporary position) which looks for the "n" character

      $spos      = strpos($tmpStr, $nodeIp); //spos (start/string position?) is set to equal the strpos (String position?) which references the tmpStr (temporary string), and the nodeIP

      if($spos !== FALSE): //checks to see if the $spos is not equal to false
        $ipLen = strlen($nodeIp); // variable of ipLen is equal to strlen (string length) of the nodeIp
        $offset= $ipLen + $spos; //variable of offset is equal to the iplen and the spos variables

        $epos  = strpos($targetStr,$nodeIp,$offset) + $ipLen; //the epos (exponential variable because they are too fucking many fucking variables in here why did the bastard not create objects?) is equal to strpos (starting position) which looks at targetstr,nodeip, and offset then add the ipLen back in
        if($epos !== FALSE): //checks to see if the epos is equal to false
          $targetStr   = substr($targetStr,0,$epos); //the target string is then set to a substring of the targetStr,0, and epos variable
          $targetFound = TRUE; //variable of targetFound is set to true
          break;
        endif; //ends 2nd if statement
      endif; //ends 1st if statement

      $pathToPos = strpos($targetStr,$needle,strlen($needle)); //the variable of pathToPos is set to the strpos (Starting position) that looks at the targetStr,needle and the string length of the needle
    }

    if($targetFound === FALSE): //checks to see if the targetFound is false
      return FALSE;  // returns false if target is not found
    endif; //ends if statement

    $lines = explode("\n",$targetStr); //variable of lines is using the function explode looking for the character "n" in the variable $targetStr
    unset($lines[0],$lines[1]); // the function unset is used to reference lines at the index of 0 and lines at the index of 1 this resets the variable lines back to the original after looking for the "n" character

    $lines = array_values($lines); //variable lines is set to arrary_values of lines
    if(count($lines) <= 1) return FALSE; //checks to see if the count of lines is less than or equal to 1 and if it is then returns false (error checking)

    $matrix = array(); //variable matrix set to an array

    foreach($lines as $k => $line): //start of for each, lines is references as K and is equal to or greater than line
      if($line != ''): // if the variable line is not equal to a " " (space) then the next line will trim the variable line
        $line = trim($line); //see above
        $cols = preg_split('/\s{2,}/',$line); // the variable cols = is splitting the lines variable at "s" and 2

      if(!isset($cols[1])) return FALSE; //the isset is looking at the cols varible at the index of 1 and if cols is set to the index of 1 return false
        $matrix[$k] = array_map('trim',$cols); //the array matrix is looking at the index of $k (lines) and set equal to the array_map to "trim" the variable cols
      endif; // end if
    endforeach; // end for each

    $count = count($matrix); //variable count is set to count the matrix array
    $target= $matrix[--$count]; //target is set to the matrix array and decrementing the count
    $feeder= $matrix[--$count]; //the feeder variable is set to the array matrix and decrementing the count

    $final['nodeindex'] = $feeder[0]; // nodeindex is set to feeder index of 0
    $final['fedbyip'] = $feeder[1]; // fedbyip is set to feeder index of 1
    $final['fedbyslot'] = $feeder[2]; //fedbyslot is set to feeder index of 2
    $final['fedbyport'] = $feeder[3]; //fedbyport is set to feeder index of 3
    $final['uplink'] = $feeder[4]; //uplink is set to feeder index of 4

    $final['nodeip'] = $target[1]; // nodeip is set to target index of 1

    if($final['fedbyip'] != $treeIp): // checks to see if the final feeder index of 1 is equal to the variable of treeIP
      $feederLog = self::fetch_command_results($final['fedbyip']); // the feederLog variable looks at the fetch_command_results and displays the "fedbyip" remark
      $system_inventory = $feederLog['system_inventory']; //  the variable system_inventoryis stored in the variable feederLog as "system_inventory"
      $efmGroup = $feederLog['efm-group']; // the efmGroup is stored in the feederlog as efm-group
    else: //start of else
      $system_inventory = $data['system_inventory']; //system_inventory is set to the variable of datat that is storing "system_inventory"
      $efmGroup = $data['efm-group']; //efmGroup is set to varaible data storing "efm-group"
    endif; //endif

    if(!empty($system_inventory) and preg_match('%1/'.$final['fedbyslot'].'[^,]+,(?P<card>[^,]+)%i', // checks to see if the variable system_inventory is eximpy then runs a regualr expression match that looks for
                  $system_inventory,// place holder of 1/X (variable) drilling into the .$final variable looking for (fed by slot) .
                  $regs)):

      $final['nodeCard'] = trim($regs['card']); // final is looking at nodecard and trimming the variable regs down to 'card'
    else: //start of else
      $final['nodeCard'] = NULL; //if it doesn't exist returns NULL
    endif; // end if

    $final['spans'] = $final['provisioned_links'] = $final['active_links'] = NULL; // variable of final stores spans provisioned_links and active_links setting to NULL

    $targets = array( // variable targets is set to an arry with outputting interface efm-group 1/ (referencing the $final variable ) which stored the fed by slot and fed by port indexes to see where it is being fed by
      "interface efm-group 1/{$final['fedbyslot']}/{$final['fedbyport']}",
      'Provisioned Links',
      'Active Links',
      'Inhibited'
    );

    $target = current($targets); //variable target set to current $targets variable

    if( ($pos = strpos($efmGroup,$target)) !== FALSE ): // if the pos variable is set to the starting positing of emfGroup and target then it is not equal to false then it will offset (stored in a varialbe)
      $offset = strlen($target) + $pos; //then will determine the string length of target and add the pos to the length of the string
      $target = next($targets); // then will set the variable of target to the next instance of $targets after determing the string length and starting position
      if( ($pos = strpos($efmGroup,$target,$offset)) !== FALSE ): // checks to see if the starting position is set to the starting position of emfGroup,target,and offset not equal to false
        $offset = strlen($target) + $pos; // then offsets the string length of target and adds it to the varibale pos (position?)
        $target = next($targets); // then adds it to the target variable
        $epos = strpos($efmGroup,$target,$offset); // the epos variable is set to the staring position of emfGroup,target,and offset

        $text = substr($efmGroup,$pos,($epos - $pos)); // the variable text is being set to the substring of variables efmgroup,pos, and the epos - pos
        $text = trim($text); // then the text variable trims the text to equal :
        $x = explode(':',$text); // see above
        $text = trim($x[1]); //text variabe is trimmed to match the x variable so that the x resides with just x:
        $text = preg_replace('/[\r\n]+/',',',$text); // looks for the pattern ofr "/[\r\n]+/" then replaces it with , , in the text variable
        $x = explode(',',$text); // breaks the variable text into a array by using the ","
        $x = array_map('trim',$x); // x after exploded set to an array_map and will trim, variable of X
        $final['provisioned_links'] = implode(',',$x); // after array_map the final will look for provisioned_links and add the , to the variable x

        $pos = $epos;
        $offset = $pos + strlen($target);
        $target = next($targets);
        $epos = strpos($efmGroup,$target,$offset);
        $text = substr($efmGroup,$pos,($epos - $pos));
        $text = trim($text);
        $x = explode(':',$text);
        $text = trim($x[1]);
        $text = preg_replace('/[\r\n]+/',',',$text);
        $x = explode(',',$text);
        $x = array_map('trim',$x);
        $final['spans'] = count($x);
        $final['active_links'] = implode(',',$x);
      endif;
    endif;

    return $final;
  }

  function get_system_version($nodeIp)
  {
    $data = self::fetch_command_results($nodeIp);

    if($data === FALSE or empty($data['version'])):
      return FALSE;
    endif;

    $version = '';
    //will need to get version from the node ip itself, not parent
    if(preg_match('%1/[0-9]+\s([a-z]+[0-9]+)\s[^\s]*%im', $data['version'], $regs)):
      $version = $regs[1];
    endif;

    //check system inv for number slots to
    //determine ta5000 or ta5006
    if($version != ''):
      preg_match_all('%1/([0-9]+)\b%im', $data['system_inventory'], $result, PREG_PATTERN_ORDER);
      $slots = isset($result[1]) ? $result[1] : NULL;
      if(is_array($slots) and (int)end($slots) == 6 and stripos('TA5000',$version) !== FALSE):
        $version = 'TA5006';
      endif;
    endif;

    return $version != '' ? $version : FALSE;
  }

  static function get_conn_args($ip)
  {
    $vars = array(
      'host' => $ip,
      'user' => 'xxxxxx',
      'pass' => 'xxxxxx',
      'port' => '23',
      'debug'=> 0,
    );

    return $vars;
  }

  static function fetch_command_results($ip)
  {
    $sectioned_log = self::cubbyGet($ip);

    if(empty($sectioned_log)):
      $t = new ptelv2();
      $args = self::get_conn_args($ip);

      if($t->connect($args) == FALSE):
        return FALSE;
      endif;

      $full_log = '';
      $sectioned_log = array();

      //get top tree topology and system inventory first
      $t->enable();
      $t->DoCommand('show topology tree detail');
      $t->more(0,TRUE);

      //break it up into sections for easier parsing
      $full_log .= $t->response_log;
      $sectioned_log['topology_tree_detail'] = trim($t->response_log);

      //reset after breaking into sections
      $t->response_log = '';

      $t->DoCommand('show system inventory');
      $t->more(0,TRUE);

      //break it up into sections for easier parsing
      $full_log .= $t->response_log;
      $sectioned_log['system_inventory'] = trim($t->response_log);

      //reset after breaking into sections
      $t->response_log = '';

      $t->DoCommand('show version');
      $t->DoCommand('break');

      //break it up into sections for easier parsing
      //break it up into sections for easier parsing
      $full_log .= $t->response_log;
      $sectioned_log['version'] = trim($t->response_log);

      //reset after breaking into sections
      $t->response_log = '';

      $t->DoCommand('show interface efm-group');
      $t->more(0,TRUE);

      $full_log .= $t->response_log;
      $sectioned_log['efm-group'] = trim($t->response_log);

      //reset after breaking into sections
      $t->response_log = '';

      $t->quit();
      $full_log .= $t->response_log;

      $sectioned_log['full_log'] = $full_log;

      self::cubbySet($ip,$sectioned_log);
    endif;

    return $sectioned_log;
  }

  function main()
  {
    $rev = 5;
    $misfits = array();

    $this->ci->db->query("DELETE FROM `tool_system_inventory`");


    $query = $this->ci->db->order_by('company ASC, ipaddress ASC')
                      ->get_where('dslams',array('deleted'=>0));

    if( $query->num_rows() == 0 ):
      //exit;
    endif;

    foreach($query->result_array() as $row)
    {
      if( stripos($row['equipment_type'],'TA500') !== FALSE ):
        $realm = trim(strtolower($row['company']));
        $x     = explode('.',$row['ipaddress']);
        $oct3  = $x[0].'.'.$x[1].'.'.$x[2];
        $oct4  = $x[3];

        $x = explode('-',$row['systemname']);
        $y = trim(strtolower($x[1]));
        $z = trim(strtolower($x[2]));

        if(preg_match('/172\.16\.[0-9]+\.1[1-9]/',$row['ipaddress']) and $y == $z):
          $parentNodes[$oct3][$oct4] = $row;
        elseif($row['ipaddress'] != '172.16.67.32'):
          $childNodes[$oct3][] = $row;
        endif;
      else:
        $row['note'] = "wrong equipment type or bad ip";
        $misfits[] = $row;
      endif;
    }

    if( count($misfits) )
      $this->insert($misfits);

    foreach($misfits as $row):
      extract($row);
      $this->update_status($id,"Skipping - reason: {$note}");
    endforeach;

    self::cubbySet('parentNodes',$parentNodes);
    self::cubbySet('childNodes',$childNodes);

    foreach($childNodes as $oct => $rows):

      if( !isset($parentNodes[$oct])):
        $this->insert($rows,"No top tree ip found");
        continue;
      endif;

      $topTreeNode = $parentNodes[$oct]['11'];

      //For testing purposes only. Remove the following line when done
      if($topTreeNode['ipaddress'] != '172.16.148.11') continue;

      //$this->update_status();
      $topTreeInfo = self::fetch_command_results($topTreeNode['ipaddress']);


      if($topTreeInfo === FALSE):
        $this->insert($topTreeNode,"Unable to connect to host");
        continue;
      endif;

      foreach($rows as $row):
        //get tree and card details for this node ip
        $nodeip = isset($row['ipaddress']) ? trim($row['ipaddress']) : '';

        if($nodeip == ''):
          $this->insert($row,"Invalid IP found");
          continue;
        endif;

        $nodeData = self::isolate($nodeip,$topTreeNode['ipaddress'],$topTreeInfo);

        if($nodeData == FALSE):
          $this->insert($row,'failed to get node information');
          continue;
        endif;

        $nodeData['equipment_type'] = $row['equipment_type'];
        $nodeData['dslam_id']       = $row['id'];
        $nodeData['node_name']      = $row['node'];

        $ver = self::get_system_version($nodeip);
        $nodeData['system_version'] = !empty($ver) ? $ver : '?';

        if( !$this->insert($nodeData,'success') ):
          //file_put_contents();
        endif;

        --$rev;
        if($rev <= 0) break 2;
      endforeach;
    endforeach;
  }

  function insert($data,$note=NULL)
  {
    $rows = array();

    if( isset($data[0]) ):
      $dataSet = $data;
    else:
      $data['note'] = $note;
      $dataSet = array($data);
    endif;

    foreach($dataSet as $k => $data):
      if(isset($data['ipaddress'])):
        $data['nodeip']    = !empty($data['ipaddress']) ? $data['ipaddress'] : NULL;
        $data['node_name'] = !empty($data['node']) ? $data['node'] : NULL;
        $data['dslam_id']  = !empty($data['id']) ? $data['id'] : NULL;
      endif;

      if( (!isset($data['note']) or $data['note'] == '') and $note !== NULL ):
        $data['note'] = $note;
      endif;

      $values = array(
        'dslam_id'          => element('dslam_id',$data),
        'node_name'         => element('node_name',$data),
        'equipment_type'    => element('equipment_type',$data),
        'system_version'    => element('system_version',$data),
        'nodeindex'         => element('nodeindex',$data),
        'fedbyip'           => element('fedbyip',$data),
        'fedbyslot'         => element('fedbyslot',$data),
        'fedbyport'         => element('fedbyport',$data),
        'uplink'            => element('uplink',$data),
        'nodeip'            => element('nodeip',$data),
        'nodeCard'          => element('nodeCard',$data),
        'provisioned_links' => element('provisioned_links',$data),
        'active_links'      => element('active_links',$data),
        'spans'             => element('spans',$data),
        'note'              => element('note',$data),
      );

      $dataSet[$k] = $values;
    endforeach;

    return $this->ci->db->insert_batch('tool_system_inventory',$values,TRUE);
  }

  function synchronize()
  {
    $data = array();
    $cardTypes = array('GE','HDSL','T1','SHDSL');
        $rates['K'] = $rates['k'] = pow(10,3);
        $rates['M'] = $rates['m'] = pow(10,6);
        $rates['G'] = $rates['g'] = pow(10,9);

    $query = $this->ci->db->where('fedbyip IS NOT NULL',NULL,TRUE)
                          ->where('uplink < 1000000',NULL,TRUE)
                          ->get('tool_system_inventory');

    if( $query->num_rows() > 0 )
    {
      foreach( $query->result() as $row ):
        $row->spans = (int)$row->spans;//in case this is NULL for some reason
        foreach($cardTypes as $ct):
          if( strpos($row->nodecard,$ct) === 0 ):
            $row->nodecard = strtolower($ct);
            break;
          endif;
        endforeach;

        $data[] = array(
          'id'=>$row->dslam_id,
          'equipment_type' => $row->system_version,
          'uplink_spans'   => $row->spans,
          'uplink_type'    => $row->nodecard,
          'uplink_speed'   => $row->spans ? ( ($row->spans - 1) * 1.5 ) : 0,
        );
      endforeach;

      $rowsUpdated = $this->ci->update_batch('dslams',$data,'id');

      //update status table on rows updated tool_system_inventory_status


      return $rowsUpdated;
    }

    return 0;
  }

  private function update_status($id,$note=NULL)
  {
    $data['dslam_id'] = $id;
    $data['note'] = $id;

    $dt = class_datetime();
    $data['datetime'] = $dt->format('Y-m-d H:i:s');

    $this->ci->db->insert('tool_system_inventory_status',$data);
  }
}

你能告诉我启动执行过程的实际函数吗?另外,请告诉我哪一部分数据未正确提交。?这是一个批处理文件,实际开始执行脚本。发布的代码运行良好,这不是我的问题。我的问题是,我需要更改或添加到此文件,以便获得所需的数据。再次感谢您的关注。数据库中插入的信息的一些列名是什么?缺失字段的名称是什么?你能给我们看一下表模式吗?你能告诉我启动执行过程的实际函数吗?另外,请告诉我哪一部分数据未正确提交。?这是一个批处理文件,实际开始执行脚本。发布的代码运行良好,这不是我的问题。我的问题是,我需要更改或添加到此文件,以便获得所需的数据。再次感谢您的关注。数据库中插入的信息的一些列名是什么?缺失字段的名称是什么?你能给我们看一下表格模式吗?