09-20-2017 06:50 PM - edited 03-01-2019 06:09 PM
Hi, I'm new to python and need help on accessing multiple switches and grab some information from the devices. I tried to run these commands but it didn't give the result that I needed - it doesn't send/execute the show commands. Notes: I can't add module like Netmiko due to the version of RHE I use to run this.
Codes:
#!/usr/bin/env python
import pexpect
import sys
print("Opening an closing the file")
ips = open("devices.txt","r")
for line in ips:
print(line)
command = pexpect.spawn ('l '+line)
command.logfile = sys.stdout
command.timeout = 10
command.expect ('H#')
command.sendline()
command.se('sh run | i snmp\r')
command.expect('snmp-server')
ips.close()
Results:
SWITCH>en
Password:
SWITCH#Traceback (most recent call last):
File "./test1.py", line 16, in ?
command.expect ('H#')
File "/usr/lib/python2.4/site-packages/pexpect.py", line 1311, in expect
return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
File "/usr/lib/python2.4/site-packages/pexpect.py", line 1325, in expect_list
return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
File "/usr/lib/python2.4/site-packages/pexpect.py", line 1409, in expect_loop
raise TIMEOUT (str(e) + '\n' + str(self))
pexpect.TIMEOUT: Timeout exceeded in read_nonblocking().
<pexpect.spawn object at 0x2afc3be44390>
version: 2.3 ($Revision: 399 $)
command: /usr/local/bin/l
args: ['/usr/local/bin/l', 'switch.local']
searcher: searcher_re:
0: re.compile("s1#")
buffer (last 100 chars): ####################################################
SWITCH>en
Password:
SWITCH#
before (last 100 chars): ####################################################
SWITCH>en
Password:
SWITCH#
after: pexpect.TIMEOUT
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 2457
child_fd: 4
closed: False
timeout: 10
delimiter: pexpect.EOF
logfile: <open file '<stdout>', mode 'w' at 0x2afc3839b198>
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
Anyone can help me why this happens and how to fix it?
Thank You.
09-20-2017 09:12 PM - edited 09-20-2017 09:20 PM
Hello,
You dont neet to mix Python with Expect, you can use Expect only. Python is useful when you can run libriries which is not your case as per your information.
Expect is supported in any Unix like distribution, is very fast and connects in device that Python dont.
Try this and let me know. Maybe some ajustment is necessary. I also attached txt file just in case.
Save file as file_name.exp and run on Linux with the command:
expect file_name.exp
Of course, you need to edit script with the device information accordingly.
#!/usr/bin/expect set router "x.x.x.x" set username "user" set password "pass" set port "22" spawn ssh -p $port $router match_max 100000000 set timeout 6 expect "(yes/no)?" { send "yes\r"; exp_continue } expect User: send -- "$username\r" expect Password: send -- "$password\r" expect > send -- "terminal lengh 0\r" send -- "sh run | i snmp\r" log_file "show_snmp.txt" send "logout\r" expect "(y/N)" send -- "n\r" expect eof
09-21-2017 08:59 PM
Hi Flavio,
thanks so much for taking time to assist me on this. You're expect solution is good but I would prefer to use Python since I'm in the middle of learning this language.
I made some changes on the script to include pexpect.TIMEOUT and once it reaches SWITCH# , it always timeout and before sending the show command. Anyone knows why???
import pexpect
import sys
import subprocess
import time
import logging
device_list = open(Devices.txt","r")
count_lines = 0
start_time = time.time()
details = open("Details.log","w")
logger = logging.getLogger("info_logger")
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler("Info.log", "w")
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(fh)
def main():
#try:
for line in device_list:
print(line)
command = pexpect.spawn ('l '+line)
#command.delaybeforesend = None
command.logfile = details
command.timeout = 60
i = command.expect(['Password:', pexpect.TIMEOUT, pexpect.EOF, 'Connection refused', 'Connection timed out', 'Connection refused by server'], timeout=60)
if i == 0:
command.expect ('SWITCH#')
command.delaybeforesend = None
command.sendline('show ver')
command.expect ('SWITCH#')
command.sendline('logout')
logger.info( '%s has been sucessfully configured', line)
print( '%s has been sucessfully configured -o_0-' % line)
sys.exit
elif i == 1:
logger.info('%s : Timeout', line)
print('%s : Timeout'% line)
sys.exit
elif i == 2:
logger.info('%s : Reached EOF', line)
print('%s : Reached EOF'% line)
...............................................
main()
=================================
SWITCH#
before (last 100 chars):
SWITCH#
after: pexpect.TIMEOUT
match: None
match_index: None
exitstatus: None
flag_eof: False
Discover and save your favorite ideas. Come back to expert answers, step-by-step guides, recent topics, and more.
New here? Get started with these tips. How to use Community New member guide