cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
86620
Views
35
Helpful
18
Replies

Basic Python Script

nemenciobeberu
Level 1
Level 1

Hi All,

 

im working as WAN edge engineer and still  telnet/ssh manually to device. I'm new and studying python to automate things but most of the videos i watched is using either mac or ubuntu as host pc. 

my office laptop is using windows and i cannot bring other pc inside our office. Can anyone help or maybe share simple python script hosted in windows box to access routers/switch and run show ip interface brief?

 

Thanks in advance 

Bebu

 

18 Replies 18

Try mine...

it has 3 files:

general-show.py  >>> this is the script

general-show-hosts.txt  >>> to store the devices info one per line in format: hostname ipAddr, e.g. switch01 10.1.1.1

general-show-cmd.txt >>> whatever cli cmd, e.g. show clock, show ip int brief, show ip route... one cli per line. The script was written to block the configuration thus it will not make change to the device.

Note: you may need to change files permission to allow other users to execute this script.

====================

file general-show.py 

 

"""
 Written by Them Huyen - Window version
 This is the general script to run the show cmd only to multiple devices and capture to file general-show-cap.txt
 File general-show-hosts.txt is a list of devices in format hostname ipAddr on each line
 File general-show-cmds.txt is a list of show cmd line by line
 To run: from Windows cmd, type in: python D:\scripts\general-show\general-show.py
 Example: C:\Users> python D:\scripts\general-show\general-show.py
"""
import paramiko
import time
import datetime
import getpass
import os
import re
import socket
paramiko.util.log_to_file("filename.log")
try:
    os.remove('D:\scripts\general-show\general-show-cap.txt')
except OSError:
    pass
with open('D:\scripts\general-show\general-show-hosts.txt') as f:
    devices = f.readlines()
    print ""
    username = raw_input('Enter the TACACS Username: ')
    password = getpass.getpass('Enter the TACACS Password: ')
for line in devices:
  try:
    output_str = ""
    device_list = line.split()
    host = device_list[0].strip()
    ip = device_list[1].strip()
    print ''
    print '##########################################################'
    print ''
    print "!!! Attempting SSH to " + host + " " + ip + " !!!"
    print ""
    ssh_client = paramiko.SSHClient()
    ssh_client
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(ip, username=username, password=password, look_for_keys=False, allow_agent=False)
    print ''
    print "!!! SSH successfully established !!!"
    remote_conn = ssh_client.invoke_shell()
    output = remote_conn.recv(10000)
    remote_conn.send("\n")
    remote_conn.send("term len 0\n")
    remote_conn.send("term exec prompt timestamp\n")
    config_mode = re.compile('conf[a-z]* t[a-z]*')
    file = open('D:\scripts\general-show\general-show-cmds.txt', 'r')
    for cmds in file:
       match_config = config_mode.search(cmds)
       if match_config:
          print '!!! Configuration is not allowed. Exit... !!!'
          print ''
          exit ()
       else:
          remote_conn.send(cmds)
          remote_conn.send('\n')
    remote_conn.send("exit\n")
    time.sleep(5)
    output = remote_conn.recv(150000)
    output_str = output.decode('utf-8')
    print (output_str)
  except paramiko.AuthenticationException:
    print("!!! User or password incorrect, please try again. Exit !!!")
    ssh_fail="Auth-Fail"
    exit()
  except paramiko.ssh_exception.SSHException:
    print("!!! Unable to SSH to the device. Exit !!!")
    ssh_fail="No-ssh"
  except paramiko.ssh_exception.NoValidConnectionsError:
    print("!!! Not SSH able !!!")
    ssh_fail="No-ssh"
  except socket.error:
    print ("!!! Device is not reachable !!!")
    ssh_fail="Dev-Down"
  file=open('D:\scripts\general-show\general-show-cap.txt', 'a')
  print >> file, ''
  print >> file, '==============================================='
  if output_str: 
       print >> file, host, ip, 'Device-Up'
       print >> file, output_str
  else:
       fail_dev = host + " " + ip + " " + ssh_fail
       print >> file, fail_dev
  file.close()
 
====================
 
Result:
 
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
C:\Users>python D:\scripts\general-show\general-show.py
Enter the TACACS Username: xxxxx
Enter the TACACS Password:
##########################################################
!!! Attempting SSH to switch01 10.1.1.1 !!!

!!! SSH successfully established !!!
switch01#term len 0
switch01#term exec prompt timestamp
switch01#show clock
Load for five secs: 1%/0%; one minute: 2%; five minutes: 2%
Time source is NTP, 09:22:49.529 AEDST Oct 24 2018
09:22:49.529 AEDST Oct 24 2018
switch01#
switch01#!
switch01#
switch01#sh ip int brief
<snip>
===============================================
switch02 10.2.2.2 Dev-Down
===============================================
switch03 10.3.3.3. Device-Up

switch03#term len 0
switch03#term exec prompt timestamp
switch03#show clock
ime source is NTP, 09:22:50.101 AEDST  Oct 24 2018
09:22:50.101 AEDST Oct 24 2018
switch03#
switch03#!
switch03#
switch03#sh ip int brief
<snip>

kumarH
Level 1
Level 1

scottledonne
Level 1
Level 1

@nemenciobeberu  Use WSL and then you can use ubuntu on your windows workstation. From that point on you should be able to keep up with and follow the videos you are watching. 


Review Cisco Networking for a $25 gift card