def routerLogin():
# This function prompts the user to provide their login credentials and logs into each
# of the routers before calling the buildIndex function to extract relevant portions of
# the router config.  As designed, this function actually has the capability to login to
# multiple routers simultaneously.  I chose to not allow it to multi-thread given possibility
# of undesirable results from multiple threads writing to the same index file simultaneously

    try:# Check for existence of routerFile; If exists, continue with program
        with open(routerFile, "r"): pass
        
        # Read hosts from specified file & remove duplicate entries, set protocol to SSH2
        hosts = get_hosts_from_file(routerFile,default_protocol="ssh2",remove_duplicates=True)

        if username == "":          # If username is blank
            print
            account = read_login()  # Prompt the user for login credentials

        elif password == "":        # If password is blank
            print
            account = read_login()  # Prompt the user for login credentials

        else:                       # Else use username/password from configFile
            account = Account(name=username, password=b64decode(password))
        
        # Minimal message from queue, 1 threads, redirect errors to null
        queue = Queue(verbose=0, max_threads=1, stderr=(open(os.devnull, "w")))
        queue.add_account(account)              # Use supplied user credentials
        print
        stdout.write("--> Building index...")   # Print without trailing newline
        queue.run(hosts, buildIndex)            # Create queue using provided hosts
        queue.shutdown()                        # End all running threads and close queue
        
        # If logFileDirectory does not exist, create it.
        if not path.exists(logFileDirectory): makedirs(logFileDirectory)

        # Define log filename based on date
        logFilename = logFileDirectory+"VRFSearchAndBackup_"+date+".log"

        # Check to see if logFilename currently exists.  If it does, append an
        # integer onto the end of the filename until logFilename no longer exists
        incrementLogFilename = 1
        while fileExist(logFilename):
            logFilename = logFileDirectory+"VRFSearchAndBackup_"+date+"_"+str(incrementLogFilename)+".log"
            incrementLogFilename = incrementLogFilename + 1

        # Write log results to logFile
        with open(logFilename, "w") as outputLogFile:
            try:
                outputLogFile.write(summarize(logger))

            # Exception: router file was not able to be opened
            except IOError:
                print
                print "--> An error occurred opening "+logFileDirectory+logFile+"."

    # Exception: router file could not be opened
    except IOError:
        print
        print "--> An error occurred opening "+routerFile+"."
예제 #2
0
def main():
	commands = "COMMANDS"
	filename = "switches.txt"
	file = open(filename, 'r')


	missed = []
	switches = []

	for s in file:
		switches.append(s[:-2])

	print switches
		
	#Initialize switch login credentials w/o enable pass
	account = read_login()

	#Add enable pass to login credentials
	enable_pw = getpass.getpass("Please enter the enable password: ")
	account.set_authorization_password(enable_pw)

	for x in switches:
		command_file = open(commands, 'r')
		ssh = SSH2()
		error = switch_connect(ssh, x, account, missed)
		if error:
			continue
		for line in command_file:
			ssh.execute(line)
			print ssh.response
		ssh.send('exit\r')
		ssh.close()

	print missed
예제 #3
0
def quickrun(hosts, func, **kwargs):
    """
    A wrapper around run() that creates the account by asking the user
    for entering his login information.

    @type  hosts: Host|list[Host]
    @param hosts: A list of Host objects.
    @type  func: function
    @param func: The callback function.
    @type  kwargs: dict
    @param kwargs: Passed to the Exscript.Queue constructor.
    """
    run(read_login(), hosts, func, **kwargs)
예제 #4
0
def quickrun(hosts, func, **kwargs):
    """
    A wrapper around run() that creates the account by asking the user
    for entering his login information.

    @type  hosts: Host|list[Host]
    @param hosts: A list of Host objects.
    @type  func: function
    @param func: The callback function.
    @type  kwargs: dict
    @param kwargs: Passed to the Exscript.Queue constructor.
    """
    run(read_login(), hosts, func, **kwargs)
예제 #5
0
 def render_to_file_and_deploy(self):
     username = ''
     password = ''
     try:
         username, acc, password = \
             netrc.netrc().authenticators(self._device.name)
         account = Account(name=username, password=password, key=None)
     except Exception, e:
         print e
         print("ERROR: could not find device in ~/.netrc file")
         print("HINT: either update .netrc or enter username + pass now.")
         try:
             account = read_login()
         except EOFError:
             print("ERROR: could not find proper username + pass")
             print("HINT: set username & pass in ~/.netrc for device %s"
                   % self._device.name)
             sys.exit(2)
예제 #6
0
 def render_to_file_and_deploy(self):
     username = ''
     password = ''
     try:
         username, acc, password = \
             netrc.netrc().authenticators(self._device.name)
         account = Account(name=username, password=password, key=None)
     except Exception, e:
         print e
         print("ERROR: could not find device in ~/.netrc file")
         print("HINT: either update .netrc or enter username + pass now.")
         try:
             account = read_login()
         except EOFError:
             print("ERROR: could not find proper username + pass")
             print("HINT: set username & pass in ~/.netrc for device %s"
                   % self._device.name)
             sys.exit(2)
예제 #7
0
def deploy(hostname=None, acls=None, transport='ssh', save_config=True,
           timeout=60):
    """
    Deploy code to a JunOS device
    """
    try:
        username, acc, password = \
            netrc.netrc().authenticators(hostname)
        account = Account(name=username, password=password, key=None)
    except Exception, e:
        print e
        print("ERROR: could not find device in ~/.netrc file")
        print("HINT: either update .netrc or enter username + pass now.")
        try:
            account = read_login()
        except EOFError:
            print("ERROR: could not find proper username + pass")
            print("HINT: set username & pass in ~/.netrc for device %s"
                  % hostname)
            import sys
            sys.exit(2)
#C:\Users\yasser>pip install Exscript

from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
account = read_login()
conn = SSH2()
conn.connect('192.168.1.50')
conn.login(account)
conn.execute('show ip route')
print(conn.response)
conn.send('exit\r')
conn.close()
#!/usr/bin/python
import Exscript

from Exscript.util.interact    import read_login
from Exscript.protocols        import SSH2

account = read_login()				# Prompt the user for his name and password
socket = SSH2()                     # Set connection type to SSH2
socket.connect('192.168.1.1')       # Open connection to router
socket.login(account)               # Authenticate on the remote host

socket.execute('terminal length 0') # Disable page breaks in router output
                                    # socket.autoinit() doesn't seem to disable
                                    # page breaks; Using standard command instead
socket.execute('show run')          # Send command to router
print socket.response               # Print results of command to screen

socket.send('exit\r')               # Send command to exit gracefully
                                    # socket.execute('exit') produces EOF error
socket.close()                      # Close connection

    # If backupDirectory does not contain trailing backslash, append one
    if backupDirectory != "":
        if backupDirectory[-1:] != "\\": backupDirectory = backupDirectory+"\\"

    # Error checking for verboseOutput & maxThreads
    if int(verboseOutput) not in range(0,5):    verboseOutput = 1
    if int(maxThreads) not in range(1,100):     maxThreads = 2

    if fileExist(routerFile):
        # Define "date" variable for use in the output filename
        date = datetime.now()           # Determine today's date
        date = date.strftime("%Y%m%d")  # Format date as YYYYMMDD
    
        if username == "":              # If username is blank
            print
            account = read_login()      # Prompt the user for login credentials

        elif password == "":            # If password is blank
            print
            account = read_login()      # Prompt the user for login credentials

        else:                           # Else use username/password from configFile
            account = Account(name=username, password=b64decode(password))
    
        # Read hosts from specified file & remove duplicate entries, set protocol to SSH2
        hosts = get_hosts_from_file(routerFile, default_protocol="ssh2", remove_duplicates=True)
        
        print
        
        # Verbose & # threads taken from configFile, redirect errors to null
        queue = Queue(verbose=int(verboseOutput), max_threads=int(maxThreads), stderr=(open(os.devnull, "w")))
예제 #11
0
def deploy(hostname=None, acls=None, transport='ssh', save_config=False,
           timeout=60):
    """
    Deploy code in a safe way o a Cisco NX-OS device.
    """
    try:
        username, enable_pass, password = \
            netrc.netrc().authenticators(hostname)
        account = Account(name=username, password=password,
                          password2=enable_pass)
    except:
        print("ERROR: could not find device in ~/.netrc file")
        print("HINT: either update .netrc or enter username + pass now.")
        try:
            account = read_login()
        except EOFError:
            print("ERROR: could not find proper username + pass")
            print("HINT: set username & pass in ~/.netrc for device %s"
                  % hostname)
            import sys
            sys.exit(2)

    def s(conn, line):
        print("   %s" % line)
        conn.execute(line)

    def collect_interfaces(conn):
        template = """# textfsm
Value Required Interface ([^ ]+)
Value Inbound (.*)
Value Outbound (.*)

Start
  ^${Interface} is up
  ^  Outgoing access list is ${Outbound}
  ^  Inbound  access list is ${Inbound} -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        s(conn, 'show ip int | inc ine pro|list is')
        interface_acl_v4 = table.ParseText(conn.response)

        template = """# textfsm
Value Required Interface ([^ ]+)
Value Inbound (.*)
Value Outbound (.*)

Start
  ^${Interface} is up
  ^  Inbound access list ${Inbound}
  ^  Outgoing access list ${Outbound} -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        s(conn, 'show ipv6 int  | i ine pro|access list')
        interface_acl_v6 = table.ParseText(conn.response)
        template = """# textfsm
Value Required Vty (\d+\s\d+)
Value Inbound4 ([^ ]+)
Value Outbound4 ([^ ]+)
Value Inbound6 ([^ ]+)
Value Outbound6 ([^ ]+)

Start
  ^line vty ${Vty}
  ^ access-class ${Inbound4} in
  ^ access-class ${Outbound4} out
  ^ ipv6 access-class ${Inbound6} in
  ^ ipv6 access-class ${Outbound6} out -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        s(conn, 'show run | begin ^line vty')
        interface_acl_vty = table.ParseText(conn.response)

        results = {4: interface_acl_v4, 6: interface_acl_v6}
        # add vty lines
        for vty in interface_acl_vty:
            # v4 inbound
            v4_inbound = vty[1] if vty[1] else "not set"
            v4_outbound = vty[2] if vty[1] else "not set"
            v6_inbound = vty[3] if vty[1] else "not set"
            v6_outbound = vty[4] if vty[1] else "not set"
            results[4].append(["vty %s" % vty[0], v4_inbound, v4_outbound])
            results[6].append(["vty %s" % vty[0], v6_inbound, v6_outbound])
        return results

    # main flow of the program starts here
    if transport == 'ssh':
        conn = SSH2(verify_fingerprint=False, debug=0, timeout=timeout)
    elif transport == 'telnet':
        conn = Telnet(debug=0)
    else:
        print("ERROR: Unknown transport mechanism: %s"
              % transport)
        sys.exit(2)
    conn.set_driver('nxos')
    conn.connect(hostname)
    conn.login(account)
    conn.execute('terminal length 0')
    conn.auto_app_authorize(account)
    capabilities = {}
    s(conn, "show ipv6 cef")
    capabilities['ipv6'] = False if "%IPv6 CEF not running" in conn.response else True
    if capabilities['ipv6']:
        print("INFO: IPv6 support detected")
    else:
        print("INFO: NO IPv6 support detected, skipping IPv6 ACLs")
    # map into structure:
    # policyname { (int, afi, direction) }
    map_pol_int = {}
    interfaces_overview = collect_interfaces(conn)
    for afi in interfaces_overview:
        for interface, inbound, outbound in interfaces_overview[afi]:
            # add inbound rules to map
            if inbound not in map_pol_int.keys():
                map_pol_int[inbound] = [{"int": interface,
                                        "afi": afi,
                                        "dir": "in"}]
            else:
                map_pol_int[inbound].append({"int": interface,
                                             "afi": afi,
                                             "dir": "in"})
            # add outbound
            if outbound not in map_pol_int.keys():
                map_pol_int[outbound] = [{"int": interface,
                                          "afi": afi,
                                          "dir": "in"}]
            else:
                map_pol_int[outbound].append({"int": interface,
                                             "afi": afi,
                                             "dir": "out"})
    print("INFO: interface / policy mapping:")
    pprint(map_pol_int)

    def lock_step(lock, pol, capabilities):
        name = acls[pol]['name']
        afi = acls[pol]['afi']
        if afi == 6 and not capabilities['ipv6']:
            return
        policy = acls[pol]['policy']
        print("INFO: uploading name: %s, afi: %s" % (name, afi))
        s(conn, 'configure session aclhound')
        if afi == 4:
            try:
                s(conn, "no ip access-list %s%s" % (lock, name))
            except:
                pass
            s(conn, "ip access-list %s%s" % (lock, name))
            for line in policy.split('\n'):
                s(conn, line)
        if afi == 6:
            try:
                s(conn, "no ipv6 access-list %s%s" % (lock, name))
            except:
                pass
            s(conn, "ipv6 access-list %s%s" % (lock, name))
            for line in policy.split('\n'):
                s(conn, line)
        s(conn, "commit")


    for policy in acls:
            lock_step("", policy, capabilities)

    if save_config == True:
        s(conn, "copy running-config startup-config")
예제 #12
0
#!/opt/local/bin/python
import hashlib
import Exscript

from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

account = read_login()  # Prompt the user for his name and password
conn = SSH2()  # We choose to use SSH2
conn.connect('192.168.16.1')  # Open the SSH connection
conn.login(account)  # Authenticate on the remote host
conn.execute('conf t')  # Execute the "uname -a" command
conn.execute('interface Fastethernet 0/8')
conn.execute('Description Test*')
conn.execute('no shutdown')
conn.execute('end')
conn.execute('sh run int Fastethernet0/8')
print conn.response
예제 #13
0
def deploy(hostname=None, acls=None, transport='ssh', save_config=False):
    """
    Deploy code in a safe way o a Cisco IOS device.
    """

    try:
        username, enable_pass, password = \
            netrc.netrc().authenticators(hostname)
        account = Account(name=username, password=password,
                          password2=enable_pass)
    except:
        account = read_login()

    def s(conn, line):
        print("   %s" % line)
        conn.execute(line)

    def collect_interfaces(conn):
        template = """# textfsm
Value Required Aclname ([^ ]+)
Value Required Direction ([^ ]+)
Value Required Interface (.*)

Start
  ^access-group ${Aclname} ${Direction} interface ${Interface} -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        conn.execute('show run | include ^access-group')
        map_acl_int = {}
        for aclname, direction, interface in table.ParseText(conn.response):
            if aclname in map_acl_int.keys():
                map_acl_int[aclname].append({"dir": direction,
                                             "int": interface})
            else:
                map_acl_int[aclname] = [{"dir": direction, "int": interface}]

        return map_acl_int

    # main flow of the program starts here
    if transport == 'ssh':
        conn = SSH2(verify_fingerprint=False, debug=0)
    elif transport == 'telnet':
        conn = Telnet(debug=0)
    else:
        print("ERROR: Unknown transport mechanism: %s" %
              transport)
        sys.exit(2)
    conn.set_driver('ios')
    conn.connect(hostname)
    try:
        conn.login(account)
    except LoginFailure:
        print("ERROR: Username or Password incorrect for %s" % hostname)
        print("HINT: verify authentication details in your .netrc file")
        sys.exit(2)
    s(conn, "terminal pager 0")

    map_pol_int = collect_interfaces(conn)
    pprint(map_pol_int)

    def lock_step(lock, pol):
        name = acls[pol]['name']
        afi = acls[pol]['afi']
        policy = acls[pol]['policy']
        print("INFO: uploading name: %s, afi: %s" % (name, afi))
        s(conn, 'configure terminal')
        if afi == 4:
            try:
                s(conn, "clear configure access-list %s%s" % (lock, name))
            except:
                pass
            for line in policy.split('\n'):
                if lock:
                    line = line.replace("access-list %s " % name,
                                        "access-list %s%s " % (lock, name))
                s(conn, line)
        if afi == 6:
            try:
                s(conn, "clear configure ipv6 access-list %s%s" % (lock, name))
            except:
                pass
            for line in policy.split('\n'):
                if lock:
                    line = line.replace("access-list %s " % name,
                                        "access-list %s%s " % (lock, name))
                s(conn, line)
        s(conn, "end")

        # then replace ACL on all interfaces / VTYs
        if name in map_pol_int:
            for entry in map_pol_int[name]:
                print("INFO: lockstepping policy %s afi %s" % (name, afi))
                s(conn, "configure terminal")
                s(conn, "access-group %s%s %s interface %s"
                  % (lock, name, entry['dir'], entry['int']))
                s(conn, "end")

    for policy in acls:
        for lock in ["LOCKSTEP-", ""]:
            lock_step(lock, policy)
        # cleanup
        s(conn, "configure terminal")
        if acls[policy]['afi'] == 4:
            s(conn, "clear configure access-list LOCKSTEP-%s"
              % acls[policy]['name'])
        if acls[policy]['afi'] == 6:
            s(conn, "clear configure ipv6 access-list LOCKSTEP-%s"
              % acls[policy]['name'])
        s(conn, "end")
    if save_config == True:
        s(conn, "write")
예제 #14
0
def deploy(hostname=None, acls=None, transport='ssh', save_config=False):
    """
    Deploy code in a safe way o a Cisco IOS device.
    """

    try:
        username, enable_pass, password = \
            netrc.netrc().authenticators(hostname)
        account = Account(name=username, password=password,
                          password2=enable_pass)
    except:
        account = read_login()

    def s(conn, line):
        print("   %s" % line)
        conn.execute(line)

    def collect_interfaces(conn):
        template = """# textfsm
Value Required Aclname ([^ ]+)
Value Required Direction ([^ ]+)
Value Required Interface (.*)

Start
  ^access-group ${Aclname} ${Direction} interface ${Interface} -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        conn.execute('show run | include ^access-group')
        map_acl_int = {}
        for aclname, direction, interface in table.ParseText(conn.response):
            if aclname in map_acl_int.keys():
                map_acl_int[aclname].append({"dir": direction,
                                             "int": interface})
            else:
                map_acl_int[aclname] = [{"dir": direction, "int": interface}]

        return map_acl_int

    # main flow of the program starts here
    if transport == 'ssh':
        conn = SSH2(verify_fingerprint=False, debug=0)
    elif transport == 'telnet':
        conn = Telnet(debug=0)
    else:
        print("ERROR: Unknown transport mechanism: %s" %
              transport)
        sys.exit(2)
    conn.set_driver('ios')
    conn.connect(hostname)
    try:
        conn.login(account)
    except LoginFailure:
        print("ERROR: Username or Password incorrect for %s" % hostname)
        print("HINT: verify authentication details in your .netrc file")
        sys.exit(2)
    s(conn, "terminal pager 0")

    map_pol_int = collect_interfaces(conn)
    pprint(map_pol_int)

    def lock_step(lock, pol):
        name = acls[pol]['name']
        afi = acls[pol]['afi']
        policy = acls[pol]['policy']
        print("INFO: uploading name: %s, afi: %s" % (name, afi))
        s(conn, 'configure terminal')
        if afi == 4:
            try:
                s(conn, "clear configure access-list %s%s" % (lock, name))
            except:
                pass
            for line in policy.split('\n'):
                if lock:
                    line = line.replace("access-list %s " % name,
                                        "access-list %s%s " % (lock, name))
                s(conn, line)
        if afi == 6:
            try:
                s(conn, "clear configure ipv6 access-list %s%s" % (lock, name))
            except:
                pass
            for line in policy.split('\n'):
                if lock:
                    line = line.replace("access-list %s " % name,
                                        "access-list %s%s " % (lock, name))
                s(conn, line)
        s(conn, "end")

        # then replace ACL on all interfaces / VTYs
        if name in map_pol_int:
            for entry in map_pol_int[name]:
                print("INFO: lockstepping policy %s afi %s" % (name, afi))
                s(conn, "configure terminal")
                s(conn, "access-group %s%s %s interface %s"
                  % (lock, name, entry['dir'], entry['int']))
                s(conn, "end")

    for policy in acls:
        for lock in ["LOCKSTEP-", ""]:
            lock_step(lock, policy)
        # cleanup
        s(conn, "configure terminal")
        if acls[policy]['afi'] == 4:
            s(conn, "clear configure access-list LOCKSTEP-%s"
              % acls[policy]['name'])
        if acls[policy]['afi'] == 6:
            s(conn, "clear configure ipv6 access-list LOCKSTEP-%s"
              % acls[policy]['name'])
        s(conn, "end")
    if save_config == True:
        s(conn, "write")
예제 #15
0
def deploy(hostname=None, acls=None, transport='ssh', save_config=False,
           timeout=60):
    """
    Deploy code in a safe way o a Cisco IOS device.
    """
    try:
        username, enable_pass, password = \
            netrc.netrc().authenticators(hostname)
        account = Account(name=username, password=password,
                          password2=enable_pass)
    except:
        print("ERROR: could not find device in ~/.netrc file")
        print("HINT: either update .netrc or enter username + pass now.")
        try:
            account = read_login()
        except EOFError:
            print("ERROR: could not find proper username + pass")
            print("HINT: set username & pass in ~/.netrc for device %s"
                  % hostname)
            import sys
            sys.exit(2)

    def s(conn, line):
        print("   %s" % line)
        conn.execute(line)

    def collect_interfaces(conn):
        template = """# textfsm
Value Required Interface ([^ ]+)
Value Inbound (.*)
Value Outbound (.*)

Start
  ^${Interface} is up
  ^  Outgoing access list is ${Outbound}
  ^  Inbound  access list is ${Inbound} -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        s(conn, 'show ip int | inc ine pro|list is')
        interface_acl_v4 = table.ParseText(conn.response)

        template = """# textfsm
Value Required Interface ([^ ]+)
Value Inbound (.*)
Value Outbound (.*)

Start
  ^${Interface} is up
  ^  Inbound access list ${Inbound}
  ^  Outgoing access list ${Outbound} -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        s(conn, 'show ipv6 int  | i ine pro|access list')
        interface_acl_v6 = table.ParseText(conn.response)
        template = """# textfsm
Value Required Vty (\d+\s\d+)
Value Inbound4 ([^ ]+)
Value Outbound4 ([^ ]+)
Value Inbound6 ([^ ]+)
Value Outbound6 ([^ ]+)

Start
  ^line vty ${Vty}
  ^ access-class ${Inbound4} in
  ^ access-class ${Outbound4} out
  ^ ipv6 access-class ${Inbound6} in
  ^ ipv6 access-class ${Outbound6} out -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        s(conn, 'show run | begin ^line vty')
        interface_acl_vty = table.ParseText(conn.response)

        results = {4: interface_acl_v4, 6: interface_acl_v6}
        # add vty lines
        for vty in interface_acl_vty:
            # v4 inbound
            v4_inbound = vty[1] if vty[1] else "not set"
            v4_outbound = vty[2] if vty[1] else "not set"
            v6_inbound = vty[3] if vty[1] else "not set"
            v6_outbound = vty[4] if vty[1] else "not set"
            results[4].append(["vty %s" % vty[0], v4_inbound, v4_outbound])
            results[6].append(["vty %s" % vty[0], v6_inbound, v6_outbound])
        return results

    # main flow of the program starts here
    if transport == 'ssh':
        conn = SSH2(verify_fingerprint=False, debug=0, timeout=timeout)
    elif transport == 'telnet':
        conn = Telnet(debug=0)
    else:
        print("ERROR: Unknown transport mechanism: %s"
              % transport)
        sys.exit(2)
    conn.set_driver('ios')
    conn.connect(hostname)
    conn.login(account)
    conn.execute('terminal length 0')
    conn.auto_app_authorize(account)
    capabilities = {}
    s(conn, "show ipv6 cef")
    capabilities['ipv6'] = False if "%IPv6 CEF not running" in conn.response else True
    if capabilities['ipv6']:
        print("INFO: IPv6 support detected")
    else:
        print("INFO: NO IPv6 support detected, skipping IPv6 ACLs")
    # map into structure:
    # policyname { (int, afi, direction) }
    map_pol_int = {}
    interfaces_overview = collect_interfaces(conn)
    for afi in interfaces_overview:
        for interface, inbound, outbound in interfaces_overview[afi]:
            # add inbound rules to map
            if inbound not in map_pol_int.keys():
                map_pol_int[inbound] = [{"int": interface,
                                        "afi": afi,
                                        "dir": "in"}]
            else:
                map_pol_int[inbound].append({"int": interface,
                                             "afi": afi,
                                             "dir": "in"})
            # add outbound
            if outbound not in map_pol_int.keys():
                map_pol_int[outbound] = [{"int": interface,
                                          "afi": afi,
                                          "dir": "in"}]
            else:
                map_pol_int[outbound].append({"int": interface,
                                             "afi": afi,
                                             "dir": "out"})
    print("INFO: interface / policy mapping:")
    pprint(map_pol_int)

    def lock_step(lock, pol, capabilities):
        name = acls[pol]['name']
        afi = acls[pol]['afi']
        if afi == 6 and not capabilities['ipv6']:
            return
        policy = acls[pol]['policy']
        print("INFO: uploading name: %s, afi: %s" % (name, afi))
        s(conn, 'configure terminal')
        if afi == 4:
            try:
                s(conn, "no ip access-list extended %s%s" % (lock, name))
            except:
                pass
            s(conn, "ip access-list extended %s%s" % (lock, name))
            for line in policy.split('\n'):
                s(conn, line)
        if afi == 6:
            try:
                s(conn, "no ipv6 access-list %s%s" % (lock, name))
            except:
                pass
            s(conn, "ipv6 access-list %s%s" % (lock, name))
            for line in policy.split('\n'):
                s(conn, line)
        s(conn, "end")

        # then replace ACL on all interfaces / VTYs
        if name in map_pol_int:
            for entry in map_pol_int[name]:
                if not entry['afi'] == afi:
                    continue
                print("INFO: lockstepping policy %s afi %s" % (name, afi))
                s(conn, "configure terminal")
                if entry['int'].startswith('vty '):
                    s(conn, "line %s" % entry['int'])
                    if afi == 4:
                        s(conn, "access-class %s%s %s"
                          % (lock, name, entry['dir']))
                    if afi == 6:
                        s(conn, "ipv6 access-class %s%s %s"
                          % (lock, name, entry['dir']))
                else:
                    s(conn, "interface %s" % entry['int'])
                    if afi == 4:
                        s(conn, "ip access-group %s%s %s"
                          % (lock, name, entry['dir']))
                    if afi == 6:
                        s(conn, "ipv6 traffic-filter %s%s %s"
                          % (lock, name, entry['dir']))
                s(conn, "end")

    for policy in acls:
        for lock in ["LOCKSTEP-", ""]:
            lock_step(lock, policy, capabilities)
        # cleanup
        s(conn, "configure terminal")
        if acls[policy]['afi'] == 4:
            s(conn, "no ip access-list extended LOCKSTEP-%s"
              % acls[policy]['name'])
        if acls[policy]['afi'] == 6 and capabilities['ipv6']:
            s(conn, "no ipv6 access-list LOCKSTEP-%s"
              % acls[policy]['name'])
        s(conn, "end")

    if save_config == True:
        s(conn, "write")
예제 #16
0
print "*  NWFCU - Authorized users only                            *"
print "*                         	   				  *"
print "* " + e + "  						  *"
print "*******************************************************************"
print "PortSecurity"
print
print
print '''
Refer to the emails generated for the below information.
Failure to do may cause routing issues within the environment

'''

print "*******************************************************************"
print "*******************************************************************"
accountcore = read_login()
print

userhostname = raw_input("Enter Hostname: ")
usermac = raw_input("Enter MAC address: ")
userinterface = raw_input("Enter Interface: ")
time.sleep(4)
os.system('clear')
print
print "*******************************************************************"
print "*******************************************************************"


def portsecurityaddresschecker(hostname, violationMAC):
    try:
        #print hostname
예제 #17
0
			serial = optic.find('{0}serial-number'.format(namespace)).text
			description = optic.find('{0}description'.format(namespace)).text
			pic = optic.getparent().find('{0}name'.format(namespace)).text
			mic = optic.getparent().getparent().find('{0}name'.format(namespace)).text
			fpc = optic.getparent().getparent().getparent().find('{0}name'.format(namespace)).text
			intf = fpc.split(" ")[1]+"/"+ pic.split(" ")[1] +"/"+name.split(" ")[1]
			
			f.write(description + "\t\t\t" + intf + "\t\t\t" + "Serial: " + serial +  "\n")
		

		f.close()


# Read input data.
#accounts = get_accounts_from_file('accounts.cfg')
accounts = read_login()
try:
	hosts    = get_hosts_from_file('hostlist.txt')
except:
	print """
Devi creare un file che si chiama hostlist.txt e dentro
ci sono linee di questo tipo:

ssh://r.rm2.garr.net
"""
	sys.exit(0)
# Run do_something on each of the hosts. The given accounts are used
# round-robin. "verbose = 0" instructs the queue to not generate any
# output on stdout.
queue = Queue(verbose = 3, max_threads = 5)
def backupVRF(vrfName, localPeer):
# This function takes the VRF Name and Local Peer IP as determined during
# the searchIndex() function, retrieves all matching VRFs from their respective
# routers and writes the config to a file.

    # If backupDirectory does not exist, create it
    if not path.exists(backupDirectory): makedirs(backupDirectory)

    # Define output filename based on hostname and date
    outputFilename = backupDirectory+vrfName+"_Config_"+date+".txt"
    
    # Check to see if outputFilename currently exists.  If it does, append an
    # integer onto the end of the filename until outputFilename no longer exists
    incrementFilename = 1
    while fileExist(outputFilename):
        outputFilename = backupDirectory+vrfName+"_Config_"+date+"_"+str(incrementFilename)+".txt"
        incrementFilename = incrementFilename + 1
    
    with open(outputFilename, "w") as outputFile:
        try:
            if username == "":          # If username is blank
                print
                account = read_login()  # Prompt the user for login credentials
            
            elif password == "":        # If password is blank
                print
                account = read_login()  # Prompt the user for login credentials
        
            else:                       # Else use username/password from configFile
                # base64 decode password from the config file
                account = Account(name=username, password=b64decode(password))
                
            print
            print "--> Logging into "+localPeer+"..."
            
            socket = SSH2()             # Set connection type to SSH2
            socket.connect(localPeer)   # Open connection to router
            socket.login(account)       # Authenticate on the remote host
            
            print "--> Backing up "+vrfName+"..."
            
            socket.execute("terminal length 0") # Disable page breaks in router output
                                                # socket.autoinit() doesn't seem to disable
                                                # page breaks; Using standard command instead
            # Send command to router to retrieve first part of VRF configuration
            socket.execute("show running-config | section "+vrfName)

            outputFile.write(socket.response)    # Write contents of running config to output file
            
            # Use REGEX to locate Route Distinguisher in results from router
            routeDistinguisher = search(r"\srd\s\b[0-9]{0,4}\b:0", socket.response).group(0)
            # Use REGEX to remove everything but the actual Route Distinguisher number.
            routeDistinguisher = sub(r"\srd\s", "", routeDistinguisher)
            routeDistinguisher = sub(r":0", "", routeDistinguisher)
            
            # Send command to router to retrieve second part of VRF configuration
            socket.execute("show running-config | section SMVPN "+routeDistinguisher+" ")
            outputFile.write(socket.response)   # Write contents of running config to output file
        
            socket.send("exit\r")   # Send the "exit" command to log out of router gracefully
            socket.close()          # Close SSH connection

        # Exception: outputFile file could not be opened
        except IOError:
            print
            print "--> An error occurred opening "+outputFile+"."    

    print "--> "+vrfName+" backed up to "+outputFilename+"."
예제 #19
0
print "Login Method"
print "============"
print "1.Telnet"
print "2.SSHv2"
print
Connection_Type = raw_input('Connection Type :')
print
print
Device_IP = raw_input('IP Address :')

conn = None

if Connection_Type == '1':
	enable_pass = raw_input('Enable Password :'******'enable')
	conn.execute(enable_pass)
	
elif Connection_Type == '2':
	conn = SSH2()
	account = read_login()            
	conn.connect(Switch_IP)     
	conn.login(account)                 



conn.execute('term len 0')
conn.execute('term width 0')
예제 #20
0
          if len(line) > 0:
             cmds.append(line)
             prompt = moreprompt
          else:
             getmore = False
       return cmds

    # Does a check to see if the script recieved a value from
    # the args.  If it did not, then it runs the commands
    # to get the values from the command line.
    # ----------------------------------------------------------:
    try:
        if not ip_addr:
            ip_addr=raw_input('Please enter the device management IP address: ')
        if not user:
            accnt=read_login()
            if en:
                enablepassw = getpass.getpass(prompt='Enter your enable password: '******'Enter your password: '******'Enter your enable password: '******'Please enter the commands (no quotes!) you wish to execute. Enter blank line to exit.\n ')

    # Used to split the list of IP addresses and set the response to None.
    # ----------------------------------------------------------
        ip_addrs = ip_addr.replace(',', '\n').split('\n')
        resp = ""

    # Actions performed on each device specified in the ip_addr