Routerconfigs plugin / how it works?

Discussions on developing plugins for the Cacti Plugin Architecture

Moderators: Developers, Moderators

Post Reply
dieselboy
Cacti User
Posts: 135
Joined: Wed May 27, 2009 5:10 pm

Routerconfigs plugin / how it works?

Post by dieselboy »

Can anyone help explain to me how the routerconfigs plugin works? I have edited the code in functions.php for two reasons. The first to allow the cacti telnet session to enable using the same user credentials provided in the authentication list, and secondly to allow ASA and PIX firewalls to be backed up successfully.

I can see that the mySQL database has entries for Cisco IOS and Cisco CatOS, inside these tables there is data like copy run tftp. What I would like to know is how this information is dealt with?

I would like to input an extra table called HP switches, so that it is selectable from the drop down menu under devices in Cacti.
I have looked through functions.php but cannot see how the drop down menu selects the device and runs commands based on that specific device.

Here is my functions.php code which allows me to complete what I described above. Hopefully someone who knows a little more can provide some input?
dieselboy
Cacti User
Posts: 135
Joined: Wed May 27, 2009 5:10 pm

Post by dieselboy »

Code: Select all

<?php
/*
 +-------------------------------------------------------------------------+
 | Copyright (C) 2007 The Cacti Group                                      |
 |                                                                         |
 | This program is free software; you can redistribute it and/or           |
 | modify it under the terms of the GNU General Public License             |
 | as published by the Free Software Foundation; either version 2          |
 | of the License, or (at your option) any later version.                  |
 |                                                                         |
 | This program is distributed in the hope that it will be useful,         |
 | but WITHOUT ANY WARRANTY; without even the implied warranty of          |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           |
 | GNU General Public License for more details.                            |
 +-------------------------------------------------------------------------+
 | Cacti: The Complete RRDTool-based Graphing Solution                     |
 +-------------------------------------------------------------------------+
 | This code is designed, written, and maintained by the Cacti Group. See  |
 | about.php and/or the AUTHORS file for specific developer information.   |
 +-------------------------------------------------------------------------+
 | http://www.cacti.net/                                                   |
 +-------------------------------------------------------------------------+
*/

function plugin_routerconfigs_redownload_failed () {
	$t = time();
	$passed = array();
	// Get device that have not backed up in 24 hours + 30 minutes and that haven't been tried in the last 30 minutes
	$devices = db_fetch_assoc("SELECT * FROM plugin_routerconfigs_devices WHERE enabled = 'on' AND ($t - (schedule * 86400)) - 3600 > lastbackup AND $t - lastattempt > 1800", false);

	if (!empty($devices)) {
		db_execute("UPDATE plugin_routerconfigs_devices set lastattempt = $t WHERE $t - lastbackup > 88200 AND $t - lastattempt > 1800");
		foreach ($devices as $device) {
			print $device['hostname'] . "\n";
			plugin_routerconfigs_download_config($device);
			$t = time() - 120;
			$f = db_fetch_assoc("SELECT * FROM plugin_routerconfigs_backups WHERE btime > $t AND device = " . $device['id']);
			if (!empty($f)) {
				$passed[] = array ('hostname' => $device['hostname']);
			}
			sleep(10);
		}
	}

	if (!empty($passed)) {
		$message = "A successful backup has now been completed on these devices\n--------------------------------\n";
		foreach ($passed as $f) {
			$message .= $f['hostname'] . "\n";
		}
		echo $message;

		$email = read_config_option('routerconfigs_email');
		$from = read_config_option('routerconfigs_from');
		if (strlen($email) > 1) {
			if (strlen($from) < 2) {
				$from = 'ConfigBackups@reyrey.com';
			}
		}
		send_mail($email, $from, 'Network Device Configuration Backups - Reattempt', $message, $filename = '', $headers = '', $fromname = 'Config Backups');
	}
}


function plugin_routerconfigs_retention () {
	$backuppath = read_config_option("routerconfigs_backup_path");
	if (!is_dir($backuppath) || strlen($backuppath) < 2) {
		print "Backup Path is not set or is not a directory";
		exit;
	}

	$days = read_config_option('routerconfigs_retention');
	if ($days < 1 || $days > 365) {
		$days = 30;
	}
	$time = time() - ($days * 24 * 60 * 60);
	$backups = db_fetch_assoc("SELECT * FROM plugin_routerconfigs_backups WHERE btime < $time");
	foreach ($backups as $backup) {
		$dir = $backup['directory'];
		$filename = $backup['filename'];
		@unlink("$backuppath/$dir/$filename");
	}
	db_execute("DELETE FROM plugin_routerconfigs_backups WHERE btime < $time");
}

function plugin_routerconfigs_check_config ($data) {
	$data = explode("\n", $data);
	foreach ($data as $d) {
		if (trim($d) == 'end')
			return TRUE;
	}
	return FALSE;
}

function plugin_routerconfigs_download_config ($device) {
	$info = plugin_routerconfigs_retrieve_account($device['id']);
	$dir = $device['directory'];

	$backuppath = read_config_option("routerconfigs_backup_path");
	if (!is_dir($backuppath) || strlen($backuppath) < 2) {
		print "Backup Path is not set or is not a directory";
		exit;
	}

	$tftpserver = read_config_option("routerconfigs_tftpserver");
	if (strlen($tftpserver) < 2) {
		print "TFTP Server is not set";
		exit;
	}

	$tftpfilename = $device['hostname'];
	$filename = $tftpfilename;
	$telnet = new PHPTelnet();

	$devicetype = db_fetch_row("SELECT * FROM plugin_routerconfigs_devicetypes WHERE id = " . $device['devicetype']);

	if (empty($devicetype)){
		$devicetype = array('username' => 'sername:',
					'password' => 'assword:',
					'enable' => 'ena',
					'copytftp' => 'copy start tftp:',
					'version' => 'show version',
					'forceconfirm' => 0,
				);
	}
	$result = $telnet->Connect($device['ipaddress'], $info['username'], $info['password'], $devicetype);
	$debug = $telnet->debug;
	db_execute('UPDATE plugin_routerconfigs_devices SET lastattempt = ' . time() . ' WHERE id = ' . $device['id']);

	if ($result == 0) {
		$telnet->DoCommand($devicetype['enable'], $result);
		$debug .= $result;
		//echo $result;
		$telnet->DoCommand($info['password'], $result);
		$debug .= $result;
		//echo $result;
		$telnet->DoCommand($devicetype['copytftp'], $result);
		$debug .= $result;
		//echo $result;
		$telnet->DoCommand($tftpserver, $result);
		$debug .= $result;
		//echo $result;
		$telnet->DoCommand($filename, $result);
		$debug .= $result;
		//echo $result;

		if (strpos($result, 'confirm') !== FALSE || strpos($result, 'to tftp:') !== FALSE || $devicetype['forceconfirm']) {
			$telnet->DoCommand('y', $result);
			$debug .= $result;
			//echo $result;
		}

		$x = 0;
		while ($x < 30) {
			$telnet->GetResponse($result);
			$debug .= $result;
			//echo $result;

			if (strpos($result, 'Error'))
				break;

			$data = '';
			if (file_exists("$backuppath/$tftpfilename")) {
				clearstatcache();
				$file = fopen("$backuppath/$tftpfilename", 'r');
				if (filesize("$backuppath/$tftpfilename") > 0) {
					$data = fread($file, filesize("$backuppath/$tftpfilename"));
				}
				fclose($file);
				if (plugin_routerconfigs_check_config ($data)) {
					break;
				}
			}
			sleep(1);	
			$x++;
		}

		if (!file_exists("$backuppath/$tftpfilename")) {
			$telnet->error = 7;
			plugin_routerconfigs_save_error ($device['id'], $telnet);
			plugin_routerconfigs_save_debug($device, $debug);
			$telnet->Disconnect();
			return false;
		} else {
			@unlink("$backuppath/$tftpfilename");
		}

		//if (!plugin_routerconfigs_check_config ($data)) {
			//$telnet->error = 5;
			//plugin_routerconfigs_save_error ($device['id'], $telnet);
			//plugin_routerconfigs_save_debug($device, $debug);
			//$telnet->Disconnect();
			//return false;
		}

		$data = str_replace ("\n", "\r\n", $data);
		$data2 = explode("\r\n", $data);
		$lastchange = '';
		$lastuser = '';
		foreach ($data2 as $d) {
			if (strpos($d, 'Last configuration change at') !== FALSE) {
				$lastchange = substr($d, strpos($d, 'change at') + 10, strpos($d, ' by ') - (strpos($d, 'change at') + 10));

				$t = explode(' ', $lastchange);
				if (isset($t[5])) {
					$t = array($t[3], $t[4], $t[5], $t[0], $t[1]);
					$t = implode(' ', $t);
					$lastchange = strtotime($t);
					if (substr($d, strpos($d, ' by ')) !== FALSE) {
						$lastuser = substr($d, strpos($d, ' by ') + 4);
					}
				}
			}
			if (substr($d, 0, 9) == 'hostname ') {
				$filename = trim(substr($d, 9));
				if ($device['hostname'] != $filename) {
					db_execute("UPDATE plugin_routerconfigs_devices SET hostname = '$filename' WHERE id = " . $device['id']);
				}
			}
			if (substr($d, 0, 17) == 'set system name ') {
				$filename = trim(substr($d, 17));
				if ($device['hostname'] != $filename) {
					db_execute("UPDATE plugin_routerconfigs_devices SET hostname = '$filename' WHERE id = " . $device['id']);
				}
			}
		}

		if ($lastchange != '' && $lastchange != $device['lastchange']) {
			db_execute("UPDATE plugin_routerconfigs_devices SET lastchange = $lastchange, username = '$lastuser' WHERE id = " . $device['id']);
		} else if ($lastchange == '' && $devicetype['version'] != '') {
			$telnet->DoCommand($devicetype['version'], $version);
			$t = time();
			$debug .= $version;
			$version = explode("\n", $version);

			if (!empty($version)) {
				foreach ($version as $v) {
					if (strpos($v, ' uptime is ') !== FALSE) {
						$uptime = 0;
						$up = trim(substr($v, strpos($v, ' uptime is ') + 11));

						$up = explode(',', $up);
						$x = 0;
						foreach ($up as $u) {
							$s = explode(' ', trim($u));
							switch (trim($s[1])) {
								case 'years':
								case 'year':
									$uptime += ($s[0] * 31449600);
									break;
								case 'months':
								case 'month':
									$uptime += ($s[0] * 2419200);
									break;
								case 'weeks':
								case 'week':
									$uptime += ($s[0] * 604800);
									break;
								case 'days':
								case 'day':
									$uptime += ($s[0] * 86400);
									break;
								case 'hours':
								case 'hour':
									$uptime += ($s[0] * 3600);
									break;
								case 'minutes':
								case 'minute':
									$uptime += ($s[0] * 60);
									break;
								case 'seconds':
								case 'second':
									$uptime += $s[0];
									break;
							}
						}

						$lastuser = '-- Reboot --';
						$lastchange = $t - $uptime;
						$diff = $lastchange - $device['lastchange'];
						if ($diff < 0)
							$diff = $diff * -1;
						if ($diff > 60) {
							db_execute("UPDATE plugin_routerconfigs_devices SET lastchange = $lastchange, username = '$lastuser' WHERE id = " . $device['id']);
						} else {
							$lastchange = $device['lastchange'];
						}
					}
				}
			}
		}
		$telnet->Disconnect();

		if (strlen($data) > 100) {
			if (!is_dir("$backuppath/$dir")) {
				mkdir("$backuppath/$dir", 0777, true);
			}
			db_execute('UPDATE plugin_routerconfigs_devices SET lastbackup = ' . time() . ' WHERE id = ' . $device['id']);

			$date = date("Y-m-d-Hi");
			$file = fopen("$backuppath/$dir/$filename-$date", 'w');
			fwrite($file, $data);
			fclose($file);
			$data2 = mysql_escape_string($data);
			$t = time();
			if ($lastchange == '')
				 $lastchange = 0;
			db_execute('INSERT INTO plugin_routerconfigs_backups (device, btime, directory, filename, config, lastchange, username) VALUES (' . $device['id'] . ",$t,'$dir','$filename-$date', '$data2', $lastchange, '$lastuser')");
		} else {
			plugin_routerconfigs_save_error ($device['id'], $telnet);
			plugin_routerconfigs_save_debug($device, $debug);
			return false;
		}
	} else {
		plugin_routerconfigs_save_error ($device['id'], $telnet);
		plugin_routerconfigs_save_debug($device, $debug);
		return false;
	}
	plugin_routerconfigs_save_error ($device['id'], $telnet);
	plugin_routerconfigs_save_debug($device, $debug);
	return true;
}

function plugin_routerconfigs_save_debug($device, $debug) {
	$debug = base64_encode($debug);
	//echo "Saving Debug\n";
	db_execute("UPDATE plugin_routerconfigs_devices SET debug = '$debug' WHERE id = " . $device['id']);
}

function plugin_routerconfigs_save_error ($id, $telnet) {
	$error = $telnet->ConnectError($telnet->error);
	db_execute("UPDATE plugin_routerconfigs_devices SET lasterror = '$error' WHERE id = $id");
}

function plugin_routerconfigs_retrieve_account ($device) {
	if ($device == '') {
		return false;
	}
	$info = db_fetch_row("SELECT plugin_routerconfigs_accounts.* FROM plugin_routerconfigs_accounts,plugin_routerconfigs_devices WHERE plugin_routerconfigs_accounts.id = plugin_routerconfigs_devices.account AND plugin_routerconfigs_devices.id = " . $device, FALSE);
	if (isset($info['username'])) {
		$info['password'] = plugin_routerconfigs_decode($info['password']);
		return $info;
	}
	return false;		
}

function plugin_routerconfigs_decode ($info) {
	$info = base64_decode($info);
	$info = unserialize($info);
	$info = $info['password'];
	return $info;
}

function plugin_routerconfigs_encode ($info) {
	$a = array(rand(1,time()) => rand(1,time()),'password' => '', rand(1,time()) => rand(1,time()));
	$a['password'] = $info;
	$a = serialize($a);
	$a = base64_encode($a);
	return $a;
}

/*
PHPTelnet 1.1
by Antone Roundy
adapted from code found on the PHP website
public domain
*/
class PHPTelnet {
	var $show_connect_error=1;

	var $use_usleep=1;	// change to 1 for faster execution
		// don't change to 1 on Windows servers unless you have PHP 5
	var $sleeptime=125000;
	var $loginsleeptime=1000000;

	var $fp=NULL;
	var $loginprompt;
	var $error = 0;
	
	var $conn1;
	var $conn2;

	var $debug;
	
	/*
	0 = success
	1 = couldn't open network connection
	2 = unknown host
	3 = login failed
	4 = PHP version too low
	*/
	function Connect($server, $user, $pass, $devicetype) {
		$this->debug = '';
		$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]) {
				echo $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);
				if (strpos($r, $device['username']) === FALSE && strpos($r, 'Access not permitted.') !== FALSE || !$this->fp) {
					//echo $r;
					return 6;
				}

				if (strpos($r, $devicetype['username']) !== FALSE) {
					fputs($this->fp, "$user\r");
					$this->Sleep();
				}
				$r=explode("\n", $r);
				$this->loginprompt = trim(substr($r[count($r) - 1], 0, strpos($r[count($r) - 1], ' ')));
				@fputs($this->fp, "$pass\r");
				$res = '';
				$x = 0;
				while ($x < 10) {
					sleep(1);
					//$this->GetResponse($r);
//echo $r;
					$res .= $r;
					if (strpos($r, '#') !== FALSE || strpos($r, '> (') !== FALSE) {
						break;
					}
					$x++;
				}
				$r=explode("\n", $r);
				if (($r[count($r) - 1] == '') || ($this->loginprompt == trim($r[count($r) - 1]))) {
					$rv = 3;
					$this->Disconnect();
				}
			} else $rv = 1;
		}
		
		if ($rv) echo $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 = '';
		stream_set_timeout($this->fp, 1);
		do { 
			$r .= fread($this->fp, 2048);
			$this->debug .= $r;
			$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) {
			$this->error = $num;
			switch ($num) {
				case 1:
					return 'Unable to open network connection';
					break;
				case 2:
					return 'Unknown host';
					break;
				case 3:
					return 'Login failed';
					break;
				case 4:
					return 'Connect failed: Your servers PHP version is too low for PHP Telnet';
					break;
				case 5:
					return 'Bad download of config';
					break;
				case 6:
					return 'Access not Permitted';
					break;
				case 7:
					return 'No Config uploaded from Router';
					break;
			}
		}
		return '';
	}
}
grady
Cacti User
Posts: 60
Joined: Wed Feb 20, 2008 5:02 pm

Post by grady »

Did you ever get this sorted out? I too would like to backup HP gear via the routerconfigs plugin
dieselboy
Cacti User
Posts: 135
Joined: Wed May 27, 2009 5:10 pm

Post by dieselboy »

No, I am hoping someone could work with me on this? I've tried for hours to understand how the drop down box inside Cacti effects the config telnet commands used when logging into the switch. I have investigated the database and noted the commands.

The key thing we need to insert is a carriage return for the HP switches since it wants you to hit any key before it will prompt you for a log in. If I only knew how that database entry interacts with the functions.php then I could work it out myself and post back.

Basically, I need to know or understand at what point the database is looked into for the commands used for said device. I have gotten so far as to make the auto-detect part of the script work for ASA, switches, routers even if you need to enable though.
grady
Cacti User
Posts: 60
Joined: Wed Feb 20, 2008 5:02 pm

Post by grady »

Adding HP to plugin_routerconfigs_devicetypes will put it in the drop down. (I just added this)

Code: Select all

mysql> select * from plugin_routerconfigs_devicetypes;
+----+-------------+----------+----------+--------------------------+--------------+---------+--------------+
| id | name        | username | password | copytftp                 | version      | confirm | forceconfirm |
+----+-------------+----------+----------+--------------------------+--------------+---------+--------------+
|  1 | Cisco IOS   | sername: | assword: | copy run tftp            | show version | y       |            0 |
|  2 | Cisco CatOS | sername: | assword: | copy config tftp         |              | y       |            1 |
|  3 | HP 3500 yl  | sername: | assword: | copy running-config tftp | sh ver       |         |            0 |
+----+-------------+----------+----------+--------------------------+--------------+---------+--------------+
The harder part, like you mentioned is going to be authentication. If you take a look at router-accounts.php it looks like it saves it to the plugin_routerconfigs_accounts table. However, first it encodes the username and password. It looks like it does so using base64. (see the function plugin_routerconfigs_encode, decode) in functions.php. I don't know how to get around that. Any ideas?
dieselboy
Cacti User
Posts: 135
Joined: Wed May 27, 2009 5:10 pm

Post by dieselboy »

Hi yes, that shouldnt matter though. I have seen that database area, and we can use the code already written to call back passwords:

Code: Select all

$info['password']
we either use a password from the database that is assigned to that device, or create a new username / password for the new HP kit and assign it using the cacti plugin.

What I tried to do was re-jig the catOS database entry for HP kit. In honesty the HP kit isnt that much different from cisco, we just need to have any key sent to the HP kit so it then asks for the user credentials. The steps are;

1) press any key
2) username
3) password
4) copy start tftp [ipadd.] [filename]

Can you understand how the catOS database entry is used? I spent more than a few days on it and couldnt work it out.
grady
Cacti User
Posts: 60
Joined: Wed Feb 20, 2008 5:02 pm

Post by grady »

Oh. So fucntions.php gets the devices that it thinks are ready to be backed up:

Code: Select all

 $devices = db_fetch_assoc("SELECT * FROM plugin_routerconfigs_devices WHERE enabled = 'on' AND ($t - (schedule * 86400)) - 3600 > lastbackup AND $t - lastattempt > 1800", false);
It then makes sure it's valid and if yes, does:

Code: Select all

                        plugin_routerconfigs_download_config($device);
Thats defined below in that function name. So it sounds like maybe all we do is modify plugin_routerconfigs_download_config in functions.php to add an additional if. (if devicetype = HP then blargh)

Code: Select all

$devicetype = db_fetch_row("SELECT * FROM plugin_routerconfigs_devicetypes WHERE id = " . $device['devicetype']);

        if (empty($devicetype)){
                $devicetype = array('username' => 'sername:',
                                        'password' => 'assword:',
                                        'copytftp' => 'copy run tftp',
                                        'version' => 'show version',
                                        'forceconfirm' => 0,
                                );
        }
dieselboy
Cacti User
Posts: 135
Joined: Wed May 27, 2009 5:10 pm

Post by dieselboy »

I thought this, but I can not find "if device type = catOS" so, I had nothing to go on.
If you want to make changes, I can test here with my cacti setup (I have two and plenty of kit)
grady
Cacti User
Posts: 60
Joined: Wed Feb 20, 2008 5:02 pm

Post by grady »

So maybe this will work.

Code: Select all

     $devicetypeHP = db_fetch_row("SELECT name FROM plugin_routerconfigs_devicetypes WHERE id = " . $device['devicetypeHP']);


        if ($devicetypeHP == "HP"){
                $HPConnect = $telnet->ConnectHP($device['ipaddress'], $info['username'], $info['password'], $info['enablepw'], $devicetype);
                $debug = $telnet->debug;
                db_execute('UPDATE plugin_routerconfigs_devices SET lastattempt = ' . time() . ' WHERE id = ' . $device['id']);
        }

I then cloned the Connect function in the PHPTelnet class at the bottom, with a slight mod after the fsockopen statement. @fputs now has "\r", which should maybe send a return.

Code: Select all

        function ConnectHP($server, $user, $pass, $enablepw, $devicetype) {
                $this->debug = '';
                $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]) {
                                echo $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("\r",$this->fp, $this->conn1);
                                $this->Sleep();

                                @fputs($this->fp, $this->conn2);
                                $this->Sleep();

                                $this->GetResponse($r);
                                if (strpos($r, $devicetype['username']) === FALSE && strpos($r, 'Access not permitted.') !== FALSE || !$this->fp) {
                                        echo $r;
                                        return 6;
                                }
                                echo $r;
Id of course back up functions.php first.
Last edited by grady on Mon Mar 22, 2010 12:23 pm, edited 1 time in total.
dieselboy
Cacti User
Posts: 135
Joined: Wed May 27, 2009 5:10 pm

Post by dieselboy »

If you'd like you can edit your functions.php file and I'll try it?
As a sugestion, we could name the database entry HPSwitch (it may differ from HP devices?)
grady
Cacti User
Posts: 60
Joined: Wed Feb 20, 2008 5:02 pm

Post by grady »

I tried, it hates the additional telnet function. Not sure why yet. If left uncommented out it pukes
dieselboy
Cacti User
Posts: 135
Joined: Wed May 27, 2009 5:10 pm

Post by dieselboy »

Can you highlight the bad command somehow? What is the error?
grady
Cacti User
Posts: 60
Joined: Wed Feb 20, 2008 5:02 pm

Post by grady »

Well, the root cause there is I dont know where to put the \r (return) in that function. I'm playing around trying to figure that out
dieselboy
Cacti User
Posts: 135
Joined: Wed May 27, 2009 5:10 pm

Post by dieselboy »

Does the PHP error out or does it work but the config download not work?

I had to comment out the code which goes through the downloaded file and checks if its good or not otherwise it detects ASA configs as bad and deletes them. This was line 187 to 192
grady
Cacti User
Posts: 60
Joined: Wed Feb 20, 2008 5:02 pm

Post by grady »

My select or if statement from the below is whats causing the problem:

Code: Select all

        //$devicetypeHP = db_fetch_row("SELECT name FROM plugin_routerconfigs_devicetypes WHERE id = " . $device['devicetypeHP']);
        $devicetypeHP = db_fetch_row("SELECT name FROM plugin_routerconfigs_devicetypes WHERE id is not null");
        echo $devicetypeHP;

        if ($devicetypeHP == "HP"){
                $devicetype = db_fetch_row("SELECT * FROM plugin_routerconfigs_devicetypes WHERE id = " . $device['devicetype']);
                $HPConnect = $telnet->Connect($device['ipaddress'], '\r', $info['username'], $info['password'], $info['enablepw'], $devicetype);
                $debug = $telnet->debug;
                db_execute('UPDATE plugin_routerconfigs_devices SET lastattempt = ' . time() . ' WHERE id = ' . $device['id']);

                if ($HPConnect == 0) {
                $telnet->DoCommand($devicetype['copytftp'], $HPConnect);
                $debug .= $HPConnect;
                echo $HPConnect;
                $telnet->DoCommand($tftpserver, $HPConnect);
                $debug .= $HPConnect;
                echo $HPConnect;
                $telnet->DoCommand($filename, $HPConnect);
                $debug .= $HPConnect;
                echo $HPConnect;
        }
}
                if (strpos($HPConnect, 'confirm') !== FALSE || strpos($HPConnect, 'to tftp:') !== FALSE || $devicetype['forceconfirm']) {
                        $telnet->DoCommand('y', $HPConnect);
                        $debug .= $HPConnect;
                        echo $HPConnect;

        }
I've added a HP device and when I run router-download it echoes array, for some reason it's thinking that device type is empty.

Code: Select all

php router-download.php 

Processing hpswitch
Array
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest