Showing posts with label cisco. Show all posts
Showing posts with label cisco. Show all posts

Friday, June 15, 2012

How to create dynagen network topology with multible dynamips service



I explained "Using dynagen & dynamips for multible cisco router simulation" in the http://stdioe.blogspot.com/2012/06/using-dynagen-dynamips-for-multible.html article before. I'm going to talk about how to create a dynagen configuration for multiple dynamips service. Also we are going to work about dynagen performance optimization. Let's create a network topology to try on our system.

Now, we have got three dynamips services. Each single dynamips service is creating three virtual routers and all of them are connected to each other. The first dynamips service contains R1, R2 and R3 routers, the second dynamips service contains R4, R5 and R6 routers, the third dynamips service contains R7, R8 and R9 routers. They are  seperated on configuration but logically they are connected to each other directly.

Start to practice,



1-) Starting dynamips services with different port numbers,

ismail@ismail-ThinkPad-T410:~$ dynamips -H 7200 &
ismail@ismail-ThinkPad-T410:~$ dynamips -H 7301 &
ismail@ismail-ThinkPad-T410:~$ dynamips -H 7402 &

2-) Create dynamips configuration file corresponding our network topology,

###############################1-Dynamips-1#############################
[localhost:7200]
  udp=10000
  workingdir = /tmp/workingdy1

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100 
  disk0=128

 [[Router R1]]
  model = 3725
  console = 2001
  autostart = false
  S0/0 = R2 S0/0

 [[Router R2]]
  model = 3725
  console = 2002
  autostart = false
  S0/0 = R1 S0/0
  S0/1 = R3 S0/0

 [[Router R3]]
  model = 3725
  console = 2003
  autostart = false
  WIC0/0 = WIC-2T
  S0/0 = R2 S0/1 
  S0/1 = R7 S0/1

###############################1-Dynamips-1#############################

###############################2-Dynamips-2#############################
[localhost:7201]
  udp=11000
  workingdir = /tmp/workingdy2

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100 
  disk0=128

 [[Router R4]]
  model = 3725
  console = 2004
  autostart = false
  S0/0 = R5 S0/0
  S0/1 = R8 S0/1

 [[Router R5]]
  model = 3725
  console = 2005
  autostart = false
  S0/0 = R4 S0/0
  S0/1 = R6 S0/0

 [[Router R6]]
  model = 3725
  console = 2006
  autostart = false
  S0/0 = R5 0/1

###############################2-Dynamips-2#############################

###############################3-Dynamips-3#############################
[localhost:7202]
  udp=12000
  workingdir = /tmp/workingdy3

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100 
  disk0=128

 [[Router R7]]
  model = 3725
  console = 2007
  autostart = false
  S0/0 = R9 S0/0
  S0/1 = R3 S0/1

 [[Router R8]]
  model = 3725
  console = 2008
  autostart = false
  WIC0/0 = WIC-2T
  S0/0 = R9 S0/1
  S0/1 = R4 S0/1

 [[Router R9]]
  model = 3725
  console = 2009
  autostart = false
  S0/0 = R7 0/0
  S0/1 = R8 0/0

###############################3-Dynamips-3#############################

I saved the content above with a file name of sample2.net name in /tmp directory.  We need working directories as below:

ismail@ismail-ThinkPad-T410:~$ mkdir /tmp/workingdy1
ismail@ismail-ThinkPad-T410:~$ mkdir /tmp/workingdy2
ismail@ismail-ThinkPad-T410:~$ mkdir /tmp/workingdy3

3-) The working directories are ready. Right now, dynagen service is ready to start. I did a mistake to shown follow up how to troubleshooting.

ismail@ismail-ThinkPad-T410:~$ dynagen /tmp/sample2.net 
Reading configuration file...

Shutdown in progress...
Shutdown completed.
Shutdown in progress...
Shutdown completed.
Shutdown in progress...
Shutdown completed.
*** Warning:  Connecting R6 S0/0 to R5 0/1 resulted in:
 malformed destination interface: R5 0/1
*** Warning:  Connecting R9 S0/0 to R7 0/0 resulted in:
 malformed destination interface: R7 0/0
*** Warning:  Connecting R9 S0/1 to R8 0/0 resulted in:
 malformed destination interface: R8 0/0

*** Error:  errors during loading of the topology file, please correct them
Shutdown in progress...
Error: could not communicate with dynamips server localhost
It may have crashed. Check the dynamips server output.
Exiting...
Press ENTER to exit
[3]+  Segmentation fault      (core dumped) dynamips -H 7202
ismail@ismail-ThinkPad-T410:~$ 

Normally, you can define a connection on both ends of lines. But on our sample, dynagen service doesn't accept this duplicate defination. I removed " S0/1 = R6 S0/0" line in R5 router part. Also "  S0/0 = R9 S0/0" line in R7 part and " S0/0 = R9 S0/1" line in R8 part. After editing, sample2.net file has a content as seen below:


###############################1-Dynamips-1#############################
[localhost:7200]
  udp=10000
  workingdir = /tmp/workingdy1

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100
  disk0=128

 [[Router R1]]
  model = 3725
  console = 2001
  autostart = false
  S0/0 = R2 S0/0

 [[Router R2]]
  model = 3725
  console = 2002
  autostart = false
  #S0/0 = R1 S0/0
  S0/1 = R3 S0/0

 [[Router R3]]
  model = 3725
  console = 2003
  autostart = false
  #S0/0 = R2 S0/1
  S0/1 = R7 S0/1

###############################1-Dynamips-1#############################

###############################2-Dynamips-2#############################
[localhost:7201]
  udp=11000
  workingdir = /tmp/workingdy2

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100
  disk0=128

 [[Router R4]]
  model = 3725
  console = 2004
  autostart = false
  S0/0 = R5 S0/0
  S0/1 = R8 S0/1

 [[Router R5]]
  model = 3725
  console = 2005
  autostart = false
  #S0/0 = R4 S0/0
  S0/1 = R6 S0/0

 [[Router R6]]
  model = 3725
  console = 2006
  autostart = false
#  S0/0 = R5 0/1

###############################2-Dynamips-2#############################

###############################3-Dynamips-3#############################
[localhost:7202]
  udp=12000
  workingdir = /tmp/workingdy3

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100
  disk0=128

 [[Router R7]]
  model = 3725
  console = 2007
  autostart = false
  S0/0 = R9 S0/0
  #S0/1 = R3 S0/1

 [[Router R8]]
  model = 3725
  console = 2008
  autostart = false
  S0/0 = R9 S0/1
  #S0/1 = R4 S0/1

 [[Router R9]]
  model = 3725
  console = 2009
  autostart = false
#  S0/0 = R7 0/0
#  S0/1 = R8 0/0

###############################3-Dynamips-3#############################

We already started dynamips with 7200, 7201 and 7202 ports but dynagen service has been crashed. Some dynamips services may have been crashed. We have to check them before restarting dynages service.

ismail@ismail-ThinkPad-T410:~$ ps -ef | grep dynamips
ismail    3811  3756  1 10:15 pts/0    00:00:14 dynamips -H 7200
ismail    3829  3756  1 10:16 pts/0    00:00:14 dynamips -H 7201
ismail    4017  3756  0 10:27 pts/0    00:00:00 grep --color=auto dynamips

So One dynamips service crashed and other two ones still working. I want to kill all dynamips services and start them again to make sure about everything on the way. We can kill a PID using the "kill -9 3811" command but I selected pkill command in this sample to show first practice.

ismail@ismail-ThinkPad-T410:~$ pkill dynamips
[1]-  Terminated              dynamips -H 7200
[2]+  Terminated              dynamips -H 7201
ismail@ismail-ThinkPad-T410:~$ 

And now, there is no any running dynamip process. We can start all of them again,

ismail@ismail-ThinkPad-T410:~$ dynamips -H 7201 &
ismail@ismail-ThinkPad-T410:~$ dynamips -H 7202 &
ismail@ismail-ThinkPad-T410:~$ dynamips -H 7203 &
ismail@ismail-ThinkPad-T410:~$ dynagen /tmp/sample2.net 
Reading configuration file...
...
...
...
Dynagen management console for Dynamips and Pemuwrapper 0.11.0
Copyright (c) 2005-2007 Greg Anuzelli, contributions Pavel Skovajsa

=> 

Finally dynagen loaded our network topology. We can handle it now. We can start routers with "start" command on dynagen console and get console of routers with "telnet Rx" command (x is number of router name, for example R4).

We may need to use the "idlepc" parameter in this sample. If you need more performance, you have to use idlepc parameter. Dynagen can optimize itself using the value given for idlepc. We have to learn only what is our idlepc value for our system. We can use following command in the dynagen console,

=> start R1
=> idlepc get R1
Please wait while gathering statistics...

Please wait while gathering statistics...
Done. Suggested idling PC:
   0x60c08128 (count=22)
   0x60c08164 (count=33)
   0x60c08180 (count=35)
   0x60c081c0 (count=66)
   0x62b2823c (count=45)
   0x60c08bf8 (count=23)
   0x60c08c20 (count=20)
   0x614b0e34 (count=38)
   0x62b2b134 (count=20)
   0x6026bca4 (count=30)
Restart the emulator with "--idle-pc=0x60c08128" (for example)
   1: 0x60c08128 [22]
   2: 0x60c08164 [33]
   3: 0x60c08180 [35]
   4: 0x60c081c0 [66]
   5: 0x62b2823c [45]
   6: 0x60c08bf8 [23]
   7: 0x60c08c20 [20]
   8: 0x614b0e34 [38]
   9: 0x62b2b134 [20]
  10: 0x6026bca4 [30]
Potentially better idlepc values marked with "*"
Enter the number of the idlepc value to apply [1-10] or ENTER for no change: 
No changes made
=> 

If you find any "*" line, you can use this line value. If you don't have any marked line with "*", you can try to get idlepc value again.

Monday, June 4, 2012

Using dynagen & dynamips for multible cisco router simulation


dynage dynamips cisco linux console terminal network lab simulation


       If you want to simulate a Cisco router, you can use dynamips but if you want to create a network topology you have to use both of dynagen and dynamips. This blog post is about about creating a sample network topology, connecting routers to each other and testing all nodes in the topology.


       I'm using Ubuntu 12.04 to show an example now. First, we have to install dynagen (and dynamips) on Ubuntu 12.04. Actually we will also need dynamips but dynamips is a dependance of dynamips. So if we install dynagen, dynamips will be installed with dynagen.



ismail@ismail-ThinkPad-T410:~$ sudo apt-get install dynagen 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  dynamips python-configobj
The following NEW packages will be installed:
  dynagen dynamips python-configobj
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 1,070 kB/1,418 kB of archives.
After this operation, 4,263 kB of additional disk space will be used.
Do you want to continue [Y/n]? 
Get:1 http://tr.archive.ubuntu.com/ubuntu/ precise/main python-configobj all 4.7.2+ds-3build1 [233 kB]
Get:2 http://tr.archive.ubuntu.com/ubuntu/ precise/multiverse dynagen all 0.11.0-6 [836 kB]
Fetched 1,070 kB in 0s (1,495 kB/s)
Selecting previously unselected package dynamips.
(Reading database ... 206573 files and directories currently installed.)
Unpacking dynamips (from .../dynamips_0.2.7-0.2.8RC2-5ubuntu1_amd64.deb) ...
Selecting previously unselected package python-configobj.
Unpacking python-configobj (from .../python-configobj_4.7.2+ds-3build1_all.deb) ...
Selecting previously unselected package dynagen.
Unpacking dynagen (from .../dynagen_0.11.0-6_all.deb) ...
Processing triggers for man-db ...
Processing triggers for doc-base ...
Processing 1 added doc-base file...
Registering documents with scrollkeeper...
Setting up dynamips (0.2.7-0.2.8RC2-5ubuntu1) ...
Setting up python-configobj (4.7.2+ds-3build1) ...
Setting up dynagen (0.11.0-6) ...
Processing triggers for python-support ...
ismail@ismail-ThinkPad-T410:~$ 

Let's start to work with sample network topology;



       There are only 3 routers on our sample network topology. Only one dynamips instance should be enough.

1-) Start dynamips instance


ismail@ismail-ThinkPad-T410:~$ dynamips -H 7100 &
[1] 16919
ismail@ismail-ThinkPad-T410:~$ Cisco Router Simulation Platform (version 0.2.8-RC2-amd64)
Copyright (c) 2005-2007 Christophe Fillot.
Build date: Jan 18 2011 19:25:29

Hypervisor TCP control server started (port 7100).

ismail@ismail-ThinkPad-T410:~$ ps -ef | grep dynamips
ismail   16919  8265  6 17:59 pts/2    00:00:00 dynamips -H 7100
ismail   16934  8265  0 17:59 pts/2    00:00:00 grep --color=auto dynamips
ismail@ismail-ThinkPad-T410:~$ 

       We are starting dynamips service with "dynamips -H 7100 &" and checking it with "ps -ef | grep dynamips" command.

2-) Create a dynagen configuration file


# [START INSTANCE1]

[localhost:7100]
  udp=10000
  workingdir = /tmp/working

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
#  idlepc = ?? We will talk about it later.
  ghostios = true
  sparsemem = true
  idlemax = 100
  disk0=128

 [[Router R1]]
  model = 3725
  console = 2001
  autostart = false
#  F0/0 =
  S0/0 = R2 S0/0

 [[Router R2]]
  model = 3725
  console = 2002
  autostart = false
#  F0/0 =
  S0/0 = R1 S0/0
  S0/1 = R3 S0/0

 [[Router R3]]
  model = 3725
  console = 2003
  autostart = false
  S0/0 = R2 S0/1
# F0/0 =

# [FINISH INSTANCE1] 

       First stage is about connecting to an existing dynamips service. Dynamips will create some files when it is loading a topology. This files will be created in  the "workingdir" directory.

       Second stage is about creating a Cisco Router model. We have to define a Cisco ios file path and some hardware specifications in this stage.

       The last stages are about defining our virtual routers. If we create more than one models, we can select different models for earch virtual router. The "console" key defines the port number. We will use this port numbers to connect to console of router. Autostart key defines either manual or auto router booting while starting to dynagen process. Finally we will define  connections between virtual routers.

       I created a "working" directory under /tmp and the dynagen configuration file before starting the dynagen as shown below:

ismail@ismail-ThinkPad-T410:~$ vim /tmp/sample1.net
{write dynagen configuration file content as above INSTANCE1}
ismail@ismail-ThinkPad-T410:~$ 
ismail@ismail-ThinkPad-T410:~$ dynagen /tmp/sample1.net 
Reading configuration file...

Shutdown in progress...
Shutdown completed.
CPU0: carved JIT exec zone of 64 Mb into 2048 pages of 32 Kb.
NVRAM is empty, setting config register to 0x2142
C3725 instance 'ghost-c3725-adventerprisek9-mz.124-15.T13.bin-localhost.ghost' (id 3):
  VM Status  : 0
  RAM size   : 128 Mb
  NVRAM size : 128 Kb
  IOS image  : /tmp/c3725-adventerprisek9-mz.124-15.T13.bin

Loading ELF file '/tmp/c3725-adventerprisek9-mz.124-15.T13.bin'...
ELF entry point: 0x80008000

C3725 'ghost-c3725-adventerprisek9-mz.124-15.T13.bin-localhost.ghost': starting simulation (CPU0 PC=0xffffffffbfc00000), JIT enabled.

C3725 'ghost-c3725-adventerprisek9-mz.124-15.T13.bin-localhost.ghost': stopping simulation.
Network successfully loaded

Dynagen management console for Dynamips and Pemuwrapper 0.11.0
Copyright (c) 2005-2007 Greg Anuzelli, contributions Pavel Skovajsa

=> list
Name       Type       State      Server          Console   
R1         3725       stopped    localhost:7100  2001      
R2         3725       stopped    localhost:7100  2002      
R3         3725       stopped    localhost:7100  2003      
=> 
=> ?

Documented commands (type help <topic>):
========================================
capture  confreg  cpuinfo  export  hist    list  py      save   show   suspend
clear    console  end      filter  idlepc  no    reload  send   start  telnet 
conf     copy     exit     help    import  push  resume  shell  stop   ver    

=> 
=> start R1
Warning: Starting R1 with no idle-pc value
CPU0: carved JIT exec zone of 64 Mb into 2048 pages of 32 Kb.
C3725 instance 'R1' (id 0):
  VM Status  : 0
  RAM size   : 128 Mb
  NVRAM size : 128 Kb
  IOS image  : /tmp/c3725-adventerprisek9-mz.124-15.T13.bin

Loading ELF file '/tmp/c3725-adventerprisek9-mz.124-15.T13.bin'...
ELF loading skipped, using a ghost RAM file.
ELF entry point: 0x80008000

C3725 'R1': starting simulation (CPU0 PC=0xffffffffbfc00000), JIT enabled.
100-VM 'R1' started
=> 
=> start R2
Warning: Starting R2 with no idle-pc value
CPU0: carved JIT exec zone of 64 Mb into 2048 pages of 32 Kb.
NVRAM is empty, setting config register to 0x2142
C3725 instance 'R2' (id 1):
  VM Status  : 0
  RAM size   : 128 Mb
  NVRAM size : 128 Kb
  IOS image  : /tmp/c3725-adventerprisek9-mz.124-15.T13.bin

Loading ELF file '/tmp/c3725-adventerprisek9-mz.124-15.T13.bin'...
ELF loading skipped, using a ghost RAM file.
ELF entry point: 0x80008000

C3725 'R2': starting simulation (CPU0 PC=0xffffffffbfc00000), JIT enabled.
100-VM 'R2' started
=> start R3
Warning: Starting R3 with no idle-pc value
CPU0: carved JIT exec zone of 64 Mb into 2048 pages of 32 Kb.
NVRAM is empty, setting config register to 0x2142
C3725 instance 'R3' (id 2):
  VM Status  : 0
  RAM size   : 128 Mb
  NVRAM size : 128 Kb
  IOS image  : /tmp/c3725-adventerprisek9-mz.124-15.T13.bin

Loading ELF file '/tmp/c3725-adventerprisek9-mz.124-15.T13.bin'...
ELF loading skipped, using a ghost RAM file.
ELF entry point: 0x80008000

C3725 'R3': starting simulation (CPU0 PC=0xffffffffbfc00000), JIT enabled.
100-VM 'R3' started
=> 

Open another terminal and execute this command:

ismail@ismail-ThinkPad-T410:~$ telnet localhost 2001
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connected to Dynamips VM "R1" (ID 0, type c3725) - Console port

when press enter will appear this;

% Please answer 'yes' or 'no'.
Would you like to enter the initial configuration dialog? [yes/no]: 

press Ctrl+c and enter and enter again:

Press RETURN to get started!


*Mar  1 00:00:03.843: %LINEPROTO-5-UPDOWN: Line protocol on Interface VoIP-Null0, changed state to up
*Mar  1 00:00:03.847: %LINEPROTO-5-UPDOWN: Line protocol on Interface IPv6-mpls, changed state to up
*Mar  1 00:00:03.927: %LINK-3-UPDOWN: Interface Serial0/0, changed state to up
*Mar  1 00:00:03.935: %LINK-3-UPDOWN: Interface Serial0/1, changed state to up
*Mar  1 00:00:04.927: %LINEPROTO-5-UPDOWN: Line protocol on Interface Serial0/0, changed state to up
*Mar  1 00:00:04.935: %LINEPROTO-5-UPDOWN: Line protocol on Interface Serial0/1, changed state to up
*Mar  1 00:00:32.927: %LINEPROTO-5-UPDOWN: Line protocol on Interface Serial0/1, changed state to down
*Mar  1 00:01:26.839: %LINEPROTO-5-UPDOWN: Line protocol on Interface Serial0/0, changed state to down
*Mar  1 00:01:32.875: %LINEPROTO-5-UPDOWN: Line protocol on Interface Serial0/0, changed state to up
*Mar  1 00:01:39.015: %LINK-5-CHANGED: Interface FastEthernet0/1, changed state to administratively down
*Mar  1 00:0
Router>1:39.075: %LINK-5-CHANGED: Interface FastEthernet0/0, changed state to administratively down
*Mar  1 00:01:40.115: %SYS-5-RESTART: System restarted --
Cisco IOS Software, 3700 Software (C3725-ADVENTERPRISEK9-M), Version 12.4(15)T13, RELEASE SOFTWARE (fc3)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2010 by Cisco Systems, Inc.
Compiled Wed 07-Apr-10 12:44 by prod_rel_team
*Mar  1 00:01:40.123: %SNMP-5-COLDSTART: SNMP agent on host Router is undergoing a cold start
*Mar  1 00:01:40.147: %LINEPROTO-5-UPDOWN: Line protocol on Interface FastEthernet0/1, changed state to down
*Mar  1 00:01:40.147: %LINEPROTO-5-UPDOWN: Line protocol on Interface FastEthernet0/0, changed state to down
*Mar  1 00:01:40.159: %CRYPTO-6-ISAKMP_ON_OFF: ISAKMP is OFF
*Mar  1 00:01:40.159: %CRYPTO-6-GDOI_ON_OFF: GDOI is OFF
*Mar  1 00:01:40.951: %LINK-5-CHANGED: Interface Serial0/0, changed state to administratively down
*Mar  1 00:01:40.951: %LINK-5-CHANGED: Interface Serial0/1, changed state to administratively down
*Mar  1 00:01:41.951: %LINEPROTO-5-UPDOWN: Line protocol on Interface Serial0/0, changed state to down
*Mar  1 00:01:43.839: %IP-5-WEBINST_KILL: Terminating DNS process
Router>

        So you can get console for other virtual routers with "telnet localhost 2002", "telnet localhost 2003" and "telnet localhost 2004" commands.   

        I'm preparing more samples for multiple instances, physical ethernet connectivity and switch simulation with dynagen&dynamips.

Wednesday, November 30, 2011

How to Connect Cisco Router with PHP Scripts



I used to explain a Perl version of these scripts in page "http://stdioe.blogspot.com/2011/09/how-to-connect-cisco-router-with-perl.html". And now, I'm talking about the Php version. Because, Php is known to be easier than Perl by the most of the people. You may want to implement these samples in your existing projects. Essentially, we are establishing a telnet session between our script and a Cisco router. It's only a telnet connection. There are a lot of telnet-scripts for php in the internet. You can use them but we are talking about a specific situation. Let's write it from scratch.

I prepare to write those scripts as much as parametric, that is, I will avoid writing all of staff hard-coded. "$argv" variable is a predefined array in Php and it is able to capture the given parameters as well as in the console. For example,

<?php
#!/usr/bin/php
$if(isset($argv[2])) {
print "The first parameter is:".$argv[1]."\n";
print "The second parameter is:".$argv[2]."\n";
} else {
print "usage: ./sample.php parameter1 parameter2 \n";
print "or \n";
print "usage: php sample.php parameter1 parameter2 \n";
}

?>

You can execute the script by typing "./sample.php" or "php sample.php" directly in your console. If you want to execute it as "./sample.php", you have to add the line (#!/usr/bin/php) on the top of your script and you have to give executive permissions to sample.php. (chmod +x sample.php). If you want to execute with the syntax "php sample.php", you don't need to add the line and give those rights. Because, the executing rights are already given for "php" part.

The sample.php script is capturing your parameters using the array variable $argv. You can see all of the $argv content using the line "print_r($argv);" in you Php script. So we will use the $argv array to take ip_address, username and password values from the user. I used fsockopen, fput and fgets commands to establish connections, to send commands and to get the output from the router, respectively.

If the cisco router output is very long for one page, it returns a " -- More -- " statement in the last line. If we press the space button on the keyboard when we see this statement, the router will send next page. If we press the enter key on the keyboard when we see this statement, router will send the next line. So we have to control the content and if there is a " -- More -- " statement in the content, we have to send a space character to get next part of the router output. We will control the " -- More -- " statement with an "ereg" function of php.

The php script for connecting to the Cisco router (telnetCisco.php):

#!/usr/bin/php
<?php
if(!isset($argv[2])) {
die ("usage: ./scriptName router_ip username password\n");
}
$port = 23;
$timeout = 10;
$router_ip = $argv[1];
$username = $argv[2];
$password = $argv[3];

$connection = fsockopen($router_ip, $port, $errno, $errstr, $timeout);

if(!$connection){
echo "Connection failed\n";
exit();
} else {
echo "Connected\n";
fputs($connection, "$username\r\n");
fputs($connection, "$password\r\n");
fputs($connection, "show run\r\n");
fputs($connection, " ");

$j = 0;
while ($j < 16) {
fgets($connection, 128);
$j++;
}
stream_set_timeout($connection, 2);
$timeoutCount = 0;
while (!feof($connection)){
$content = fgets($connection, 128);
$content = str_replace("\r", '', $content);
$content = str_replace("\n", "", $content);
print $content."\n";

# If the router say "press space for more", send space char:
if (ereg('--More--', $content) ){ // IF current line contain --More-- expression,
fputs ($connection, " "); // sending space char for next part of output.
} # The "more" controlling part complated.

$info = stream_get_meta_data($connection);
if ($info['timed_out']) { // If timeout of connection info has got a value, the router not returning a output.
$timeoutCount++; // We want to count, how many times repeating.
}
if ($timeoutCount >2){ // If repeating more than 2 times,
break; // the connection terminating..
}
}
}
echo "End.\r\n";
?>

"stream_get_meta_data" function is the most critical one in this article. Because, I used the stream_get_meta_data to check the status of connection. Following output shows the "stream_get_meta_data" content with print_r function to see "how to recognize end of the output". (The last three loop)

....
...
Array
(
[stream_type] => tcp_socket
[mode] => r+
[unread_bytes] => 0
[seekable] =>
[timed_out] => 1
[blocked] => 1
[eof] =>
)
Array
(
[stream_type] => tcp_socket
[mode] => r+
[unread_bytes] => 0
[seekable] =>
[timed_out] => 1
[blocked] => 1
[eof] =>
)
Array
(
[stream_type] => tcp_socket
[mode] => r+
[unread_bytes] => 0
[seekable] =>
[timed_out] => 1
[blocked] => 1
[eof] =>
)

The time_out values are "1" in the last two loops. The $timeoutCount value is counting that "1"s in the telnetCisco.php and if it gets "1" more than two times, it stops reading the output with a "break;" line.

Friday, October 21, 2011

Checking System Room Temperature with Cisco, Hp, Netscreen

{ able to visit following link to read newest entry about same subject;
This article has got a mobile phone client application to follow up to system room temperature. That first version is especially for Nokia Phones. }

The "http://stdioe.blogspot.com/2011/09/how-to-follow-up-temperature-of-system_23.html" article is explaining "How to follow up temperature of system room" via an IBM Blade Chassis device. I used to plan to explain how to use it because, the most reliable device on my system room is IBM Blade chassis. But may most of SDTIOE blog users haven't got an IBM blade chassis. Anyway that article can be able to help them ofcourse but I can re-write it for frequently used devices such as Cisco, Juniper and Hp. These products also have different operation systems. So each version has got little differences. This article presents some composite solutions for those systems.

Checking the system room temperature with Cisco:


Cisco routers have internaly got "show environment" or "show environment temperature" commands. We can get the temperature information with these commands. we can also use the article on page "http://stdioe.blogspot.com/2011/09/how-to-follow-up-temperature-of-system_23.html" to get that info from Cisco routers using the script below:

#!/usr/bin/perl

use Net::Telnet::Cisco;

my $session = Net::Telnet::Cisco->new(Host => 'x.x.x.x');
$session->login('TelnetUser', 'TelnetPassword');

# Execute a command
my @output = $session->cmd('show environment');
print @output;

$session->close;



attention!:
Cisco routers have different IOS versions and different IOS's have got different level of detail.

First Cisco example:

The first example is about Cisco 3661. It has got following IOS version;

HostName_Router_3661#show version 
Cisco Internetwork Operating System Software
IOS (tm) 3600 Software (C3660-IK9S-M), Version 12.2(13)T12, RELEASE SOFTWARE (fc1)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2004 by cisco Systems, Inc.
Compiled Tue 30-Mar-04 14:38 by ccai
Image text-base: 0x60008940, data-base: 0x61C20000

ROM: System Bootstrap, Version 12.0(6r)T, RELEASE SOFTWARE (fc1)
ROM: 3600 Software (C3660-IK9S-M), Version 12.2(13)T12, RELEASE SOFTWARE (fc1)

HostName_Router_3661 uptime is 7 weeks, 5 days, 11 hours, 21 minutes
System returned to ROM by reload
System restarted at 04:17:12 ISTANBUL Sat Aug 27 2011
System image file is "flash:c3660-ik9s-mz.122-13.T12.bin"

cisco 3660 (R527x) processor (revision 1.0) with 119808K/11264K bytes of memory.
Processor board ID JAC0617A0XT
R527x CPU at 225Mhz, Implementation 40, Rev 10.0, 2048KB L2 Cache
Channelized E1, Version 1.0.
Bridging software.
X.25 software, Version 3.0.0.
SuperLAT software (copyright 1990 by Meridian Technology Corp).
Primary Rate ISDN software, Version 1.1.
Basic Rate ISDN software, Version 1.1.


3660 Chassis type: ENTERPRISE
5 FastEthernet/IEEE 802.3 interface(s)
2 Serial network interface(s)
8 ISDN Basic Rate interface(s)
1 ATM network interface(s)
2 Channelized E1/PRI port(s)
2 Voice FXO interface(s)
2 Voice FXS interface(s)
DRAM configuration is 64 bits wide with parity disabled.
125K bytes of non-volatile configuration memory.
24576K bytes of processor board System flash (Read/Write)

Configuration register is 0x2102

HostName_Router_3661#


This IOS version supports only the "show environment" command and the output is simple. It hasn't got any value about the temperature as shown below:

HostName_Router_3661#show environment 

Power Supply 1 is present.
Thermal status: normal
Input Voltage status: normal
DC Output Voltage status: normal

Power Supply 2 is present.
Thermal status: normal
Input Voltage status: normal
DC Output Voltage status: normal

Board Temperature: normal.

HostName_Router_3661#


We have to grep the "Thermal status:" line and split it using the ":" character and get the usual part. The perl script should be changed for this goal as shown below:

#!/usr/bin/perl
use Net::Telnet::Cisco;
my $session = Net::Telnet::Cisco->new(Host => 'x.x.x.x');
$session->login('userName', 'passWord');
my @output = $session->cmd('show environment');

$session->close;

foreach $item (@output)
{
if(grep(/Thermal status/, $item) == "1") {
($key, $value) = split(/:/,$item);
}
}

sub trim($)
{
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}


$value = trim($value);
print "theValue:".$value."\n";

# If you want to write result to a file, you can use following part with erase "#" chars.

#open (target, ">tempfile.txt") || die ("Could not open file <br> $!");
#print target "$value";
#close (target);


We can do the parsing step in this Perl script or we can save the output of "show environment" command to a file and than handle it with shell commands. Lets try this way on "Second cisco example":

Second Cisco example:

The second example is about Cisco 38xx. It has got following IOS version;

HostName_Router_3800#show version 
Cisco IOS Software, 3800 Software (C3845-ADVIPSERVICESK9-M), Version 12.4(11)T3, RELEASE SOFTWARE (fc4)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2007 by Cisco Systems, Inc.
Compiled Wed 11-Jul-07 21:30 by prod_rel_team

ROM: System Bootstrap, Version 12.4(13r)T, RELEASE SOFTWARE (fc1)

HostName_Router_3800 uptime is 7 weeks, 4 days, 15 hours, 56 minutes
System returned to ROM by power-on
System image file is "flash:c3845-advipservicesk9-mz.124-11.T3.bin"


This product contains cryptographic features and is subject to United
States and local country laws governing import, export, transfer and
use. Delivery of Cisco cryptographic products does not imply
third-party authority to import, export, distribute or use encryption.
Importers, exporters, distributors and users are responsible for
compliance with U.S. and local country laws. By using this product you
agree to comply with applicable laws and regulations. If you are unable
to comply with U.S. and local laws, return this product immediately.

A summary of U.S. laws governing Cisco cryptographic products may be found at:
http://www.cisco.com/wwl/export/crypto/tool/stqrg.html

If you require further assistance please contact us by sending email to
export@cisco.com.

Cisco 3845 (revision 1.0) with 482304K/41984K bytes of memory.
Processor board ID FTX1135A1E0
4 FastEthernet interfaces
2 Gigabit Ethernet interfaces
1 Virtual Private Network (VPN) Module
DRAM configuration is 64 bits wide with parity enabled.
479K bytes of NVRAM.
125440K bytes of ATA System CompactFlash (Read/Write)

Configuration register is 0x2142 (will be 0x2102 at next reload)

HostName_Router_3800#


This IOS version supports only the "show environment" command but the output has higher level of detail when we compare it to "First Example". It has got temperature values as shown below:

HostName_Router_3800#show environment 

SYS PS1 is present.
Fan status: Normal
Input Voltage status: Normal
DC Output Voltage status: Normal
Type: AC
Thermal status: Normal

SYS PS2 is absent.

AUX(-48V) PS1 is present.
Status: Normal

AUX(-48V) PS2 is absent.
Compliance Mode: IEEE 802.af compliant

Fan 1 Normal
Fan 2 Normal
Fan 3 Normal

Fan Speed is Normal

Alert settings:
Intake temperature warning: Enabled, Threshold: 55
Core temperature warning: Enabled, Threshold: 70 (CPU: 90)

Board Temperature: Normal
Internal-ambient temperature = 31, Normal
CPU temperature = 42, Normal
Intake temperature = 24, Normal
Backplane temperature = 25, Normal

Voltage 1(3300) is Normal, Current voltage = 3316 mV
Voltage 2(5150) is Normal, Current voltage = 5153 mV
Voltage 3(2500) is Normal, Current voltage = 2525 mV
Voltage 4(1200) is Normal, Current voltage = 1215 mV

Nominal frequency

HostName_Router_3800#


We are interested in the temperature of system room, so we will use "Backplane temperature" part in this case. But other values are really very helpful for different purposes so you can edit this sample for something else like CPU. In this case, the Perl script records all of the output of "show environment" command to a file and we will handle that work using linux shell commands,

#!/usr/bin/perl
use Net::Telnet::Cisco;
my $session = Net::Telnet::Cisco->new(Host => 'x.x.x.x');
$session->login('userName', 'passWord');
my @output = $session->cmd('show environment');

$session->close;

open (target, ">tempfile.txt") || die ("Could not open file <br> $!");
print target "@output";
close (target);


Right now, all the information that we need is in the text file. We can handle it easily with linux shell commands. Lets continue,

grep "Backplane temperature" tempfile.txt | awk -F ' ' '{print $4}' | awk -F ',' '{print $1}'


The above result is 25 in this sample. We can use this final result as described on "http://stdioe.blogspot.com/2011/09/how-to-follow-up-temperature-of-system_23.html" article.

Checking system room temperature with Juniper / Netscreen:

Right now, I'm using an ISG2000 to prepare this article. The version information is;


Hardware Version: 3010(0)-(04), FPGA checksum: 00000000, VLAN1 IP (0.0.0.0)
Software Version: 6.1.0r3.0, Type: Firewall+VPN


We can use the following command to get the temperature information:

UGC:isg2000-UP(M)-> get chassis 
Chassis Environment:
Power Supply: Good
Fan Status: Good
CPU Temperature: 104'F ( 40'C)
Slot Information:
Slot Type S/N Assembly-No Version Temperature
0 System Board 0079082006000411 0051-005 E01 80'F (27'C), 84'F (29'C)
4 Management 0081082006000307 0049-004 D11 104'F (40'C)
5 ASIC Board 000319230H060098 0050-003 C00
Marin FPGA version 9, Jupiter ASIC version 1, Fresno FPGA version 102
I/O Board
Slot Type S/N Version FPGA version
1 2 port 10/100/1000T 0142092006000038 C00 20
3 2 port 10/100/1000T 0142092006000036 C00 20
4 4 port 10/100 0138082006000020 D01 6
Alarm Control Information:
Power failure audible alarm: disabled
Fan failure audible alarm: disabled
Low battery audible alarm: disabled
Temperature audible alarm: disabled
Normal alarm temperature is 132'F (56'C)
Severe alarm temperature is 150'F (66'C)
UGC:isg2000-UP(M)->


We can use the "|" (pipe) function to get required lines only. (Also This feature exists in Cisco. I try to write different solutions in each single example. But of course you can also use the pipe function in Cisco example.)

UGC:isg2000-UP(M)-> get chassis | include temperature
CPU Temperature: 104'F ( 40'C)
Slot Type S/N Assembly-No Version Temperature
Temperature audible alarm: disabled
Normal alarm temperature is 132'F (56'C)
Severe alarm temperature is 150'F (66'C)
UGC:isg2000-UP(M)->


This output is better, isn't it? Let's write a Perl script to get this info from the Juniper box to a file on our system.

#!/usr/bin/perl

use Net::Telnet::Netscreen ();

my $fw = new Net::Telnet::Netscreen(host=>'x.x.x.x');

$fw->login('username','password') or die $fw->error;

@lines = $fw->cmd("get chassis | include temperature");

open (target, ">tempfile.txt") || die ("Could not open file <br> $!");
print target "@lines";
close (target);


Now, we can use the content of tempfile.txt file. If you want to focus on only only a single line of this content, you can change "temperature" part on "get chassis | include temperature" command but It's not needed because, we can already manipulate that string with grep and awk commands.

Checking system room temperature with HP Procurve switch:

The first step is writing a Perl script to get the temperature information from Hp Procurve Switch. We can use a script as shown below:


#!/usr/bin/perl

use Net::Telnet ();
$session = new Net::Telnet (Timeout => 5,
Telnetmode => 0,
Prompt => '/PROMPTofDEVICE#/',
Host => "x.x.x.x");

# $session->waitfor('/Press any key to continue/');
# $session->print("");

$session->waitfor('/Password: /');
$session->print('PassworDofDevice');

$session->waitfor('/PROMPTofDEVICE#/');

@lines = $session->cmd("show system temperature");

$session->cmd("exit");
$session->cmd("exit");

open (target, ">tempfile.txt") || die ("Could not open file <br> $!");
print target "@lines";
close (target);


When we connect to a Procurve device, a "Press any key to continue" expression is shown. Some versions don't require this message to be shown. If you want this message to be shown, you can delete the '#' chars at the beginning of lines. The tempfile.txt file contains the information below:

 System Air Temperatures
# |Current Temp | Max Temp | Min Temp | Threshold | OverTemp
-------+-------------+----------+----------+-----------+----------
Sys-1 | 20C | 29C | 14C | 55C | NO


We can use a command as follows:

grep Sys-1 tempfile.txt | awk -F ' ' '{print $3}'


We can add that script to crontab and record output to mysql table. The other script/service can analyze recorded values like "http://stdioe.blogspot.com/2011/09/how-to-follow-up-temperature-of-system_23.html" article.