03-13-2019 02:25 AM
Hi,
I try to use python to backup or upload network devices (like switch,router ) IOS but failed.
The script can login to the switch but cannot download IOS.
The script is:
# -*- coding: utf-8 -*-
import pexpect
import time
import sys
def CISCO_SSH(host, user, passwd, en_passwd):
ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?'
constr = 'ssh ' + user + '@' + host
ssh = pexpect.spawn(constr)
ssh.logfile = sys.stdout
ret = ssh.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:','>'],timeout=3)
time.sleep(2)
if ret == 0:
print '1'
return
if ret == 1:
print '2'
ssh.sendline('yes')
time.sleep(1)
if ret == 2:
print '2'
ssh.sendline(passwd)
time.sleep(1)
ret = ssh.expect([pexpect.TIMEOUT,'[P|p]assword:','>'],timeout=3)
if ret == 0:
print '[-] Could not accept new key from ' + host
print ssh.before
return
if ret == 1:
print '[-] The Password is invalid!'
return
if ret == 2:
ssh.sendline('enable')
ret = ssh.expect([pexpect.TIMEOUT,'[P|p]assword:'])
if ret == 0:
print '[-]Timeout!'
if ret == 1:
ssh.sendline(en_passwd)
ret = ssh.expect([pexpect.TIMEOUT,'[P|p]assword:','#'])
if ret == 0:
print 'Error'
return
if ret == 1:
print '[-] The Prilivage Password is invalid!'
return
if ret == 2:
ssh.sendline('copy flash:/c2918-lanlitek9-mz.122-50.SE5.bin ftp://yaya:122222@192.168.1.10/test.bin')
ret = ssh.expect([pexpect.TIMEOUT,']?','#'])
if ret ==0:
print '[-]Error! Maybe the network was disconnect!'
return
while ret ==1:
ssh.sendline('\r\n')
time.sleep(2)
ret = ssh.expect([pexpect.TIMEOUT,']?','#','!'])
while ret ==3:
print 'transmiting'
time.sleep(2)
ret = ssh.expect([pexpect.TIMEOUT,']?','#','!'])
else:
print 'Done! Close SSH'
time.sleep(5)
ssh.close()
return
03-13-2019 04:36 AM
can you run a debug in the script when running it, and tell us when it errors out exactly (what line).
does this script run on other devices or is it faulty on all?
does the 'copy flash:/c2918-lanlitek9-mz.122-50.SE5.bin ftp://yaya:122222@192.168.1.10/test.bin statement run just from that devices CLI?
03-13-2019 04:54 AM
Hello,
Iave this script and woks very well for me.
#!/bin/bash
[ -n "$1" ] || exit 1
SWITCHES=$1
DIR="/backups-devices-pioneer/"
MAILTO='teste@teste.com
DATE=`date +"%Y%m%d"`
KEEP=60 # days
umask 77
cd $DIR || exit 1
mkdir -p $1
cd $1
exec > /dev/null
# Get configuration files
echo "get startup-config" | tftp $SWITCHES
# Rename files
mv -f startup-config $1-startup-config-$DATE
# Compact archive
gzip -f $1-startup-config-$DATE
#Remove file more than 60 days -
#find . -maxdepth 1 -mtime +$KEEP -exec rm -f {} \;
03-13-2019 11:12 PM
03-14-2019 01:36 AM - edited 03-14-2019 01:42 AM
Hi there,
Can I suggest that for this purpose using a library less brittle than expect! I've adjusted one of my favourite scripts (at least for answering questions on this forum!) to suit your requirement:
https://github.com/sebrupik/srupik-apic-em-tools/blob/master/frozenPony/src/oneLinerSimple.py
import getpass import csv import netmiko import paramiko from argparse import ArgumentParser COPY_CMD = "copy flash:/{0} ftp://yaya:122222@192.168.1.10/{0}" def main(): parser = ArgumentParser(description='Arguments for running oneLiner.py') parser.add_argument('-c', '--csv', required=True, action='store', help='Location of CSV file') args = parser.parse_args() ssh_username = input("SSH username: ") ssh_password = getpass.getpass('SSH Password: ') with open(args.csv, "r") as file: reader = csv.DictReader(file) for device_row in reader: try: ssh_session = netmiko.ConnectHandler(device_type='cisco_ios', ip=device_row['device_ip'], username=ssh_username, password=ssh_password) print("+++++ {0} +++++".format(device_row['device_ip'])) ssh_session.send_command(COPY_CMD.format(device_row["image_name"])) ssh_session.disconnect() except (netmiko.ssh_exception.NetMikoTimeoutException, netmiko.ssh_exception.NetMikoAuthenticationException, paramiko.ssh_exception.SSHException) as s_error: print(s_error) if __name__ == "__main__": main()
You will need to create a CSV file containing IP address and the name of the image you want to copy:
device_ip,image_name 192.168.0.1,c2918-lanlitek9-mz.122-50.SE5.bin 192.168.0.2,c2918-lanlitek9-mz.122-50.SE4.bin
You then run the script with the following arguments:
python oneLiner.py -c <name_of_csv_file>
Let me know if you encounter any issues.
cheers,
Seb.
03-14-2019 12:24 PM
Seb
I have just started using netmiko etc. to automate a few things and purely for my own information why do you import paramiko as well ie. what does it give you that netmiko doesn't.
Is it just for the exception error ?
Jon
03-14-2019 01:23 PM
@Jon Marshall good question. I was probably just adding exceptions to the except clause to catch an edge case.
netmiko only extends a small subset (two) of the paramiko exceptions class:
https://github.com/ktbyers/netmiko/blob/develop/netmiko/ssh_exception.py
...including the paramiko ssh_exception class allows the capture of a huge range of other exceptions:
https://github.com/paramiko/paramiko/blob/master/paramiko/ssh_exception.py
Arguably you could get rid of the first two netmiko class in the except statement, but it is always best practice to catch with the most specific class.
cheers,
Seb.
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