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)





1 comment:

  1. There is no part of script that logins to the jump server. What should be done for that?

    ReplyDelete