Wednesday 27 September 2017

Python for network engineer:- Configure multiple router using SSH :- Python2.7

import paramiko
import time
import sys
import logging
import socket

remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# store router ip in ip.txt file in same folder where script is.
ips = [i.strip() for i in open("ip.txt")]

g = open('config.txt', 'r+')# store configuration in config.txt file in same folder where script is.
str = g.read()
g.close

for ip in ips:
    try:
        remote_conn_pre.connect(ip, username='test', password='test', timeout=4, look_for_keys=False, allow_agent=False)

        remote_conn = remote_conn_pre.invoke_shell()
        print (ip + ' === Device Reachable')
        remote_conn.send("\n")
        remote_conn.send((str))
        time.sleep(2)
        #output = remote_conn.recv(5000)
        #print (output)
    except paramiko.AuthenticationException:
        print ip + ' === Bad credentials'
    except paramiko.SSHException:
        print ip + ' === Issues with ssh service'
    except socket.error:
        print ip + ' === Device unreachable'

Saturday 23 September 2017

Python for network engineer: cisco device backup using SSH : python2.7

Below script will take the backup of cisco devices in the folder where you have stored your python script. Please make sure ip.txt file(which contains router IP address) is also in same folder.

Below is the sample ip.txt file.


import paramiko
import time
import datetime

ssh1 = paramiko.SSHClient()
ssh1.set_missing_host_key_policy(paramiko.AutoAddPolicy())

now = datetime.datetime.now()

#open file in read mode
#ip.txt is a text file which contains routers IP address. Make sure it is stored in same folder #where the python script is. 
f = open("ip.txt","r")
lines = f.readlines()
f.close()

#open file in write mode and remove spaces between rows.

f = open("ip.txt","w")
for line in lines:
    if line!=""+"\n":
        f.write(line)
f.close()

ips = [i.strip() for i in open("ip.txt")]

for ip in ips:
    try:
        filename_prefix = (ip)
        ssh1.connect(ip,username='test', password='test')
        ssh = ssh1.invoke_shell()
        time.sleep(5)
        print ip
        ssh.send("\nterminal length 0\n")
        ssh.send("show run\n")
        time.sleep(5)
        output = ssh.recv(65535)
        print output
        filename = "%s_%.2i-%.2i-%i_%.2i-%.2i-%.2i" % (filename_prefix,now.day,now.month,now.year,now.hour,now.minute,now.second)
        fp=open(filename,"w")
        fp.write(output)
        fp.close()
       
    except:
        response = 'Failed'
        print (ip + " is not reachable")




Friday 22 September 2017

Python for network Engineer:- SSH to cisco router and run multiple commands :- python2.7

import paramiko
import time
#from getpass import getpass

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.10.1', username='test', password='test')


ssh = ssh.invoke_shell()

ssh.send("show ip int brief\n")
time.sleep(1)
output = ssh.recv(65535)
print output
time.sleep(5)
ssh.send("sh ver\n")
time.sleep(1)
output = ssh.recv(65535)
print output


Monday 18 September 2017

How to remove rows with specific text from the notepad using python 2.7

Below script is used to remove specific text from notepad.

Below script is used to remove specific text from the notepad using python. To demonstrate the same we have used a file which has “networking” word in the file.

#open the file in read mode which you need to modify, we have used ip.txt file.
file= open("ip.txt","r")
# Read the file
lines = file.readlines()
# close the file
file.close()

# Read the file in write mode
file = open("ip.txt","w")
# Reading each line and writing text, which is not a "networking" word, back to the file.
for line in lines:
    if line!="networking"+"\n":
        file.write(line)
file.close()

Before the script execution, ip.txt contains below content. You can see that below file contains word "networking" in many rows and our onjective is to remove all the rows which contains word "networking".






















After script execution, all rows containing  word "networking" has been deleted.

  

How to remove empty rows from notepad using Python 2.7

Below script is used to remove empty rows from notepad.

#open the file in read mode which you need to modify, we  have used ip.txt file.
file= open("ip.txt","r")
# Read the file
lines = file.readlines()
# close the file
file.close()

# Read the file in write mode
file = open("ip.txt","w")
# Reading each line and writing text which is not a space back to the file.
for line in lines:
    if line!=""+"\n":
        file.write(line)
file.close()

Before the script execution, ip.txt contains below content. You can see there are various spaces in it.




















After script execution, All empty rows has been deleting from the file.











Thursday 14 September 2017

Python for network engineer :- RUN ping test to a destination from multiple routers using Python2.7




Below script is used to run ping test to a destination from all routers.

e.g ip.txt must in same folder where you are storing you python program.

Note:- Make sure router IP must be reachable from the machine where python script is configured.

File used in the scripts are :-
import telnetlib
import time

user = "test"
password = "test"

ips = [i.strip() for i in open("ip.txt")]

for ip in ips:
     telnet = telnetlib.Telnet(ip)
     telnet.read_until("Username: ")
     telnet.write(user + "\n")
     telnet.read_until("Password: ")
     telnet.write(password + "\n")
     telnet.write("ping 192.168.10.100\n") #< 192.168.10.100 is the destination
     time.sleep(1)
     telnet.write("exit\n")
     print telnet.read_all()

Python for network engineer :- Cisco router config backup using Python2.7



Below script is used to take backup of multiple devices. Make sure when you call a file in python then that file must be stored in same folder where you are storing your python script.

e.g both ip.txt must in same folder where you are storing you python program.

Note:- Make sure router IP must be reachable from the machine where python script is configured.



File used in the scripts are :-

ip.txt :- A notepad file contains below router IP address.

192.168.10.1
192.168.10.2
192.168.10.3


import telnetlib
import datetime

now = datetime.datetime.now()
ips = [i.strip() for i in open("ip.txt")]
username = "test"
password = "test"

for ip in ips:
    filename_prefix = (ip)
    tn = telnetlib.Telnet(ip)
    tn.read_until("Username:")
    tn.write(username+"\n")
    tn.read_until("Password:")
    tn.write(password+"\n")
    tn.write("terminal length 0"+"\n")
    tn.write("sh run"+"\n")
    tn.write("exit"+"\n")
    output=tn.read_all()

    filename = "%s_%.2i-%.2i-%i_%.2i-%.2i-%.2i" % (filename_prefix,now.day,now.month,now.year,now.hour,now.minute,now.second)

    fp=open(filename,"w")
    fp.write(output)
    fp.close()

Python for network engineer :- Configure multiple router using telnet :-python 2.7


Below script is used to configure multiple devices. In below script ACL needs to be applied to multiple routers. Both Router IP and configuration are stored in different files Make sure when you call a file in python then that file must be stored in same folder where you are storing your python script.

e.g both config.txt must in same folder where you are storing you python program.

Note:- Make sure router IP must be reachable from the machine where python script is configured.

File used in the scripts are :-

Config.txt :- A notepad file contains below ACL configuration

conf t

ip access-list extended Restrict_Outlets
Permit ip any 10.130.127.0 0.0.0.255
deny ip any 10.126.0.0 0.1.255.255
deny ip any 10.128.0.0 0.3.255.255
deny ip any 10.175.0.0 0.0.255.255
deny ip any 10.176.0.0 0.7.255.255
deny ip any 10.190.0.0 0.1.255.255
deny ip any 10.192.0.0 0.15.255.255
deny ip any 10.208.0.0 0.1.255.255
deny ip any 10.210.0.0 0.0.255.255
deny ip any 10.60.0.0 0.0.255.255
permit ip any any

int fa3/0
ip access-group Restrict_Outlets out
no shut

ip.txt :- A notepad file contains below router IP address.

192.168.10.1
192.168.10.2
192.168.10.3
====================Program============

import time
import telnetlib
import sys

#=====Credential for the devices
user = "test"
password = "test"

#=====config.txt contains the ACL

g = open('config.txt', 'r+')   
str = g.read()
g.close

#=====Extracting routers IP from ip.txt file and storing it in variable ips.

ips = [i.strip() for i in open("ip.txt")]

#=====Below FOR loop is  configuring ACL to one router at a time.

for ip in ips:
     telnet = telnetlib.Telnet(ip)
     telnet.read_until("Username: ")
     telnet.write(user + "\n")
     telnet.read_until("Password: ")
     telnet.write(password + "\n")
     telnet.write(str)
     telnet.write("end\n")
     telnet.write("exit\n")
     time.sleep(5)
     print ip
     print telnet.read_all()

====================END============

Router config example:-

hostname R1

interface FastEthernet0/0
 ip address 192.168.10.1 255.255.255.0
 duplex full
 no shut

interface FastEthernet3/0
 no ip address
 ip access-group Restrict_Outlets out ----<<<<<
 shutdown
 duplex auto
 speed auto

line vty 0 4
 login local
line vty 5 16
 login local
!
!
end






Python file modes


The modes are: 
  • r’ – Only to read a file.
  • w’ – Used to edit and write new information to the file.
  • a’ – Appending mode:- Used to add new data in existing file.  
  • r+’ – Special read and write mode, When need to perform both read and write functions to the file.

Wednesday 13 September 2017

Python for network engineer:- Configure Cisco router using Python2.7

We tried to configure loopback0 on the router using python. Same script can be used to configure anything on the router. We just need to add telnet.write command to configure the cisco router.

import telnetlib

user = "test"
password = "test"

HOST = "192.168.1.100"

telnet = telnetlib.Telnet(HOST)

telnet.read_until("Username: ")
telnet.write(user + "\n")
telnet.read_until("Password: ")
telnet.write(password + "\n")
telnet.write("conf t\n")
telnet.write("int lo0\n")
telnet.write("ip address 1.1.1.1 255.255.255.0\n")
telnet.write("end\n")
telnet.write("exit\n")
print telnet.read_all()

=== output===

R1#conf t
Enter configuration commands, one per line.  End with CNTL/Z.
R1(config)#int lo0
R1(config-if)#ip address 1.1.1.1 255.255.255.0
R1(config-if)#end
R1#exit

Python for network engineer :- SSH to Cisco router using Python2.7

Below script can be used to access the device using SSH and capture show ip int brief command output.

import paramiko  #--<< import Paramiko library
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # --<< to add host key
ssh.connect('192.168.1.100', port=22, username='test', password='test')--<< Device IP address, ssh port , username and password of the device)
stdin,stdout,stderr=ssh.exec_command('show ip int brief')
output=stdout.readlines()
type(output)
print '\n'.join(output)


Output:-

Interface                  IP-Address      OK? Method Status                Protocol

FastEthernet0/0            192.168.1.100   YES manual up                    up      

FastEthernet1/0            unassigned      YES unset  administratively down down    

FastEthernet1/1            unassigned      YES unset  administratively down down    

FastEthernet2/0            unassigned      YES unset  administratively down down    

FastEthernet2/1            unassigned      YES unset  administratively down down    

FastEthernet3/0            unassigned      YES unset  administratively down down    

FastEthernet3/1            unassigned      YES unset  administratively down down    

>>> 

Python for network engineer:- Telnet to Cisco router using Python

Below script can be used to telnet Cisco router using Python script and can capture show version output.


import telnetlib # --<< importing telnet library

user = "test"   #--<< username configured in router
password = "test" #--<<Password configured in router


HOST = "192.168.1.100" #--<<IP address of the router

telnet = telnetlib.Telnet(HOST)

telnet.read_until("Username: ") # --<<Reading username from the router CLI screen
telnet.write(user + "\n") #--<< Configure username which is configured above

telnet.read_until("Password: ") #--<<Reading Password from the router CLI screen
telnet.write(password + "\n") #--<< Configure password which is configured above

telnet.write("terminal length 0\n") #--<< Configure command to capture the complete output
telnet.write("show version \n")  #--<<configure  show run

telnet.write("exit\n")  # --<<exit from the router


print telnet.read_all()  #-<<Read output from above show version command

Tuesday 12 September 2017

Errno 10060 - SSH paramiko error

Traceback (most recent call last):
  File "D:python\SSH.py", line 3, in <module>
    ssh.connect('192.168.1.100', port=22, username='test' , password='test')
  File "C:\Python27\lib\site-packages\paramiko\client.py", line 310, in connect
    retry_on_signal(lambda: sock.connect(addr))
  File "C:\Python27\lib\site-packages\paramiko\util.py", line 276, in retry_on_signal
    return function()
  File "C:\Python27\lib\site-packages\paramiko\client.py", line 310, in <lambda>
    retry_on_signal(lambda: sock.connect(addr))
  File "C:\Python27\lib\socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

Remove the space from ssh connect command

    ssh.connect('192.168.1.100', port=22, username='test', password='test')

How to install Paramiko - Python

Make sure machine have direct internet access.

1. Go to Python27 folder.

C:\>cd Python27

C:\Python27>dir
 Volume in drive C is Windows
 Volume Serial Number is 7A6A-22DB

 Directory of C:\Python27

09/07/2017  04:08 PM    <DIR>          .
09/07/2017  04:08 PM    <DIR>          ..
09/07/2017  04:08 PM    <DIR>          DLLs
09/07/2017  04:08 PM    <DIR>          Doc
09/07/2017  04:08 PM    <DIR>          include
09/07/2017  04:14 PM    <DIR>          Lib
09/07/2017  04:08 PM    <DIR>          libs
12/17/2016  08:49 PM            38,591 LICENSE.txt
12/17/2016  08:34 PM           474,595 NEWS.txt
12/17/2016  08:44 PM            27,136 python.exe
12/17/2016  08:44 PM            27,648 pythonw.exe
12/03/2016  09:01 PM            56,938 README.txt
09/07/2017  04:08 PM    <DIR>          Scripts
09/07/2017  04:08 PM    <DIR>          tcl
09/07/2017  04:08 PM    <DIR>          Tools
12/17/2016  08:44 PM           111,104 w9xpopen.exe
               6 File(s)        736,012 bytes
              10 Dir(s)  19,453,014,016 bytes free

2. Go to script folder.

C:\Python27>cd Scripts

C:\Python27\Scripts>dir
 Volume in drive C is Windows
 Volume Serial Number is 7A6A-22DB

 Directory of C:\Python27\Scripts

09/07/2017  04:08 PM    <DIR>          .
09/07/2017  04:08 PM    <DIR>          ..
09/07/2017  04:08 PM            89,449 easy_install-2.7.exe
09/07/2017  04:08 PM            89,449 easy_install.exe
09/07/2017  04:08 PM            89,421 pip.exe
09/07/2017  04:08 PM            89,421 pip2.7.exe
09/07/2017  04:08 PM            89,421 pip2.exe
               5 File(s)        447,161 bytes
               2 Dir(s)  19,453,014,016 bytes free

3. Install Paramiko

C:\Python27\Scripts>pip install paramiko
Collecting paramiko
  Using cached paramiko-2.2.1-py2.py3-none-any.whl
Collecting bcrypt>=3.1.3 (from paramiko)
  Downloading bcrypt-3.1.3-cp27-cp27m-win32.whl
Collecting cryptography>=1.1 (from paramiko)
  Downloading cryptography-2.0.3-cp27-cp27m-win32.whl (1.1MB)
    100% |################################| 1.1MB 36kB/s
Collecting pyasn1>=0.1.7 (from paramiko)
  Downloading pyasn1-0.3.4-py2.py3-none-any.whl (63kB)
    100% |################################| 71kB 26kB/s
Collecting pynacl>=1.0.1 (from paramiko)
  Downloading PyNaCl-1.1.2-cp27-cp27m-win32.whl (138kB)
    100% |################################| 143kB 30kB/s
Collecting six>=1.4.1 (from bcrypt>=3.1.3->paramiko)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting cffi>=1.1 (from bcrypt>=3.1.3->paramiko)
  Downloading cffi-1.10.0-cp27-cp27m-win32.whl (147kB)
    100% |################################| 153kB 25kB/s
Collecting ipaddress (from cryptography>=1.1->paramiko)
  Downloading ipaddress-1.0.18-py2-none-any.whl
Collecting asn1crypto>=0.21.0 (from cryptography>=1.1->paramiko)
  Using cached asn1crypto-0.22.0-py2.py3-none-any.whl
Collecting enum34 (from cryptography>=1.1->paramiko)
  Downloading enum34-1.1.6-py2-none-any.whl
Collecting idna>=2.1 (from cryptography>=1.1->paramiko)
  Downloading idna-2.6-py2.py3-none-any.whl (56kB)
    100% |################################| 61kB 38kB/s
Collecting pycparser (from cffi>=1.1->bcrypt>=3.1.3->paramiko)
  Downloading pycparser-2.18.tar.gz (245kB)
    100% |################################| 256kB 42kB/s
Installing collected packages: six, pycparser, cffi, bcrypt, ipaddress, asn1cryp
to, enum34, idna, cryptography, pyasn1, pynacl, paramiko
  Running setup.py install for pycparser ... done
Successfully installed asn1crypto-0.22.0 bcrypt-3.1.3 cffi-1.10.0 cryptography-2
.0.3 enum34-1.1.6 idna-2.6 ipaddress-1.0.18 paramiko-2.2.1 pyasn1-0.3.4 pycparse
r-2.18 pynacl-1.1.2 six-1.10.0

4. Import Paramiko in the common shell

>>> run import paramiko

>>> import paramiko
>>> import time