Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Sunday, 5 June 2016

updating python script to SSH with and without Enable password for Cisco devices

python script to SSH with and without Enable password for Cisco devices
i have tried this on Cisco IOS, IOS-XE and NX-OS and works for me.

Without enable password requirement to print 'Show hostname' and 'Show version'(you can change that to whatever CLI you need to print.

import paramiko

def sshCall(host,port,user,passw):
  dssh = paramiko.SSHClient()
  dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  dssh.connect(hostname=host,port=port,username=user,password=passw)
  dssh.exec_command('term len 0')
  stdin, stdout, stderr = dssh.exec_command('show hostname')
  bc=stdout.read()
  print bc
  # b=bc.strip('\n')
  stdin, stdout, stderr = dssh.exec_command('show version')
  a= stdout.read()
  print a
  f = open('/output.txt', 'a')

  f.write(bc)

  f.write(a)
  f.close()
  dssh.close()

sshCall('1.1.1.1',22,"username","password”)

With enable password

import paramiko
import time

def sshCall(host,port,user,passw):
  dssh = paramiko.SSHClient()
  dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  dssh.connect(hostname=host,port=port, username=user,password=passw)
  shell = dssh.invoke_shell()
  time.sleep(1)
  shell.send('enable\n')
  shell.send('FixStream123!\n')
  time.sleep(1)
  shell.send('term len 0\n')

  shell.send('show version\n')
  time.sleep(2)
  resp = shell.recv(9999)
  print resp
  dssh.close()

sshCall('1.1.1.1',22,"usr","pwd")

Saturday, 4 June 2016

Juniper Contrail Python API


You can download the Contrail python API Bindings from here

https://github.com/Juniper/contrail-python-api

Install instructions

git clone https://github.com/Juniper/contrail-python-api
cd contrail-python-api
python setup.py install

So the basic example explains how to connect using the Client Method and list Virtual_Networks


import pycontrail.client as client
conn = client.Client(url='http://10.84.34.141:8082',
        auth_params={'type':'keystone',
        'auth_url':'http://10.84.34.141:5000/v2.0',
        'username':'admin',
        'password':'secret',
        'tenant_name':'admin'})

conn.virtual_networks_list()

I am going to explain how to collect Data that will make some sense, although a lot of python enthusiasts will figure it out but if this is any help id be happy
reason why i wanted to share this script is that i had taken time to write the loops to get all the dict data within lists etc. 

I printed all the output in JSON format as final output

from pycontrail import client
import jsonpickle

import jsonpickle
conn = client.Client(
        url='http://1.1.1.1:8082',auth_params={'type':'keystone','auth_url':'http://2.2.2.2:5000/v2.0','username':'admin','password':'password','tenant_name':'admin'})

route_instance_uuid_list=[]
bb = conn.routing_instances_list()
for each_route_instance in bb['routing-instances']:
    route_instance_uuid_list.append(each_route_instance['uuid'])


route_instance_detail_list=[]
for each_route_instance in route_instance_uuid_list:
    vn_detail_dict={'name':None,'route_instance':[],'route_target':[]}
    aa= conn.routing_instance_read(id=each_route_instance)
    vn_detail_dict['name'] =aa.name
    # print aa.name


    #route_instance
    try:
        route_instance=[]


        for each_routing in aa.routing_instance_refs:
            route_instance_dict={}
            route_instance_dict['route_instance']= dict(zip(range(0,len(each_routing['to'])), each_routing['to']))
            route_instance.append(route_instance_dict)
    except:
        pass
    vn_detail_dict['route_instance']=route_instance
    #route_instance

    #route_targets
    try:
        route_target=[]

        for each_routetarget in aa.route_target_refs:
            route_target_dict={}
            route_target_dict['route_target']= dict(zip(range(0,len(each_routetarget['to'])), each_routetarget['to']))
            route_target.append(route_target_dict)
    except:
        pass
    vn_detail_dict['route_target']=route_target
    #route_targets

    route_instance_detail_list.append(vn_detail_dict)



vn_instance_uuid_list=[]
vn=conn.virtual_networks_list()
for each_vn in vn['virtual-networks']:
    vn_instance_uuid_list.append(each_vn['uuid'])








vn_instance_detail_list=[]
for each_vn_instance in vn_instance_uuid_list:

    vn_instance_detail_dict={}
    gg=conn.virtual_network_read(id=each_vn_instance)
    vn_instance_detail_dict['virtual_network_network_id']= gg.virtual_network_network_id
    vn_instance_detail_dict['uuid']= gg.uuid
    vn_instance_detail_dict['name']= gg.name
    vn_instance_detail_dict['parent_name']= gg.parent_name
    vn_instance_detail_dict['parent_uuid']= gg.parent_uuid
    try:
        vn_instance_detail_dict['forwarding_mode']= gg.virtual_network_properties.forwarding_mode

        for each_ipam in gg.network_ipam_refs:
            ipam_subnet_list=[]
            for each_ipam_subnet in each_ipam['attr'].ipam_subnets:
                ipam_subnet_dict={}
                ipam_subnet_dict['default_gateway']= each_ipam_subnet.default_gateway
                ipam_subnet_dict['dns_server_address']= each_ipam_subnet.dns_server_address
                ipam_subnet_dict['subnet_uuid']= each_ipam_subnet.subnet_uuid
                ipam_subnet_dict['subnet_name'] =each_ipam_subnet.subnet_name
                ipam_subnet_dict['ip_prefix_len']= each_ipam_subnet.subnet.ip_prefix_len
                ipam_subnet_dict['ip_prefix']= each_ipam_subnet.subnet.ip_prefix
                ipam_subnet_list.append(ipam_subnet_dict)
                allocation_pool_list=[]
                for each_allocation_pool in  each_ipam_subnet.allocation_pools:
                    allocation_pool_dict={}
                    allocation_pool_dict['start'] =each_allocation_pool.start
                    allocation_pool_dict['end']= each_allocation_pool.end
                    allocation_pool_list.append(allocation_pool_dict)
                ipam_subnet_dict['allocation_pool']=allocation_pool_list

        vn_instance_detail_dict['ipam']=ipam_subnet_list

        network_policy_list=[]
        for each_network_policy in gg.network_policy_refs:
            network_policy_dict={}
            network_policy_dict['uuid']= each_network_policy['uuid']
            network_policy_dict['network_policy'] =dict(zip(range(0,len(each_network_policy['to'])), each_network_policy['to']))
            network_policy_list.append(network_policy_dict)
            vn_instance_detail_dict['network_policy']=network_policy_list

    except:
        pass
    vn_instance_detail_list.append(vn_instance_detail_dict)



np_uuid_list=[]
np_list = conn.network_policys_list()
for each_np in np_list['network-policys']:
    np_uuid_list.append(each_np['uuid'])


each_np_detail_list=[]
for each_np_uuid in np_uuid_list:
    each_np_detail_dict={'policy':[]}
    nppp = conn.network_policy_read(id=each_np_uuid)
    each_np_detail_dict['uuid']= nppp.uuid
    each_np_detail_dict['name']=  nppp.name
    each_np_detail_dict['parent_name']=  nppp.parent_name
    try:
        each_policy_list=[]
        for each_policy_entry in nppp.network_policy_entries.policy_rule:
            each_policy_dict={'dst_addresses':[],'src_addresses':[]}
            each_policy_dict['protocol']= each_policy_entry.protocol
            each_policy_dict['ethertype']= each_policy_entry.ethertype
            each_policy_dict['direction']= each_policy_entry.direction
            each_policy_dict['rule_uuid']= each_policy_entry.rule_uuid
            each_policy_dict['simple_action']=  each_policy_entry.action_list.simple_action
            each_policy_dict['gateway_name']=  each_policy_entry.action_list.gateway_name

            dst_address_list=[]
            for each_dst_address in each_policy_entry.dst_addresses:
                dst_address_dict={}
                dst_address_dict['network_policy']= each_dst_address.network_policy
                dst_address_dict['security_group']= each_dst_address.security_group
                dst_address_dict['subnet']= each_dst_address.subnet
                dst_address_dict['virtual_network']= each_dst_address.virtual_network
                dst_address_list.append(dst_address_dict)

            each_policy_dict['dst_addresses']=dst_address_list
            src_address_list=[]
            for each_src_address in each_policy_entry.src_addresses:
                src_address_dict={}
                src_address_dict['network_policy']= each_src_address.network_policy
                src_address_dict['security_group']=  each_src_address.security_group
                src_address_dict['subnet']=  each_src_address.subnet
                src_address_dict['virtual_network']=  each_src_address.virtual_network
                src_address_list.append(src_address_dict)
            each_policy_dict['src_addresses']=src_address_list
            each_policy_list.append(each_policy_dict)
        each_np_detail_dict['policy']=each_policy_list

    except:
        pass
    each_np_detail_list.append(each_np_detail_dict)



final_output = {
    'virtual_network_instance':vn_instance_detail_list,
    'route_instance':route_instance_detail_list,
    'network_policy':each_np_detail_list
}

print jsonpickle.pickler.encode(final_output)

    

Tuesday, 12 August 2014

python script to ssh and telnet and take input from Excel sheet

So this is a super cool script that i am going to share .

functions of the script

1. python script takes input from excel sheet cells for 
  • IP address
  • username 
  • password
  • transport type(ssh/telnet)
  • enable password
2. python script runs the functions defined and captures output of your choice and stores it in a file with the hostname/IP address of the router

assuming you have pre-installed the packages as shown in the previous script

import paramiko
import sys
import os
import xlrd
import unidecode
import telnetlib
import time

def sshCall(data1,data2,data3):
dssh = paramiko.SSHClient()
dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
dssh.connect(data1.encode('ascii'),port=22, username=data2.encode('ascii'), password=data3.encode('ascii'))  
dssh.exec_command('term len 0')
stdin, stdout, stderr = dssh.exec_command('show hostname')
bc=stdout.read()
b=bc.strip('\n')
stdin, stdout, stderr = dssh.exec_command('sh ver')
a= stdout.read()
print bc
f = open(b, 'a')
f.write(a)
f.close()
dssh.close()
def telNetCall(data1,data2,data3,data5):
hostlist= [ (data1),] 
for host in hostlist:
print data1
user  = (data2)
password = (data3)
ena = (data5)
telnet  = telnetlib.Telnet(host) 
telnet.read_until('Username: ', 3)
telnet.write(user.encode('ascii') + '\r')
telnet.read_until('Password: ', 3)
telnet.write(password.encode('ascii') + '\r')
telnet.write('enable' + '\r\n')
telnet.write(ena.encode('ascii') + '\r\n')
telnet.write('term len 0' + '\r\n')
telnet.write("show version"+ "\r\n")
telnet.write('exit' + '\r')
a=telnet.read_all()
f = open(host, 'w')
f.write(str(a))


os.chdir("C:/myscript/")
workbook = xlrd.open_workbook('Book1.xls')
worksheet = workbook.sheet_by_name('Sheet1') 


for x in range(1,4):
data1 = (worksheet.cell(x,0).value).decode('ascii')
data2 = (worksheet.cell(x,1).value).decode('ascii')
data3 = (worksheet.cell(x,2).value).decode('ascii')
data4 = (worksheet.cell(x,3).value).decode('ascii')
data5 = (worksheet.cell(x,4).value).decode('ascii')
if data4 == 'telnet':
telNetCall(data1,data2,data3,data5)
else:
sshCall(data1,data2,data3)





Sunday, 10 August 2014

python script to ssh into cisco device

So this one had my head scratching not because the script was too complex , but the overall effort to run the script. 

Again as i am new to python it took a while to get on with installing the correct packages and loading the right binaries.


so i will go step by step first on what is needed to run the ssh script in python 2.7

step1: installing the paramiko package

go to this link and download the paramiko package and unzip it in the python 2.7 folder
https://pypi.python.org/pypi/paramiko/1.14.0

now install it as show below

step2: intalling the ecdsa0.11 package

go to this link and download the ecdsa0.11 package and unzip it in the python 2.7 folder

now install it as show below

step3: download the relevant pre built pycrypto binaries for windows machine from link below


step4: so finally the script

import paramiko
import sys
import os

dssh = paramiko.SSHClient()
dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
dssh.connect('10.95.34.104',port=22, username='admin', password='Cisc0123')
dssh.exec_command('term len 0')
stdin, stdout, stderr = dssh.exec_command('sh ver')
a= stdout.read()
print a
f = open('testing.txt', 'a')
f.write(a)
f.close()
dssh.close()








Saturday, 9 August 2014

simple python script to telnet into cisco IOS device

I am no expert in python but just trying to share , something i used recently. its helpful if you want to telnet to IOS devices and get some output. using python scripts

i am using python version 2.7
you can download it from here
https://www.python.org/download/releases/2.7/

Script:

import os
import telnetlib

def telNetCall():
host  = "xx.xx.xx.xx"
user  = "username"
password = "password"
telnet  = telnetlib.Telnet(host) 
telnet.read_until('Username: ', 3)
telnet.write(user + '\r')
telnet.read_until('Password: ', 3)
telnet.write(password + '\r')
telnet.write('enable' + '\r\n')
telnet.write('enable_password' + '\r\n')
telnet.write('term len 0' + '\r\n')
telnet.write("show version"+ "\r\n")
telnet.write('exit' + '\r')
a=telnet.read_all()
f = open(host, 'w')
f.write(str(a))
telNetCall()


the script will telnet to the device and write the show version (or anything you define) into a file with the name as the host IP address.
f = open(host, 'w')

so lets run the script now for a small demo, but before that make sure you saved your script with proper indentation and file extension as .py

 step1: in your command prompt change your directory to the python27 directory

step2: execute the script by just typing the script file name with the extension as shown above

step3: done !!! your output file should be created in the python directory as show below with the file name as           the host IP address