Initial Query

Give me code that collects a Cisco IOS or NXOS device information and configuration, including things like current privilege level, running configuration, LLDP and CDP neighbors

LLM Generation

Query

Give me code that collects a Cisco IOS or NXOS device information and configuration, including things like current privilege level, running configuration, LLDP and CDP neighbors

Output

Here's a Python script that uses the Netmiko library to collect various information from a Cisco IOS or NX-OS device:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
from netmiko import ConnectHandler
from datetime import datetime
import sys
import re

def connect_to_device(device_info):
    """Establish connection to the device"""
    try:
        connection = ConnectHandler(**device_info)
        return connection
    except Exception as e:
        print(f"Failed to connect to device: {str(e)}")
        sys.exit(1)

def get_device_info(connection):
    """Collect various device information"""
    device_info = {}
    
    # Get current privilege level
    priv = connection.send_command("show privilege")
    device_info['privilege_level'] = re.search(r"Current privilege level is (\d+)", priv).group(1)
    
    # Get device version
    version = connection.send_command("show version")
    device_info['version'] = version
    
    # Get hostname
    hostname = connection.send_command("show running-config | include hostname")
    device_info['hostname'] = hostname.replace("hostname ", "").strip()
    
    return device_info

def get_running_config(connection):
    """Get running configuration"""
    return connection.send_command("show running-config")

def get_cdp_neighbors(connection):
    """Get CDP neighbors"""
    return connection.send_command("show cdp neighbors detail")

def get_lldp_neighbors(connection):
    """Get LLDP neighbors"""
    return connection.send_command("show lldp neighbors detail")

def save_output(filename, content):
    """Save output to file"""
    with open(filename, 'w') as f:
        f.write(content)

def main():
    # Device connection parameters
    device = {
        'device_type': 'cisco_ios',  # or 'cisco_nxos' for Nexus
        'host': '192.168.1.1',  # Replace with your device IP
        'username': 'your_username',
        'password': 'your_password',
        'secret': 'your_enable_secret',  # if needed
    }

    # Connect to device
    print("Connecting to device...")
    connection = connect_to_device(device)
    
    # Enable mode if needed
    if not connection.check_enable_mode():
        connection.enable()

    # Create timestamp for filenames
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    try:
        # Collect device information
        print("Collecting device information...")
        device_info = get_device_info(connection)
        
        # Get running configuration
        print("Collecting running configuration...")
        running_config = get_running_config(connection)
        
        # Get CDP neighbors
        print("Collecting CDP neighbors...")
        cdp_neighbors = get_cdp_neighbors(connection)
        
        # Get LLDP neighbors
        print("Collecting LLDP neighbors...")
        lldp_neighbors = get_lldp_neighbors(connection)

        # Save all information to files
        hostname = device_info['hostname']
        
        # Save device info
        device_info_output = "\n".join([f"{k}: {v}" for k, v in device_info.items()])
        save_output(f"{hostname}_{timestamp}_device_info.txt", device_info_output)
        
        # Save running config
        save_output(f"{hostname}_{timestamp}_running_config.txt", running_config)
        
        # Save CDP neighbors
        save_output(f"{hostname}_{timestamp}_cdp_neighbors.txt", cdp_neighbors)
        
        # Save LLDP neighbors
        save_output(f"{hostname}_{timestamp}_lldp_neighbors.txt", lldp_neighbors)

        print("\nCollection completed successfully!")
        print(f"Files have been saved with prefix: {hostname}_{timestamp}")

    except Exception as e:
        print(f"An error occurred: {str(e)}")

    finally:
        # Disconnect from device
        connection.disconnect()
        print("Disconnected from device")

if __name__ == "__main__":
    main()
To use this script: 1. First, install the required library:
1
pip install netmiko
2. Modify the device connection parameters in the `main()` function:
1
2
3
4
5
6
7
device = {
    'device_type': 'cisco_ios',  # or 'cisco_nxos' for Nexus
    'host': '192.168.1.1',  # Replace with your device IP
    'username': 'your_username',
    'password': 'your_password',
    'secret': 'your_enable_secret',  # if needed
}
This script will: 1. Connect to the specified Cisco device 2. Collect various information including: - Current privilege level - Device version - Hostname - Running configuration - CDP neighbors - LLDP neighbors 3. Save all information to separate files with timestamps 4. Handle errors and ensure proper disconnection The output files will be named using this format: - `{hostname}_{timestamp}_device_info.txt` - `{hostname}_{timestamp}_running_config.txt` - `{hostname}_{timestamp}_cdp_neighbors.txt` - `{hostname}_{timestamp}_lldp_neighbors.txt` Additional features you might want to add: 1. Command-line arguments for device parameters 2. Support for multiple devices 3. Additional show commands 4. Error handling for specific command failures 5. Support for different authentication methods (SSH key, etc.) 6. Output formatting options 7. Logging functionality Remember to handle the credentials securely in a production environment (don't hardcode them in the script). You can also add more commands to collect additional information by creating new functions similar to the existing ones and adding them to the main collection routine.

Check if all of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show version: True

Check if any of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show lldp neighbors detail: True

Substring Evaluation

Testing if the previous output contains the string show lldp neighbors: True

Final Answer: True

Check if any of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show cdp neighbors detail: True

Substring Evaluation

Testing if the previous output contains the string show cdp neighbors: True

Final Answer: True

Substring Evaluation

Testing if the previous output contains the string show run: True

Substring Evaluation

Testing if the previous output contains the string show privilege: True

Final Answer: True

Initial Query

Give me code that collects a Cisco IOS or NXOS device information and configuration, including things like current privilege level, running configuration, LLDP and CDP neighbors

LLM Generation

Query

Give me code that collects a Cisco IOS or NXOS device information and configuration, including things like current privilege level, running configuration, LLDP and CDP neighbors

Output

Here's a Python script using the `netmiko` library to collect various information from a Cisco IOS or NX-OS device:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
from netmiko import ConnectHandler
from datetime import datetime
import sys
import re
import time

def connect_to_device(device_info):
    """Establish connection to the device"""
    try:
        connection = ConnectHandler(**device_info)
        return connection
    except Exception as e:
        print(f"Failed to connect to device: {str(e)}")
        sys.exit(1)

def get_device_info(connection):
    """Collect various device information"""
    device_info = {}
    
    # Get current privilege level
    priv_level = connection.send_command("show privilege")
    device_info['privilege_level'] = priv_level.strip()
    
    # Get device version
    version = connection.send_command("show version")
    device_info['version'] = version
    
    # Get hostname
    hostname = connection.send_command("show running-config | include hostname")
    device_info['hostname'] = hostname.strip()
    
    # Get running configuration
    running_config = connection.send_command("show running-config")
    device_info['running_config'] = running_config
    
    # Get CDP neighbors
    cdp_neighbors = connection.send_command("show cdp neighbors detail")
    device_info['cdp_neighbors'] = cdp_neighbors
    
    # Get LLDP neighbors (if supported)
    try:
        lldp_neighbors = connection.send_command("show lldp neighbors detail")
        device_info['lldp_neighbors'] = lldp_neighbors
    except:
        device_info['lldp_neighbors'] = "LLDP not supported or enabled"
    
    # Get interfaces status
    interfaces = connection.send_command("show interfaces")
    device_info['interfaces'] = interfaces
    
    # Get IP interfaces
    ip_int = connection.send_command("show ip interface brief")
    device_info['ip_interfaces'] = ip_int
    
    return device_info

def save_output(device_info, hostname):
    """Save the collected information to files"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    
    # Create main output file
    with open(f"{hostname}_{timestamp}_device_info.txt", "w") as f:
        f.write("=== Device Information Collection ===\n")
        f.write(f"Collection Time: {timestamp}\n\n")
        
        f.write("=== Privilege Level ===\n")
        f.write(device_info['privilege_level'] + "\n\n")
        
        f.write("=== Device Version ===\n")
        f.write(device_info['version'] + "\n\n")
        
        f.write("=== Hostname ===\n")
        f.write(device_info['hostname'] + "\n\n")
        
        f.write("=== IP Interfaces ===\n")
        f.write(device_info['ip_interfaces'] + "\n\n")
        
        f.write("=== CDP Neighbors ===\n")
        f.write(device_info['cdp_neighbors'] + "\n\n")
        
        f.write("=== LLDP Neighbors ===\n")
        f.write(device_info['lldp_neighbors'] + "\n\n")
        
        f.write("=== Interfaces Status ===\n")
        f.write(device_info['interfaces'] + "\n\n")
    
    # Save running config to separate file
    with open(f"{hostname}_{timestamp}_running_config.txt", "w") as f:
        f.write(device_info['running_config'])

def main():
    # Device connection parameters
    device = {
        'device_type': 'cisco_ios',  # or 'cisco_nxos' for Nexus
        'host': 'device_ip_address',
        'username': 'your_username',
        'password': 'your_password',
        'secret': 'enable_secret',  # if needed
    }
    
    # Connect to device
    print("Connecting to device...")
    connection = connect_to_device(device)
    
    # Enter enable mode if needed
    if connection.check_enable_mode() is False:
        connection.enable()
    
    # Get device information
    print("Collecting device information...")
    device_info = get_device_info(connection)
    
    # Extract hostname from device info
    hostname = re.search(r'hostname (.+)', device_info['hostname'])
    hostname = hostname.group(1) if hostname else 'unknown_device'
    
    # Save information to files
    print("Saving information to files...")
    save_output(device_info, hostname)
    
    # Close connection
    connection.disconnect()
    print("Done!")

if __name__ == "__main__":
    main()
To use this script: 1. First, install the required package:
1
pip install netmiko
2. Modify the device connection parameters in the `main()` function:
1
2
3
4
5
6
7
device = {
    'device_type': 'cisco_ios',  # or 'cisco_nxos' for Nexus
    'host': 'your_device_ip',
    'username': 'your_username',
    'password': 'your_password',
    'secret': 'your_enable_secret',  # if needed
}
This script will: 1. Connect to the specified Cisco device 2. Collect various information including: - Current privilege level - Device version - Hostname - Running configuration - CDP neighbors - LLDP neighbors (if supported) - Interface status - IP interface information 3. Save the information to two files: - A main file with general device information - A separate file containing the running configuration The output files will be named using the device's hostname and a timestamp. Features: - Error handling for connection failures - Automatic enable mode detection and elevation - Separate files for better organization - Timestamp-based file naming - Support for both IOS and NX-OS devices Note: - Make sure you have network connectivity to the device - Ensure you have proper credentials and privileges - Some commands might vary between IOS and NX-OS; you might need to adjust them based on your specific device - Some devices might not support all commands (especially LLDP) You can extend this script by adding more commands or modifying the output format according to your needs.

Check if all of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show version: True

Check if any of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show lldp neighbors detail: True

Substring Evaluation

Testing if the previous output contains the string show lldp neighbors: True

Final Answer: True

Check if any of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show cdp neighbors detail: True

Substring Evaluation

Testing if the previous output contains the string show cdp neighbors: True

Final Answer: True

Substring Evaluation

Testing if the previous output contains the string show run: True

Substring Evaluation

Testing if the previous output contains the string show privilege: True

Final Answer: True

Initial Query

Give me code that collects a Cisco IOS or NXOS device information and configuration, including things like current privilege level, running configuration, LLDP and CDP neighbors

LLM Generation

Query

Give me code that collects a Cisco IOS or NXOS device information and configuration, including things like current privilege level, running configuration, LLDP and CDP neighbors

Output

Here's a Python script that uses the Netmiko library to collect various information from a Cisco IOS or NX-OS device:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
from netmiko import ConnectHandler
from datetime import datetime
import sys
import re

def connect_to_device(device_info):
    """Establish connection to the device"""
    try:
        connection = ConnectHandler(**device_info)
        return connection
    except Exception as e:
        print(f"Failed to connect to device: {str(e)}")
        sys.exit(1)

def get_device_info(connection):
    """Collect basic device information"""
    try:
        # Get device hostname
        hostname = connection.send_command('show hostname')
        
        # Get current privilege level
        priv = connection.send_command('show privilege')
        
        # Get version information
        version = connection.send_command('show version')
        
        return {
            'hostname': hostname.strip(),
            'privilege': priv.strip(),
            'version': version
        }
    except Exception as e:
        print(f"Error collecting device info: {str(e)}")
        return None

def get_running_config(connection):
    """Collect running configuration"""
    try:
        config = connection.send_command('show running-config')
        return config
    except Exception as e:
        print(f"Error collecting running config: {str(e)}")
        return None

def get_cdp_neighbors(connection):
    """Collect CDP neighbor information"""
    try:
        cdp_neighbors = connection.send_command('show cdp neighbors detail')
        return cdp_neighbors
    except Exception as e:
        print(f"Error collecting CDP neighbors: {str(e)}")
        return None

def get_lldp_neighbors(connection):
    """Collect LLDP neighbor information"""
    try:
        lldp_neighbors = connection.send_command('show lldp neighbors detail')
        return lldp_neighbors
    except Exception as e:
        print(f"Error collecting LLDP neighbors: {str(e)}")
        return None

def save_output(filename, content):
    """Save output to file"""
    try:
        with open(filename, 'w') as f:
            f.write(content)
    except Exception as e:
        print(f"Error saving to file: {str(e)}")

def main():
    # Device connection parameters
    device_info = {
        'device_type': 'cisco_ios',  # or 'cisco_nxos' for Nexus devices
        'host': '192.168.1.1',  # Replace with your device IP
        'username': 'your_username',
        'password': 'your_password',
        'secret': 'enable_secret',  # if needed
    }

    # Connect to device
    connection = connect_to_device(device_info)
    
    # Enter enable mode if needed
    if device_info['device_type'] == 'cisco_ios':
        connection.enable()

    # Get timestamp for filenames
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')

    # Collect device information
    device_info = get_device_info(connection)
    if device_info:
        hostname = device_info['hostname']
        print(f"Connected to device: {hostname}")
        print(f"Current privilege level: {device_info['privilege']}")
        
        # Save version information
        save_output(f"{hostname}_{timestamp}_version.txt", device_info['version'])

    # Collect and save running configuration
    config = get_running_config(connection)
    if config:
        save_output(f"{hostname}_{timestamp}_running_config.txt", config)

    # Collect and save CDP neighbors
    cdp_neighbors = get_cdp_neighbors(connection)
    if cdp_neighbors:
        save_output(f"{hostname}_{timestamp}_cdp_neighbors.txt", cdp_neighbors)

    # Collect and save LLDP neighbors
    lldp_neighbors = get_lldp_neighbors(connection)
    if lldp_neighbors:
        save_output(f"{hostname}_{timestamp}_lldp_neighbors.txt", lldp_neighbors)

    # Disconnect from device
    connection.disconnect()
    print("Data collection completed successfully!")

if __name__ == "__main__":
    main()
To use this script: 1. First, install the required package:
1
pip install netmiko
2. Modify the device_info dictionary with your device's: - IP address - Username - Password - Enable secret (if needed) - Device type ('cisco_ios' or 'cisco_nxos') 3. Run the script:
1
python cisco_device_info.py
The script will: 1. Connect to the device 2. Collect basic device information (hostname, privilege level, version) 3. Collect the running configuration 4. Collect CDP neighbor information 5. Collect LLDP neighbor information 6. Save all information to separate files with timestamps The output files will be named using this format: - `hostname_timestamp_version.txt` - `hostname_timestamp_running_config.txt` - `hostname_timestamp_cdp_neighbors.txt` - `hostname_timestamp_lldp_neighbors.txt` Additional features you might want to add: 1. Error handling for specific command failures 2. Support for multiple devices 3. Additional command outputs (interfaces, routing table, etc.) 4. Parse the outputs into structured data 5. Support for SSH key-based authentication 6. Configuration backup 7. Threading for multiple concurrent device connections Remember to handle the device credentials securely in a production environment (don't hardcode them in the script). This script provides a basic framework that you can build upon based on your specific needs.

Check if all of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show version: True

Check if any of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show lldp neighbors detail: True

Substring Evaluation

Testing if the previous output contains the string show lldp neighbors: True

Final Answer: True

Check if any of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show cdp neighbors detail: True

Substring Evaluation

Testing if the previous output contains the string show cdp neighbors: True

Final Answer: True

Substring Evaluation

Testing if the previous output contains the string show run: True

Substring Evaluation

Testing if the previous output contains the string show privilege: True

Final Answer: True

Initial Query

Give me code that collects a Cisco IOS or NXOS device information and configuration, including things like current privilege level, running configuration, LLDP and CDP neighbors

LLM Generation

Query

Give me code that collects a Cisco IOS or NXOS device information and configuration, including things like current privilege level, running configuration, LLDP and CDP neighbors

Output

Here's a Python script that uses the Netmiko library to collect various information from Cisco IOS or NX-OS devices:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
from netmiko import ConnectHandler
from datetime import datetime
import sys
import re

def connect_to_device(device_info):
    """Establish connection to the device"""
    try:
        connection = ConnectHandler(**device_info)
        return connection
    except Exception as e:
        print(f"Failed to connect to device: {str(e)}")
        sys.exit(1)

def get_device_info(connection):
    """Collect basic device information"""
    device_info = {}
    
    # Get privilege level
    priv = connection.send_command("show privilege")
    device_info['privilege_level'] = re.search(r"Current privilege level is (\d+)", priv).group(1)
    
    # Get version information
    version = connection.send_command("show version")
    device_info['version'] = version
    
    # Get hostname
    hostname = connection.send_command("show running-config | include hostname")
    device_info['hostname'] = hostname.replace("hostname ", "").strip()
    
    return device_info

def get_running_config(connection):
    """Get running configuration"""
    return connection.send_command("show running-config")

def get_cdp_neighbors(connection):
    """Get CDP neighbor information"""
    return connection.send_command("show cdp neighbors detail")

def get_lldp_neighbors(connection):
    """Get LLDP neighbor information"""
    return connection.send_command("show lldp neighbors detail")

def save_output(filename, content):
    """Save output to file"""
    with open(filename, 'w') as f:
        f.write(content)

def main():
    # Device connection parameters
    device = {
        'device_type': 'cisco_ios',  # or 'cisco_nxos' for Nexus
        'host': 'device_ip_address',
        'username': 'your_username',
        'password': 'your_password',
        'secret': 'enable_secret',  # if needed
    }

    # Connect to device
    print("Connecting to device...")
    connection = connect_to_device(device)
    
    # Create timestamp for filenames
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    
    try:
        # Get device information
        print("Collecting device information...")
        device_info = get_device_info(connection)
        
        # Get running configuration
        print("Collecting running configuration...")
        running_config = get_running_config(connection)
        
        # Get CDP neighbors
        print("Collecting CDP neighbor information...")
        cdp_neighbors = get_cdp_neighbors(connection)
        
        # Get LLDP neighbors
        print("Collecting LLDP neighbor information...")
        lldp_neighbors = get_lldp_neighbors(connection)
        
        # Save all information to files
        hostname = device_info['hostname']
        
        # Save device info
        device_info_output = "\n".join([f"{k}: {v}" for k, v in device_info.items()])
        save_output(f"{hostname}_{timestamp}_device_info.txt", device_info_output)
        
        # Save running config
        save_output(f"{hostname}_{timestamp}_running_config.txt", running_config)
        
        # Save CDP neighbors
        save_output(f"{hostname}_{timestamp}_cdp_neighbors.txt", cdp_neighbors)
        
        # Save LLDP neighbors
        save_output(f"{hostname}_{timestamp}_lldp_neighbors.txt", lldp_neighbors)
        
        print("All information has been collected and saved to files.")
        
    except Exception as e:
        print(f"An error occurred: {str(e)}")
    
    finally:
        # Close the connection
        connection.disconnect()
        print("Disconnected from device.")

if __name__ == "__main__":
    main()
To use this script: 1. First, install the required package:
1
pip install netmiko
2. Modify the device connection parameters in the `main()` function:
1
2
3
4
5
6
7
device = {
    'device_type': 'cisco_ios',  # or 'cisco_nxos' for Nexus
    'host': 'device_ip_address',
    'username': 'your_username',
    'password': 'your_password',
    'secret': 'enable_secret',  # if needed
}
This script will: - Connect to the device - Collect the current privilege level - Get basic device information - Collect the running configuration - Get CDP neighbor information - Get LLDP neighbor information - Save all information to separate files with timestamps The output files will be named using this format: - `hostname_timestamp_device_info.txt` - `hostname_timestamp_running_config.txt` - `hostname_timestamp_cdp_neighbors.txt` - `hostname_timestamp_lldp_neighbors.txt` Additional features you might want to add: 1. Error handling for specific commands that might not be supported 2. Support for multiple devices 3. Command-line arguments for device parameters 4. Additional device information collection (interfaces, routing tables, etc.) 5. Parallel execution for multiple devices 6. Configuration backup verification 7. Support for different authentication methods (SSH keys, etc.) Remember to handle credentials securely in a production environment. You might want to: - Use environment variables - Use a secure credential vault - Implement proper error handling - Add logging functionality - Add input validation - Implement retry mechanisms for failed connections Also, make sure you have the necessary permissions on the network device to execute these commands.

Check if all of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show version: True

Check if any of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show lldp neighbors detail: True

Substring Evaluation

Testing if the previous output contains the string show lldp neighbors: True

Final Answer: True

Check if any of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show cdp neighbors detail: True

Substring Evaluation

Testing if the previous output contains the string show cdp neighbors: True

Final Answer: True

Substring Evaluation

Testing if the previous output contains the string show run: True

Substring Evaluation

Testing if the previous output contains the string show privilege: True

Final Answer: True

Initial Query

Give me code that collects a Cisco IOS or NXOS device information and configuration, including things like current privilege level, running configuration, LLDP and CDP neighbors

LLM Generation

Query

Give me code that collects a Cisco IOS or NXOS device information and configuration, including things like current privilege level, running configuration, LLDP and CDP neighbors

Output

Here's a Python script using the Netmiko library that collects various information from a Cisco IOS or NX-OS device:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
from netmiko import ConnectHandler
from datetime import datetime
import sys
import re

def connect_to_device(device_info):
    """Establish connection to the device"""
    try:
        connection = ConnectHandler(**device_info)
        return connection
    except Exception as e:
        print(f"Failed to connect to device: {str(e)}")
        sys.exit(1)

def get_device_info(connection):
    """Collect basic device information"""
    device_info = {}
    
    # Get hostname
    hostname = connection.find_prompt()
    device_info['hostname'] = hostname.strip('#>')
    
    # Get privilege level
    priv_level = connection.send_command('show privilege')
    device_info['privilege_level'] = priv_level.strip()
    
    # Get version information
    version = connection.send_command('show version')
    device_info['version'] = version
    
    return device_info

def get_running_config(connection):
    """Get running configuration"""
    return connection.send_command('show running-config')

def get_cdp_neighbors(connection):
    """Get CDP neighbor information"""
    return connection.send_command('show cdp neighbors detail')

def get_lldp_neighbors(connection):
    """Get LLDP neighbor information"""
    return connection.send_command('show lldp neighbors detail')

def get_interfaces(connection):
    """Get interface information"""
    return connection.send_command('show interfaces')

def save_output(filename, content):
    """Save output to file"""
    with open(filename, 'w') as f:
        f.write(content)

def main():
    # Device connection parameters
    device = {
        'device_type': 'cisco_ios',  # or 'cisco_nxos' for Nexus
        'host': '192.168.1.1',  # Replace with your device IP
        'username': 'your_username',
        'password': 'your_password',
        'secret': 'enable_secret',  # if needed
    }

    # Connect to device
    print("Connecting to device...")
    connection = connect_to_device(device)
    
    # Enter enable mode if needed
    connection.enable()

    # Create timestamp for filenames
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    
    # Collect and save device information
    print("Collecting device information...")
    device_info = get_device_info(connection)
    
    print("Collecting running configuration...")
    running_config = get_running_config(connection)
    
    print("Collecting CDP neighbors...")
    cdp_neighbors = get_cdp_neighbors(connection)
    
    print("Collecting LLDP neighbors...")
    lldp_neighbors = get_lldp_neighbors(connection)
    
    print("Collecting interface information...")
    interfaces = get_interfaces(connection)

    # Save all information to files
    hostname = device_info['hostname']
    
    save_output(f"{hostname}_{timestamp}_device_info.txt", 
                str(device_info))
    save_output(f"{hostname}_{timestamp}_running_config.txt", 
                running_config)
    save_output(f"{hostname}_{timestamp}_cdp_neighbors.txt", 
                cdp_neighbors)
    save_output(f"{hostname}_{timestamp}_lldp_neighbors.txt", 
                lldp_neighbors)
    save_output(f"{hostname}_{timestamp}_interfaces.txt", 
                interfaces)

    # Disconnect from device
    connection.disconnect()
    print("Data collection complete!")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nProgram terminated by user")
        sys.exit()
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        sys.exit(1)
To use this script: 1. First, install the required package:
1
pip install netmiko
2. Modify the device connection parameters in the `main()` function:
1
2
3
4
5
6
7
device = {
    'device_type': 'cisco_ios',  # or 'cisco_nxos' for Nexus
    'host': 'your_device_ip',
    'username': 'your_username',
    'password': 'your_password',
    'secret': 'your_enable_secret',  # if needed
}
This script will: 1. Connect to the specified Cisco device 2. Collect various information including: - Basic device information - Current privilege level - Running configuration - CDP neighbors - LLDP neighbors - Interface information 3. Save all collected information to separate files with timestamps The output files will be named using the format: - `hostname_timestamp_device_info.txt` - `hostname_timestamp_running_config.txt` - `hostname_timestamp_cdp_neighbors.txt` - `hostname_timestamp_lldp_neighbors.txt` - `hostname_timestamp_interfaces.txt` Additional features you might want to add: 1. Error handling for specific commands that might not be supported 2. Support for multiple devices 3. Configuration backup 4. Parse and structure the output (using TextFSM or similar) 5. Additional device information collection (routing tables, VLANs, etc.) 6. Support for different authentication methods (SSH keys, etc.) To make the script more secure, you might want to: 1. Use environment variables for credentials 2. Add SSH key-based authentication 3. Add error handling for timeout and authentication failures 4. Add logging functionality 5. Add input validation Remember to handle the credentials securely and never store them in plain text in your script.

Check if all of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show version: True

Check if any of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show lldp neighbors detail: True

Substring Evaluation

Testing if the previous output contains the string show lldp neighbors: True

Final Answer: True

Check if any of the following conditions are true:

Substring Evaluation

Testing if the previous output contains the string show cdp neighbors detail: True

Substring Evaluation

Testing if the previous output contains the string show cdp neighbors: True

Final Answer: True

Substring Evaluation

Testing if the previous output contains the string show run: True

Substring Evaluation

Testing if the previous output contains the string show privilege: True

Final Answer: True