backup cisco with python 1

Backup of multiple Cisco ASA firewalls. Keep a list of the firewall IPs in a text file and loop through for each backup. Backs up to a tftp server with the hostname of the firewall.

#!/usr/bin/env python

 import pexpect
import sys
import time
def sshlogin(myuser,mypass):
        try:
                child = pexpect.spawn (myuser)
                #child.logfile_read = sys.stdout
                child.logfile_read = mybklog
                returnval = child.expect ([“Are you sure you want to continue connecting”,”ssword”,pexpect.EOF,pexpect.TIMEOUT])
                if returnval == 0:
                        #RSA key message presented for SSH
                        child.expect (“\)\?”)
                        child.sendline (“yes”)
                        child.expect (“ssword:”)
                        child.sendline (mypass)
                        return child;
                elif returnval == 1:
                        #There is no RSA key presented to SSH
                        child.expect (“ssword:”)
                        child.sendline (mypass)
                        return child;
                elif returnval == 2:
                        return -1;
                elif returnval == 3:
                        return -2
        except:
                return -3;
myfirewalls = open(“/home/network/mypython/fwbackups/myfirewalls.txt”,”r”)
mybklog = open(“/home/network/mypython/fwbackups/myfirewallbklog.txt”,”a”)
print “\n*************************” + time.strftime(“%l:%M%p %Z on %b %d, %Y”) + ” *************************\n”
mybklog.write (“\n*************************” + time.strftime(“%l:%M%p %Z on %b %d, %Y”) + ” *************************\n”)
child = sshlogin(“ssh username@x.x.x.x”,”xxxx”)
child.expect (“\]\$”)
for fw in myfirewalls:
        child.sendline (“ssh username@” + fw.rstrip())
        returnval = child.expect ([“Are you sure you want to continue connecting”,”ssword”,pexpect.EOF,pexpect.TIMEOUT])
        if returnval == 0:
              #RSA key message presented for SSH
              child.sendline (“yes”)
              child.expect (“ssword:”)
              child.sendline (“xxxx”)
        elif returnval == 1:
              #There is no RSA key presented to SSH
              child.sendline (“xxxx”)
        elif returnval == 2:
              print (“\nEOF – Cannot connect to host ” + fw.rstrip())
              mybklog.write (“\nEOF – Cannot connect to host ” + fw.rstrip())
              print (“\n———————————————–\n”)
              mybklog.write(“\n———————————————–\n”)
              child.sendcontrol(“c”)
              continue
        elif returnval == 3:
              print (“\nTIMEOUT – Cannot connect to host ” + fw.rstrip())
              mybklog.write (“\nTIMEOUT – Cannot connect to host ” + fw.rstrip())
              print (“\n———————————————–\n”)
              mybklog.write(“\n———————————————–\n”)
              child.sendcontrol(“c”)
              continue
        child.expect (“\>”)
        child.sendline (“enable”)
        child.expect (“ssword”)
        child.sendline (“xxxx”)
        child.expect (“#”)
        child.sendline (“\n”)
        child.expect (“#”)
        hostname = child.before.replace(“/”,”-“).strip()
        child.sendline (“copy running-config tftp://x.x.x.x/ConfigBackups/” + hostname + “.txt”)
        child.expect (“\?”)
        child.sendline (“\n”)
        child.expect (“\?”)
        child.sendline (“\n”)
        child.expect (“\?”)
        child.sendline (“\n”)
        child.expect (“#”)
        child.sendline (“exit”)
        print (“\nBackup done for ” + hostname + ” successfully!!!!!”)
        mybklog.write (“\nBackup done for ” + hostname + ” successfully!!!!!”)
        print (“\n———————————————–\n”)
        mybklog.write(“\n———————————————–\n”)
        continue
print “\n—End of firewall backup script execution—\n”
mybklog.write(“\n—End of firewall backup script execution—\n”)
mybklog.close()

OR

#
#This is an example of a script developed to connect and backup cisco device configs using python
#
import paramiko
import time
import os

def disable_paging(remote_conn):
”’Disable paging on a Cisco router”’

remote_conn.send(“terminal length 0\n”)
time.sleep(1)

# Clear the buffer on the screen
output = remote_conn.recv(1000)

return output

if __name__ == ‘__main__’:

# VARIABLES THAT NEED CHANGED
#ip = ‘10.18.113.16’
ipaddress = open(‘list.txt’)
username = ‘confbackup’
password = ‘SUPERepic@’

for ip in ipaddress:

# Create instance of SSHClient object
remote_conn_pre = paramiko.SSHClient()

# Automatically add untrusted hosts (make sure okay for security policy in your environment)
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# initiate SSH connection
remote_conn_pre.connect(ip, username=username, password=password)
print ‘#################################################’
print “SSH connection established to %s” % ip

# Use invoke_shell to establish an ‘interactive session’
remote_conn = remote_conn_pre.invoke_shell()
# print “Interactive SSH session established”

# Strip the initial router prompt
output = remote_conn.recv(1000)

# See what we have
#print output

# Turn off paging
disable_paging(remote_conn)

# Now let’s try to send the router a command
# remote_conn.send(“\n”)
# remote_conn.send(“show ip int brief\n”)

# These are only required if you need an enable password to login
# remote_conn.send(“en\n”)
# remote_conn.send(“cisco\n”)

remote_conn.send(“\n”)
output = remote_conn.recv(0)
#output = ”
remote_conn.send(“show run\n”)

# Wait for the command to complete
time.sleep(2)

output = remote_conn.recv(500000000)

# print output
# print output

##################
#OUTPUT GENERATED FOR FILES
###########################
mytime = time.strftime(‘%Y-%m-%d-%H-%M-%S’)
#Remove the trailing /n from varible ip this is required for file creation
ip = ip.strip(‘ \t\n\r’)
print
print ip + ‘ config backup in place’
print
#filename = ‘tas_%s.txt’ % str(ip)
#filename = os.path.join(‘RC-‘, mytime)
filename = (“RC-” + mytime)
filepath = os.path.join(‘configs’, ip, filename)

if not os.path.exists(os.path.dirname(filepath)):
os.makedirs(os.path.dirname(filepath))
with open(filepath, “w”) as f:
f.write(output)
f.close()

#disconnect
remote_conn.send("exit\n")
print "SSH connection closed to %s" % ip
print '#################################################'

assyrian technical blog