cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
1861
Views
15
Helpful
6
Replies
Highlighted
Beginner

use python to backup switch IOS issue

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

 

 

6 REPLIES 6
Highlighted
VIP Advisor

Re: use python to backup switch IOS issue

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?

Please remember to rate useful posts, by clicking on the stars below.

Highlighted
VIP Collaborator

Re: use python to backup switch IOS issue

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 {} \;

Jaderson Pessoa
*** Rate All Helpful Responses ***
Highlighted
Hall of Fame Community Legend

Re: use python to backup switch IOS issue

Wouldn't it be a lot easier if one would just go to the Cisco website and download the IOS instead?
Highlighted
VIP Advisor

Re: use python to backup switch IOS issue

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.

Highlighted
Hall of Fame Guru

Re: use python to backup switch IOS issue

 

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

Highlighted
VIP Advisor

Re: use python to backup switch IOS issue

@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.