├── Nornir
├── beta2.0.0b1
│ ├── config.yaml
│ ├── inventory
│ │ ├── default.yaml
│ │ ├── groups.yaml
│ │ └── hosts.yaml
│ └── script1.py
├── using_napalm_plugin
│ ├── archive
│ │ ├── PH
│ │ ├── groups.yaml
│ │ ├── hosts.yaml
│ │ ├── script1.py
│ │ └── script1_output.txt
│ ├── config.yaml
│ ├── inventory
│ │ ├── groups.yaml
│ │ └── hosts.yaml
│ └── nornir_pb.py
└── using_netmiko_plugin
│ ├── config_example.py
│ ├── groups.yaml
│ ├── hosts.yaml
│ ├── output_config_example.txt
│ ├── output_show_cmds_example.txt
│ └── show_cmds_example.py
├── README.md
├── archive
├── Netmiko_multi_dev_script.py
├── commands.txt
├── devices.txt
└── netmiko_script1.py
├── crontab_e_setup
├── dnac
├── get_client_health_info.py
└── get_devices_dnac.py
├── meraki
├── Create_Network.py
├── Get_info_dashboard.py
└── Update_SSID.py
├── misc
├── findingDupIP.py
├── loop_thru_cli_cmds.py
└── loop_thru_cli_cmds_output.txt
├── napalm
├── archive
│ ├── EOS_lab_Napalm_test_results
│ └── Notes about Napalm_ios
├── config_scripts
│ ├── access_list.cfg
│ ├── conf_merge
│ │ ├── eos1.txt
│ │ ├── eos2.txt
│ │ ├── napalm_cfg_merge.py
│ │ └── output_napalm_cfg_merge_output.txt
│ ├── config_file.cfg
│ ├── config_script1.py
│ ├── config_script_ios.py
│ ├── global_config.cfg
│ └── output_config_script_ios.py
├── napalm_eos_script_ex1.py
├── napalm_script1.py
├── script_get_cfg.py
├── script_get_facts.py
└── svc_now
│ ├── discovery_ios_svc_now.py
│ └── post_svc_now_rest_api.py
├── netconf
├── README.md
├── netconf_config_bkup.py
├── netconf_config_bkup_output.txt
├── netconf_config_device.py
├── netconf_config_device_output.txt
├── netconf_ex1.py
├── netconf_get_conf.py
├── netconf_iosxe_cfg_bkup.py
├── netconf_svr_capability.py
└── netconf_svr_capability_ouput.txt
├── netmiko
├── Juniper
│ ├── config.txt
│ ├── juniper_conf_from_file.py
│ ├── juniper_conf_from_file_output.txt
│ ├── juniper_script1.py
│ └── juniper_script1_output.txt
├── NetworkDiscovery
│ ├── host_file_and_script
│ │ ├── README.md
│ │ ├── archive
│ │ │ └── discovery_script.py
│ │ ├── auto_detect_script.py
│ │ ├── host_file.txt
│ │ ├── ios_discovery_enable_mode.py
│ │ ├── ios_discovery_script.py
│ │ └── script_output.txt
│ ├── same_config_multi_device.py
│ ├── show_cdp_neighbor.py
│ ├── show_commands.py
│ ├── show_ip_bgp_summ.py
│ ├── show_ip_int_brief
│ ├── show_ip_route.py
│ ├── show_run.py
│ ├── show_uptime.py
│ └── show_version.py
├── Normal processing vs multi-processing pools
├── archive
│ ├── clean_up_lab.py
│ ├── netmiko_script2.py
│ ├── netmiko_script3.py
│ ├── output_netmiko_multi_dev_cfg
│ ├── output_netmiko_script5.py
│ ├── output_netmiko_show_cmds.txt
│ └── placeholder
├── basic_ssh_script.py
├── config_scripts
│ ├── interactive_config_script.py
│ ├── multiple_device_config_script.py
│ └── push_same_cfg_multi_devs.py
├── jinja_example
│ ├── bgp_template_r4.yaml
│ ├── bgp_template_r5.yaml
│ ├── conf_bgp_r4_r5_using_class_obj.py
│ ├── conf_bgp_r4_r5_using_dict.py
│ ├── conf_bgp_yaml_jinja2.py
│ └── ebgp_neighbor_template.j2
├── netmiko_multi_dev_cfg.py
├── netmiko_script5.py
├── netmiko_show_cmds.py
├── scp
│ ├── ceos
│ │ ├── ceos1.config
│ │ ├── ceos2.config
│ │ ├── info.text
│ │ ├── scp_file_arista.output.txt
│ │ ├── scp_file_arista.py
│ │ └── test_file.txt
│ ├── info.txt
│ ├── netmiko_scp_script.py
│ ├── output_netmiko_scp_script.txt
│ └── test_file.txt
├── script_requests
│ └── req_config_script_07292020.py
├── ssh_sandbox.py
└── test_stuff
│ ├── interactive_script.py
│ └── interactive_script_output,txt
├── network_controller
├── get_all_devices_info.py
├── get_device_info.py
├── pt_get_info_api.py
└── update_device_config.py
├── nxapi
├── nxapi_script02.py
├── nxapi_script02_output.txt
├── nxapi_script1.py
└── nxapi_script_ex1.output.txt
├── pip3 freeze
├── pyeapi
├── .eapi.conf
├── archive
│ ├── interactive_show_cmds.py
│ ├── multi_dev_cfg_script.py
│ └── multi_dev_cfg_script2.py
├── ceos_demo
│ ├── .eapi.conf
│ ├── README.md
│ ├── script1.py
│ ├── script2.py
│ └── script3.py
├── ceos_lab_scripts
│ ├── ceos_4_sw_lab.txt
│ ├── lab_config_script.py
│ └── wr_mem_lab_configs.py
├── demo
│ ├── .eapi.conf
│ ├── script1.py
│ ├── script2.py
│ └── script_results.txt
├── eapi_config_ex1.py
├── eapi_ex1.py
├── eapi_ex2.py
├── eapi_validation_ex1.py
├── interactive_scripts
│ ├── README.md
│ ├── pyeapi_config_script.py
│ └── pyeapi_show_cmds_script.py
├── pyeapi_w_out_conf_file.py
└── script results
├── restconf
├── create_intf.py
├── delete_intf.py
├── restconf_ex1.py
├── restconf_ex2.py
└── script_output.txt
└── telnetlib
├── script_output.txt
├── telnet_py3.py
└── telnet_script_enable_mode.py
/Nornir/beta2.0.0b1/config.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | core:
3 | num_workers: 100
4 |
5 | inventory:
6 | plugin: nornir.plugins.inventory.simple.SimpleInventory
7 | options:
8 | host_file: "inventory/hosts.yaml"
9 | group_file: "inventory/groups.yaml"
10 | default_file: "inventory/default.yaml"
11 |
--------------------------------------------------------------------------------
/Nornir/beta2.0.0b1/inventory/default.yaml:
--------------------------------------------------------------------------------
1 | ---
2 |
--------------------------------------------------------------------------------
/Nornir/beta2.0.0b1/inventory/groups.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | lab:
3 | data:
4 | site: lab
5 | role: spline
6 | type: network_device
7 |
--------------------------------------------------------------------------------
/Nornir/beta2.0.0b1/inventory/hosts.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | ceos1:
3 | hostname: 127.0.0.1
4 | username: arista
5 | password: arista
6 | port: 443 #Used for napalm to connect to via eapi
7 | # port: 2022 # Used for netmiko
8 | groups:
9 | - lab
10 | platform: eos
11 | data:
12 | site: lab
13 | role: spline
14 | type: network_device
15 |
16 | ceos2:
17 | hostname: 127.0.0.1
18 | username: arista
19 | password: arista
20 | port: 8443 #Used for napalm to connect via eapi
21 | # port: 2023 # used for netmiko
22 | groups:
23 | - lab
24 | platform: eos
25 | data:
26 | site: lab
27 | role: spline
28 | type: network_device
29 |
--------------------------------------------------------------------------------
/Nornir/beta2.0.0b1/script1.py:
--------------------------------------------------------------------------------
1 | from nornir import InitNornir
2 | from nornir.plugins.functions.text import print_result
3 | from nornir.plugins.tasks import networking
4 |
5 | nr = InitNornir(config_file="config.yaml")
6 |
7 | lab_hosts = nr.filter(role="spline")
8 |
9 | result = lab_hosts.run(task=networking.napalm_get,
10 | getters=["facts", "config", "interfaces_ip"])
11 |
12 | print_result(result)
13 |
14 | print(nr.inventory.hosts)
15 | print(nr.inventory.groups)
16 |
--------------------------------------------------------------------------------
/Nornir/using_napalm_plugin/archive/PH:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Nornir/using_napalm_plugin/archive/groups.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | ceos_lab:
3 | nornir_username: arista
4 | nornir_password: arista
5 | nornir_nos: eos
6 |
--------------------------------------------------------------------------------
/Nornir/using_napalm_plugin/archive/hosts.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | ceos1:
3 | nornir_host: 127.0.0.1
4 | nornir_network_api_port: 443
5 | groups: ['ceos_lab']
6 |
7 | ceos2:
8 | nornir_host: 127.0.0.1
9 | transport: https
10 | nornir_network_api_port: 8443
11 | groups: ['ceos_lab']
12 |
--------------------------------------------------------------------------------
/Nornir/using_napalm_plugin/archive/script1.py:
--------------------------------------------------------------------------------
1 | from nornir.core import InitNornir
2 | from nornir.plugins.tasks.networking import napalm_get
3 | from nornir.plugins.functions.text import print_result
4 |
5 | nr = InitNornir()
6 |
7 | result = nr.run(
8 | napalm_get,
9 | getters=['get_facts', 'get_config',])
10 |
11 | print_result(result)
12 |
--------------------------------------------------------------------------------
/Nornir/using_napalm_plugin/config.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | num_workers: 100
3 | inventory: nornir.plugins.inventory.simple.SimpleInventory
4 | SimpleInventory:
5 | host_file: "inventory/hosts.yaml"
6 | group_file: "inventory/groups.yaml"
7 |
8 |
--------------------------------------------------------------------------------
/Nornir/using_napalm_plugin/inventory/groups.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | defaults:
3 | domain: lab.test
4 |
5 | lab:
6 | bogus: value
7 |
--------------------------------------------------------------------------------
/Nornir/using_napalm_plugin/inventory/hosts.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | eos1:
3 | nornir_host: 127.0.0.1
4 | nornir_network_api_port: 12443
5 | nornir_username: arista
6 | nornir_password: arista
7 | site: lab
8 | role: spline
9 | groups:
10 | - lab
11 | nornir_nos: eos
12 | type: network_device
13 |
14 | eos2:
15 | nornir_host: 127.0.0.1
16 | nornir_network_api_port: 13443
17 | nornir_username: arista
18 | nornir_password: arista
19 | site: lab
20 | role: spline
21 | groups:
22 | - lab
23 | nornir_nos: eos
24 | type: network_device
25 |
26 |
--------------------------------------------------------------------------------
/Nornir/using_napalm_plugin/nornir_pb.py:
--------------------------------------------------------------------------------
1 | from nornir.core import InitNornir
2 | from nornir.plugins.functions.text import print_result
3 | from nornir.plugins.tasks import networking
4 |
5 | nr = InitNornir(config_file="config.yaml")
6 |
7 | lab_hosts = nr.filter(site="lab", role="spline")
8 |
9 | result = lab_hosts.run(task=networking.napalm_get,
10 | getters=["facts", "config", "interfaces_ip"])
11 |
12 | print_result(result)
13 |
14 | print(nr.inventory.hosts)
15 | print(nr.inventory.groups)
16 |
17 |
--------------------------------------------------------------------------------
/Nornir/using_netmiko_plugin/config_example.py:
--------------------------------------------------------------------------------
1 | from nornir.core import InitNornir
2 | from nornir.plugins.tasks.networking import netmiko_send_config
3 | from nornir.plugins.functions.text import print_result
4 |
5 |
6 | target = input("Pick group of devices to configure core, distribution, access: ")
7 | cfgs = input("Enter configuration lines seperated by ',': ")
8 | cfgs_items = cfgs.split(",")
9 | print(cfgs_items)
10 |
11 | nr = InitNornir()
12 | target_host = nr.filter(site=target)
13 |
14 |
15 | result = target_host.run(
16 | task=netmiko_send_config,
17 | config_commands=cfgs_items
18 | )
19 |
20 | print_result(result)
21 |
--------------------------------------------------------------------------------
/Nornir/using_netmiko_plugin/groups.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | routers:
3 | nornir_ssh_port: 22
4 | nornir_username: admin
5 | nornir_password: automate
6 | nornir_nos: cisco_ios
7 |
8 |
--------------------------------------------------------------------------------
/Nornir/using_netmiko_plugin/hosts.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | r1:
3 | site: core
4 | groups:
5 | - routers
6 | nornir_host: 1.1.1.1
7 |
8 | r2:
9 | site: core
10 | groups:
11 | - routers
12 | nornir_host: 2.2.2.2
13 |
14 | r3:
15 | site: distribution
16 | groups:
17 | - routers
18 | nornir_host: 3.3.3.3
19 |
20 | r4:
21 | site: distribution
22 | groups:
23 | - routers
24 | nornir_host: 4.4.4.4
25 |
26 | r5:
27 | site: distribution
28 | groups:
29 | - routers
30 | nornir_host: 5.5.5.5
31 |
32 | r6:
33 | site: distribution
34 | groups:
35 | - routers
36 | nornir_host: 6.6.6.6
37 |
38 | r7:
39 | site: access
40 | groups:
41 | - routers
42 | nornir_host: 7.7.7.7
43 |
44 | r8:
45 | site: access
46 | groups:
47 | - routers
48 | nornir_host: 8.8.8.8
49 |
50 | r9:
51 | site: access
52 | groups:
53 | - routers
54 | nornir_host: 9.9.9.9
55 |
56 | r10:
57 | site: access
58 | groups:
59 | - routers
60 | nornir_host: 10.10.10.10
61 |
--------------------------------------------------------------------------------
/Nornir/using_netmiko_plugin/output_config_example.txt:
--------------------------------------------------------------------------------
1 | todd@ubuntu:~/automation/nornir_stuff$ python3 config_example.py
2 | Pick group of devices to configure core, distribution, access: access
3 | Enter configuration lines seperated by ',': interface loopback101, description access_layer_device
4 | ['interface loopback101', ' description access_layer_device']
5 | netmiko_send_config*************************************************************
6 | * r10 ** changed : True ********************************************************
7 | vvvv netmiko_send_config ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
8 | config term
9 | Enter configuration commands, one per line. End with CNTL/Z.
10 | r10(config)#interface loopback101
11 | r10(config-if)# description access_layer_device
12 | r10(config-if)#end
13 | r10#
14 | ^^^^ END netmiko_send_config ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
15 | * r7 ** changed : True *********************************************************
16 | vvvv netmiko_send_config ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
17 | config term
18 | Enter configuration commands, one per line. End with CNTL/Z.
19 | r7(config)#interface loopback101
20 | r7(config-if)# description access_layer_device
21 | r7(config-if)#end
22 | r7#
23 | ^^^^ END netmiko_send_config ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
24 | * r8 ** changed : True *********************************************************
25 | vvvv netmiko_send_config ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
26 | config term
27 | Enter configuration commands, one per line. End with CNTL/Z.
28 | r8(config)#interface loopback101
29 | r8(config-if)# description access_layer_device
30 | r8(config-if)#end
31 | r8#
32 | ^^^^ END netmiko_send_config ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
33 | * r9 ** changed : True *********************************************************
34 | vvvv netmiko_send_config ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
35 | config term
36 | Enter configuration commands, one per line. End with CNTL/Z.
37 | r9(config)#interface loopback101
38 | r9(config-if)# description access_layer_device
39 | r9(config-if)#end
40 | r9#
41 | ^^^^ END netmiko_send_config ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
42 | todd@ubuntu:~/automation/nornir_stuff$ python3 config_example.py
43 | Pick group of devices to configure core, distribution, access: distribution
44 | Enter configuration lines seperated by ',': interface loopback 101, description distribution_layer_device
45 | ['interface loopback 101', ' description distribution_layer_device']
46 | netmiko_send_config*************************************************************
47 | * r3 ** changed : True *********************************************************
48 | vvvv netmiko_send_config ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
49 | config term
50 | Enter configuration commands, one per line. End with CNTL/Z.
51 | r3(config)#interface loopback 101
52 | r3(config-if)# description distribution_layer_device
53 | r3(config-if)#end
54 | r3#
55 | ^^^^ END netmiko_send_config ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
56 | * r4 ** changed : True *********************************************************
57 | vvvv netmiko_send_config ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
58 | config term
59 | Enter configuration commands, one per line. End with CNTL/Z.
60 | r4(config)#interface loopback 101
61 | r4(config-if)# description distribution_layer_device
62 | r4(config-if)#end
63 | r4#
64 | ^^^^ END netmiko_send_config ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
65 | * r5 ** changed : True *********************************************************
66 | vvvv netmiko_send_config ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
67 | config term
68 | Enter configuration commands, one per line. End with CNTL/Z.
69 | r5(config)#interface loopback 101
70 | r5(config-if)# description distribution_layer_device
71 | r5(config-if)#end
72 | r5#
73 | ^^^^ END netmiko_send_config ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
74 | * r6 ** changed : True *********************************************************
75 | vvvv netmiko_send_config ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
76 | config term
77 | Enter configuration commands, one per line. End with CNTL/Z.
78 | r6(config)#interface loopback 101
79 | r6(config-if)# description distribution_layer_device
80 | r6(config-if)#end
81 | r6#
82 | ^^^^ END netmiko_send_config ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
83 | todd@ubuntu:~/automation/nornir_stuff$ python3 config_example.py
84 | Pick group of devices to configure core, distribution, access: core
85 | Enter configuration lines seperated by ',': interface loopback 101, description core_layer_device
86 | ['interface loopback 101', ' description core_layer_device']
87 | netmiko_send_config*************************************************************
88 | * r1 ** changed : True *********************************************************
89 | vvvv netmiko_send_config ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
90 | config term
91 | Enter configuration commands, one per line. End with CNTL/Z.
92 | r1(config)#interface loopback 101
93 | r1(config-if)# description core_layer_device
94 | r1(config-if)#end
95 | r1#
96 | ^^^^ END netmiko_send_config ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
97 | * r2 ** changed : True *********************************************************
98 | vvvv netmiko_send_config ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
99 | config term
100 | Enter configuration commands, one per line. End with CNTL/Z.
101 | r2(config)#interface loopback 101
102 | r2(config-if)# description core_layer_device
103 | r2(config-if)#end
104 | r2#
105 | ^^^^ END netmiko_send_config ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
106 | todd@ubuntu:~/automation/nornir_stuff$
107 |
--------------------------------------------------------------------------------
/Nornir/using_netmiko_plugin/show_cmds_example.py:
--------------------------------------------------------------------------------
1 | from nornir.core import InitNornir
2 | from nornir.plugins.tasks.networking import netmiko_send_command
3 | from nornir.plugins.functions.text import print_result
4 |
5 | commands = input("Enter commands: ")
6 | cmds = commands.split(",")
7 |
8 | for cmd in cmds:
9 | nr = InitNornir()
10 |
11 | result = nr.run(
12 | task=netmiko_send_command,
13 | command_string=cmd
14 | )
15 |
16 | print_result(result)
17 |
18 |
--------------------------------------------------------------------------------
/archive/Netmiko_multi_dev_script.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | from getpass import getpass
4 | from netmiko import ConnectHandler
5 | from netmiko.ssh_exception import NetMikoTimeoutException
6 | from paramiko.ssh_exception import SSHException
7 | from netmiko.ssh_exception import AuthenticationException
8 |
9 | username = input('Enter username: ')
10 | password = getpass('Enter password: ')
11 |
12 | if len(username) < 1 : username = "automate"
13 | if len(password) < 1 : password = "automation"
14 |
15 | with open('commands_file_r1') as f:
16 | commands_list_r1 = f.read().splitlines()
17 |
18 | with open('commands_file_r2') as f:
19 | commands_list_r2 = f.read().splitlines()
20 |
21 | with open('commands_file_r3') as f:
22 | commands_list_r3 = f.read().splitlines()
23 |
24 | with open('commands_file_r4') as f:
25 | commands_list_r4 = f.read().splitlines()
26 |
27 | with open('commands_file_r5') as f:
28 | commands_list_r5 = f.read().splitlines()
29 |
30 | with open('commands_file_r6') as f:
31 | commands_list_r6 = f.read().splitlines()
32 |
33 | with open('commands_file_r7') as f:
34 | commands_list_r7 = f.read().splitlines()
35 |
36 | with open('devices_file') as f:
37 | devices_list = f.read().splitlines()
38 |
39 | print("----The devices being configured----")
40 | print(devices_list)
41 |
42 | # Updated /etc/hosts to use dns names rather than host ips
43 |
44 | for hostname in devices_list:
45 | print ('Connecting to device" ' + hostname)
46 | ip_address_of_device = hostname
47 | ios_device = {
48 | 'device_type': 'cisco_ios',
49 | 'ip': ip_address_of_device,
50 | 'username': username,
51 | 'password': password
52 | }
53 |
54 | try:
55 | net_connect = ConnectHandler(**ios_device)
56 | except (AuthenticationException):
57 | print('Authentication failure: ' + ip_address_of_device)
58 | continue
59 | except (NetMikoTimeoutException):
60 | print('Timeout to device: ' + ip_address_of_device)
61 | continue
62 | except (EOFError):
63 | print("End of file while attempting device " + ip_address_of_device)
64 | continue
65 | except (SSHException):
66 | print('SSH Issue. Are you sure SSH is enabled? ' + ip_address_of_device)
67 | continue
68 | except Exception as unknown_error:
69 | print('Some other error: ' + str(unknown_error))
70 | continue
71 |
72 | if hostname == 'r1':
73 | print("hostname == r1:", hostname == 'r1')
74 | output = net_connect.send_config_set(commands_list_r1)
75 | print(output)
76 | elif hostname == 'r2':
77 | print ("hostname == r2:", hostname == 'r2')
78 | output = net_connect.send_config_set(commands_list_r2)
79 | print(output)
80 | elif hostname == 'r3':
81 | print ("hostname == r3: ", hostname == 'r3')
82 | output = net_connect.send_config_set(commands_list_r3)
83 | print(output)
84 | elif hostname == 'r4':
85 | print ("hostname == r4:", hostname == 'r4')
86 | output = net_connect.send_config_set(commands_list_r4)
87 | print(output)
88 | elif hostname == 'r5':
89 | print ("hostname == r5:", hostname == 'r5')
90 | output = net_connect.send_config_set(commands_list_r5)
91 | print(output)
92 | elif hostname == 'r6':
93 | print ("hostname == r6: ", hostname == 'r6')
94 | output = net_connect.send_config_set(commands_list_r6)
95 | print(output)
96 | elif hostname == 'r7':
97 | print ("hostname == r7: ", hostname == 'r7')
98 | output = net_connect.send_config_set(commands_list_r7)
99 | print(output)
100 |
101 |
102 |
103 |
104 |
105 |
106 |
--------------------------------------------------------------------------------
/archive/commands.txt:
--------------------------------------------------------------------------------
1 | !
2 | !! Random configs for testing
3 | !
4 | username automate password automation
5 | username automate privilege 15
6 |
7 | line vty 0 15
8 | transport input telnet ssh
9 |
10 | router ospf 1
11 | network 0.0.0.0 0.0.0.0 area 0
12 |
13 | ip ssh version 2
14 |
15 | int fa1/0
16 | description test
17 | no shut
18 |
19 | do show run int fa1/0
20 | do show ip ospf neighbor
21 |
--------------------------------------------------------------------------------
/archive/devices.txt:
--------------------------------------------------------------------------------
1 | 192.168.10.1
2 | 192.168.10.2
3 | 192.168.10.3
4 |
--------------------------------------------------------------------------------
/archive/netmiko_script1.py:
--------------------------------------------------------------------------------
1 | #
2 | #Use netmiko to connect to three gns3 ios devices and configure something
3 | #
4 | #getpass will not display password
5 | from getpass import getpass
6 | #ConnectionHandler is the function used by netmiko to connect to devices
7 | from netmiko import ConnectHandler
8 |
9 | #create variables for username and password
10 | uname = input("Username: ")
11 | passwd = getpass("Password: ")
12 |
13 | #with is used to open and close files automatically
14 | #The commands.txt has all configuration commands
15 | #To view status use the do + show command
16 | with open("commands.txt") as f:
17 | cmds_to_send = f.read().splitlines()
18 |
19 | #dictionary is used to define a device
20 | #the device_type is key to the connection type with netmiko ssh vs api
21 | #call the login variables
22 |
23 | ios_rtr1 = {
24 | "device_type": "cisco_ios",
25 | "ip": "192.168.10.1",
26 | "username": uname,
27 | "password": passwd,
28 | }
29 |
30 | ios_rtr2 = {
31 | "device_type": "cisco_ios",
32 | "ip": "192.168.10.2",
33 | "username": uname,
34 | "password": passwd,
35 | }
36 |
37 | ios_rtr3 = {
38 | "device_type": "cisco_ios",
39 | "ip": "192.168.10.3",
40 | "username": uname,
41 | "password": passwd,
42 | }
43 | #create a list of all the devices you will be calling in your script
44 | devices = [ios_rtr1, ios_rtr2, ios_rtr3]
45 | #use a for loop to iterate through the devices
46 | for device in devices:
47 | #connect to the device via ssh
48 | net_connect = ConnectHandler(**device)
49 | #print the device IP to identify which device is being configured
50 | print(device["ip"])
51 | #this variable is used to capture the output of cmds sent to device
52 | output = net_connect.send_config_set(cmds_to_send)
53 | #print the output
54 | print(output)
55 |
56 |
57 |
--------------------------------------------------------------------------------
/crontab_e_setup:
--------------------------------------------------------------------------------
1 | SHELL=/bin/bash
2 | MAILTO=""
3 | # Edit this file to introduce tasks to be run by cron.
4 | #
5 | # Each task to run has to be defined through a single line
6 | # indicating with different fields when the task will be run
7 | # and what command to run for the task
8 | #
9 | # To define the time you can provide concrete values for
10 | # minute (m), hour (h), day of month (dom), month (mon),
11 | # and day of week (dow) or use '*' in these fields (for 'any').#
12 | # Notice that tasks will be started based on the cron's system
13 | # daemon's notion of time and timezones.
14 | #
15 | # Output of the crontab jobs (including errors) is sent through
16 | # email to the user the crontab file belongs to (unless redirected).
17 | #
18 | # For example, you can run a backup of all your user accounts
19 | # at 5 a.m every week with:
20 | # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
21 | #
22 | # For more information see the manual pages of crontab(5) and cron(8)
23 | #
24 | # m h dom mon dow command
25 | #* * * * * /usr/bin/python3 /home/todd/automation/napalm_stuff/script_get_cfg.py > /home/todd/automation/napalm_stuff/cron_output.txt 2>> /home/todd/automation/napalm_stuff/cron_error.txt
26 |
--------------------------------------------------------------------------------
/meraki/Create_Network.py:
--------------------------------------------------------------------------------
1 | import requests, json
2 |
3 | url = "https://api.meraki.com/api/v1/organizations/1097053/networks"
4 |
5 | payload = '''{
6 | "copyFromNetworkId": "N_627126248111476958",
7 | "name": "My office Network",
8 | "notes": "This is my new office network",
9 | "timeZone": "America/Los_Angeles",
10 | "productTypes": [ "wireless" ],
11 | "tags": [ "hideout", "man_cave" ]
12 | }'''
13 |
14 | headers = {
15 | "Content-Type": "application/json",
16 | "Accept": "application/json",
17 | "X-Cisco-Meraki-API-Key": "<>"
18 | }
19 |
20 | response = requests.request('POST', url, headers=headers, data = payload)
21 | data = json.loads(response.text)
22 | print(json.dumps(data, indent=4))
23 |
24 | '''
25 | result of script:
26 | {
27 | "id": "N_627126248111476961",
28 | "organizationId": "1097053",
29 | "productTypes": [
30 | "wireless"
31 | ],
32 | "url": "https://n114.meraki.com/My-office-Networ/n/YjIdXbYb/manage/usage/list",
33 | "name": "My office Network",
34 | "timeZone": "America/Los_Angeles",
35 | "enrollmentString": null,
36 | "tags": [
37 | "hideout",
38 | "man_cave"
39 | ],
40 | "notes": "This is my new office network",
41 | "isBoundToConfigTemplate": false
42 | }
43 | '''
44 |
--------------------------------------------------------------------------------
/meraki/Get_info_dashboard.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import requests
4 | import json
5 | from pprint import pprint as pp
6 |
7 | print('''
8 | Example:
9 | Enter Org ID: 573083052582915264
10 | Enter Network ID: L_573083052582991362
11 | Enter API_KEY: <>
12 | ''')
13 |
14 |
15 | orgId = input("Enter Org ID: ")
16 | # set default values
17 | if len(orgId) == 0 : orgId = "1097053"
18 |
19 | networkId = input("Enter Network ID: ")
20 | # set default values
21 | if len(networkId) == 0 : networkId = "L_627126248111380187"
22 |
23 |
24 | API_KEY = input("Enter API_KEY: " )
25 | # set default values
26 | if len(API_KEY) == 0 : API_KEY = "<>"
27 |
28 | url_0 = f"https://api.meraki.com/api/v1/organizations/"
29 | url_1 = f"https://api.meraki.com/api/v1/networks/{networkId}"
30 | url_2 = f"https://api.meraki.com/api/v1/organizations/{orgId}/networks"
31 |
32 |
33 | payload = {}
34 |
35 |
36 | headers = {
37 | "Accept": "application/json",
38 | "X-Cisco-Meraki-API-Key": f"{API_KEY}",
39 | }
40 | urls = [url_0, url_1,url_2]
41 | i = 0
42 | for url in urls:
43 | i +=1
44 | print(f"Loop {i}")
45 | try:
46 | response = requests.request("GET", url, headers=headers, data=payload)
47 | data = json.loads(response.text)
48 | print(json.dumps(data, indent = 2))
49 | except Exception as e:
50 | print(e)
51 |
52 |
53 |
54 |
55 | '''
56 | output of script
57 | $ ./get_data_dashboard.py
58 |
59 | Example:
60 | Enter Org ID: 573083052582915264
61 | Enter Network ID: L_573083052582991362
62 | Enter API_KEY: <>
63 |
64 | Enter Org ID:
65 | Enter Network ID:
66 | Enter API_KEY:
67 | Loop 1
68 | [
69 | {
70 | "id": "1097053",
71 | "name": "Independent Consultant",
72 | "url": "https://n114.meraki.com/o/7QEucc/manage/organization/overview",
73 | "api": {
74 | "enabled": true
75 | },
76 | "licensing": {
77 | "model": "co-term"
78 | },
79 | "cloud": {
80 | "region": {
81 | "name": "North America"
82 | }
83 | },
84 | "management": {
85 | "details": []
86 | }
87 | }
88 | ]
89 | Loop 2
90 | {
91 | "id": "L_627126248111380187",
92 | "organizationId": "1097053",
93 | "productTypes": [
94 | "switch"
95 | ],
96 | "url": "https://n114.meraki.com/Gibsons_Network-/n/MVk3rbYb/manage/usage/list",
97 | "name": "Gibsons_Network",
98 | "timeZone": "America/New_York",
99 | "enrollmentString": null,
100 | "tags": [],
101 | "notes": "",
102 | "isBoundToConfigTemplate": false
103 | }
104 | Loop 3
105 | [
106 | {
107 | "id": "L_627126248111380187",
108 | "organizationId": "1097053",
109 | "name": "Gibsons_Network",
110 | "productTypes": [
111 | "switch"
112 | ],
113 | "timeZone": "America/New_York",
114 | "tags": [],
115 | "enrollmentString": null,
116 | "url": "https://n114.meraki.com/Gibsons_Network-/n/MVk3rbYb/manage/usage/list",
117 | "notes": "",
118 | "isBoundToConfigTemplate": false
119 | },
120 | {
121 | "id": "L_627126248111380188",
122 | "organizationId": "1097053",
123 | "name": "Lunas Network",
124 | "productTypes": [
125 | "switch"
126 | ],
127 | "timeZone": "America/Los_Angeles",
128 | "tags": [
129 | "tag1",
130 | "tag2"
131 | ],
132 | "enrollmentString": null,
133 | "url": "https://n114.meraki.com/Lunas-Network-sw/n/Tn1rEdYb/manage/usage/list",
134 | "notes": "Boy this sure is involved",
135 | "isBoundToConfigTemplate": false
136 | },
137 | {
138 | "id": "N_627126248111476956",
139 | "organizationId": "1097053",
140 | "name": "Jacks_Room",
141 | "productTypes": [
142 | "switch"
143 | ],
144 | "timeZone": "America/Los_Angeles",
145 | "tags": [],
146 | "enrollmentString": null,
147 | "url": "https://n114.meraki.com/Jacks_Room/n/qSdrCcYb/manage/usage/list",
148 | "notes": null,
149 | "isBoundToConfigTemplate": false
150 | },
151 | {
152 | "id": "N_627126248111476958",
153 | "organizationId": "1097053",
154 | "name": "Evee_Network",
155 | "productTypes": [
156 | "wireless"
157 | ],
158 | "timeZone": "America/Los_Angeles",
159 | "tags": [],
160 | "enrollmentString": null,
161 | "url": "https://n114.meraki.com/Evee_Network/n/HgaoccYb/manage/usage/list",
162 | "notes": null,
163 | "isBoundToConfigTemplate": false
164 | },
165 | {
166 | "id": "N_627126248111476961",
167 | "organizationId": "1097053",
168 | "name": "My office Network",
169 | "productTypes": [
170 | "wireless"
171 | ],
172 | "timeZone": "America/Los_Angeles",
173 | "tags": [
174 | "hideout",
175 | "man_cave"
176 | ],
177 | "enrollmentString": null,
178 | "url": "https://n114.meraki.com/My-office-Networ/n/YjIdXbYb/manage/usage/list",
179 | "notes": "This is my new office network",
180 | "isBoundToConfigTemplate": false
181 | }
182 | ]
183 | '''
184 |
--------------------------------------------------------------------------------
/meraki/Update_SSID.py:
--------------------------------------------------------------------------------
1 | import requests, json
2 |
3 | url = "https://api.meraki.com/api/v1/networks/N_627126248111476961/wireless/ssids/0"
4 |
5 | payload = '''{
6 | "encryptionMode": "wpa",
7 | "authMode": "psk",
8 | "name": "TheHouseJackBuilt",
9 | "psk": "Jackisadog"
10 | }'''
11 |
12 | headers = {
13 | "Content-Type": "application/json",
14 | "Accept": "application/json",
15 | "X-Cisco-Meraki-API-Key": "<>"
16 | }
17 |
18 | response = requests.request('PUT', url, headers=headers, data = payload)
19 | data = json.loads(response.text)
20 | print(json.dumps(data, indent=4))
21 |
22 | '''
23 | Script: Output
24 | {
25 | "number": 0,
26 | "name": "TheHouseJackBuilt",
27 | "enabled": true,
28 | "splashPage": "None",
29 | "ssidAdminAccessible": false,
30 | "authMode": "psk",
31 | "psk": "Jackisadog",
32 | "dot11w": {
33 | "enabled": false,
34 | "required": false
35 | },
36 | "dot11r": {
37 | "enabled": false,
38 | "adaptive": false
39 | },
40 | "encryptionMode": "wpa",
41 | "wpaEncryptionMode": "WPA2 only",
42 | "ipAssignmentMode": "NAT mode",
43 | "adultContentFilteringEnabled": false,
44 | "dnsRewrite": {
45 | "enabled": false,
46 | "dnsCustomNameservers": []
47 | },
48 | "minBitrate": 11,
49 | "bandSelection": "Dual band operation",
50 | "perClientBandwidthLimitUp": 0,
51 | "perClientBandwidthLimitDown": 0,
52 | "perSsidBandwidthLimitUp": 0,
53 | "perSsidBandwidthLimitDown": 0,
54 | "mandatoryDhcpEnabled": false,
55 | "visible": true,
56 | "availableOnAllAps": true,
57 | "availabilityTags": [],
58 | "speedBurst": {
59 | "enabled": false
60 | }
61 | }
62 | '''
63 |
--------------------------------------------------------------------------------
/misc/findingDupIP.py:
--------------------------------------------------------------------------------
1 | #sample Source List
2 | ip_address = ["10.0.0.1", "10.0.0.1", "10.0.0.2", "12.0.3.1", "10.9.0.1", "12.0.1.1", "10.0.0.2"]
3 |
4 | ip_counts = {ip: ip_address.count(ip) for ip in set(ip_address)}
5 |
6 | for ip, count in ip_counts.items():
7 | if count > 1:
8 | print(f"Dup IP:{ip} number of dup hosts {count}")
9 | else:
10 | continue
11 |
12 |
--------------------------------------------------------------------------------
/misc/loop_thru_cli_cmds.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | cmds = sys.argv
4 |
5 | for cmd in cmds[1:]:
6 | print(cmd)
7 |
--------------------------------------------------------------------------------
/misc/loop_thru_cli_cmds_output.txt:
--------------------------------------------------------------------------------
1 |
2 | pi@raspberrypi:~/Code_folder $ python3 loop_thru_cli_cmds.py "conf t" "interface loopback0" "ip address 10.0.0.2/24" "end" "router ospf 1" "network 0.0.0.0 255.255.255.255 area 0"
3 | conf t
4 | interface loopback0
5 | ip address 10.0.0.2/24
6 | end
7 | router ospf 1
8 | network 0.0.0.0 255.255.255.255 area 0
9 | pi@raspberrypi:~/Code_folder $
10 |
--------------------------------------------------------------------------------
/napalm/config_scripts/access_list.cfg:
--------------------------------------------------------------------------------
1 | ip access-list extended test
2 | permit ip any any
3 |
4 | int loopback 2
5 | ip access-group test in
6 | ip access-group test out
7 |
--------------------------------------------------------------------------------
/napalm/config_scripts/conf_merge/eos1.txt:
--------------------------------------------------------------------------------
1 | router ospf 1
2 | network 0.0.0.0 255.255.255.255 area 0
3 |
4 |
5 | interface loopback0
6 | ip address 1.1.1.1/32
7 |
8 | interface ethernet 1
9 | no switchport
10 | ip address 10.0.0.1/24
11 | no shutdown
12 |
13 | hostname CEOS1
14 |
15 | router bgp 65000
16 | neighbor 2.2.2.2 remote-as 65000
17 | neighbor 2.2.2.2 maximum-routes 12000
18 |
19 | ip routing
20 |
--------------------------------------------------------------------------------
/napalm/config_scripts/conf_merge/eos2.txt:
--------------------------------------------------------------------------------
1 | router ospf 1
2 | network 0.0.0.0 255.255.255.255 area 0
3 |
4 |
5 | interface loopback0
6 | ip address 2.2.2.2/32
7 |
8 |
9 | interface ethernet 1
10 | no switchport
11 | ip address 10.0.0.2/24
12 | no shutdown
13 |
14 | hostname CEOS2
15 |
16 | router bgp 65000
17 | neighbor 1.1.1.1 remote-as 65000
18 | neighbor 1.1.1.1 maximum-routes 12000
19 |
20 |
21 | ip routing
22 |
--------------------------------------------------------------------------------
/napalm/config_scripts/conf_merge/napalm_cfg_merge.py:
--------------------------------------------------------------------------------
1 | from napalm import get_network_driver
2 | from pprint import pprint as pp
3 | import sys
4 | import os
5 |
6 |
7 | driver = get_network_driver('eos')
8 |
9 | eos1 = driver(hostname= 'localhost', username='arista',
10 | password='arista', optional_args={'port': 443})
11 |
12 |
13 | eos2 = driver(hostname= 'localhost', username='arista',
14 | password='arista', optional_args={'port': 8443})
15 |
16 |
17 | def eos_rtr1():
18 | eos1.open()
19 | eos1.load_merge_candidate(filename='eos1.txt')
20 | try:
21 | print(eos1.get_facts())
22 | print(eos1.compare_config())
23 | choice = input("\nWould you like to commit these changes? [yN]: ")
24 | except NameError:
25 | choice = input("\nWould you like to commit these changes? [yN]: ")
26 | if choice == 'y':
27 | print('Committing ...')
28 | eos1.commit_config()
29 | else:
30 | print('Discarding ...')
31 | eos1.discard_config()
32 | # close the session with the device.
33 | eos1.close()
34 | print('eos1 done.')
35 |
36 | def eos_rtr2():
37 | eos2.open()
38 | eos2.load_merge_candidate(filename='eos2.txt')
39 | try:
40 | print(eos2.get_facts())
41 | print(eos2.compare_config())
42 | choice = input("\nWould you like to commit these changes? [yN]: ")
43 | except NameError:
44 | choice = input("\nWould you like to commit these changes? [yN]: ")
45 | if choice == 'y':
46 | print('Committing ...')
47 | eos2.commit_config()
48 | else:
49 | print('Discarding ...')
50 | eos2.discard_config()
51 | # close the session with the device.
52 | eos2.close()
53 | print('eos2 done.')
54 |
55 |
56 | if __name__ == '__main__':
57 | eos_rtr1()
58 | eos_rtr2()
59 |
--------------------------------------------------------------------------------
/napalm/config_scripts/conf_merge/output_napalm_cfg_merge_output.txt:
--------------------------------------------------------------------------------
1 | Todds-MacBook-Pro-3:napalm_stuff toddriemenschneider$ python3 napalm_cfg_merge.py
2 | {'hostname': 'localhost', 'fqdn': 'localhost', 'vendor': 'Arista', 'model': 'cEOSSim', 'serial_number': 'N/A', 'os_version': '4.20.5F-8127914.4205F', 'uptime': 502251, 'interface_list': ['Ethernet1', 'Ethernet2']}
3 | @@ -2,6 +2,7 @@
4 | !
5 | transceiver qsfp default-mode 4x10G
6 | !
7 | +hostname CEOS1
8 | ip name-server vrf default 8.8.8.8
9 | !
10 | spanning-tree mode mstp
11 | @@ -11,15 +12,27 @@
12 | username arista privilege 15 secret sha512 $6$KHx4c.OLx8V1Zkua$SVxRaZZ8TXoJ5VO7WBODbv2k3l8hfgWDxpHmv73Tk7bVbObadcBURxymQQAOkYqtqBHMsVEh6JBHiBuyG5sag/
13 | !
14 | interface Ethernet1
15 | - shutdown
16 | + no switchport
17 | + ip address 10.0.0.1/24
18 | !
19 | interface Ethernet2
20 | +!
21 | +interface Loopback0
22 | + ip address 1.1.1.1/32
23 | !
24 | ip route 0.0.0.0/0 192.168.1.1
25 | !
26 | ip routing
27 | !
28 | +router ospf 1
29 | + network 0.0.0.0/0 area 0.0.0.0
30 | + max-lsa 12000
31 | +!
32 | management api http-commands
33 | no shutdown
34 | !
35 | +router bgp 65000
36 | + neighbor 2.2.2.2 remote-as 65000
37 | + neighbor 2.2.2.2 maximum-routes 12000
38 | +!
39 | end
40 |
41 | Would you like to commit these changes? [yN]: y
42 | Committing ...
43 | eos1 done.
44 | {'hostname': 'localhost', 'fqdn': 'localhost', 'vendor': 'Arista', 'model': 'cEOSSim', 'serial_number': 'N/A', 'os_version': '4.20.5F-8127914.4205F', 'uptime': 502256, 'interface_list': ['Ethernet1', 'Ethernet2']}
45 | @@ -2,6 +2,7 @@
46 | !
47 | transceiver qsfp default-mode 4x10G
48 | !
49 | +hostname CEOS2
50 | ip name-server vrf default 8.8.8.8
51 | !
52 | spanning-tree mode mstp
53 | @@ -11,16 +12,28 @@
54 | username arista privilege 15 secret sha512 $6$ud66axefD4jmS.Yf$zFaSScqJwDknP/gMkXmpC2pGamemMGpR05aml.cPkaujzCpXuuxfTOmU7W5ZDS66sJwwaH7PblqPtKHBXA3pl/
55 | !
56 | interface Ethernet1
57 | - shutdown
58 | + no switchport
59 | + ip address 10.0.0.2/24
60 | !
61 | interface Ethernet2
62 | +!
63 | +interface Loopback0
64 | + ip address 2.2.2.2/32
65 | !
66 | ip route 0.0.0.0/0 192.168.1.1
67 | !
68 | ip routing
69 | !
70 | +router ospf 1
71 | + network 0.0.0.0/0 area 0.0.0.0
72 | + max-lsa 12000
73 | +!
74 | management api http-commands
75 | protocol https port 8443
76 | no shutdown
77 | !
78 | +router bgp 65000
79 | + neighbor 1.1.1.1 remote-as 65000
80 | + neighbor 1.1.1.1 maximum-routes 12000
81 | +!
82 | end
83 |
84 | Would you like to commit these changes? [yN]: y
85 | Committing ...
86 | eos2 done.
87 | Todds-MacBook-Pro-3:napalm_stuff toddriemenschneider$
88 |
--------------------------------------------------------------------------------
/napalm/config_scripts/config_file.cfg:
--------------------------------------------------------------------------------
1 | ip access-list extended test
2 | permit tcp any any log
3 | exit
4 |
5 | username test secret test
6 | username arista privilege 15 secret arista
7 |
8 | router bgp 65000
9 | no network 5.5.5.5 mask 255.255.255.255
10 | network 1.1.1.1 mask 255.255.255.255
11 |
12 |
--------------------------------------------------------------------------------
/napalm/config_scripts/config_script1.py:
--------------------------------------------------------------------------------
1 | import json
2 | from napalm import get_network_driver
3 | driver = get_network_driver('eos')
4 | veos_sw = driver('veos5', 'arista', 'arista')
5 | veos_sw.open()
6 |
7 | print ('Connecting to veos device')
8 | veos_sw.load_merge_candidate(filename='config_file.cfg')
9 | veos_sw.commit_config()
10 | veos_sw.close()
11 |
12 |
--------------------------------------------------------------------------------
/napalm/config_scripts/config_script_ios.py:
--------------------------------------------------------------------------------
1 | from napalm import get_network_driver
2 | from pprint import pprint as pp
3 | from multiprocessing import Pool
4 |
5 | routers = ['r1', 'r2', 'r3', 'r4', 'r5']
6 |
7 | def run_script(router):
8 | driver = get_network_driver('ios')
9 | rtr = driver(router, 'admin', 'automate')
10 | rtr.open()
11 | print("Connected to: ", (rtr.hostname))
12 | pp(rtr.device.send_config_from_file('/home/todd/automation/napalm_stuff/access_list.cfg'))
13 | pp(rtr.device.send_config_from_file('/home/todd/automation/napalm_stuff/global_config.cfg'))
14 | pp(rtr.device.send_command('write memory'))
15 |
16 | if __name__ == "__main__":
17 | with Pool(5) as p:
18 | print(p.map(run_script, routers))
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/napalm/config_scripts/global_config.cfg:
--------------------------------------------------------------------------------
1 | ntp server 8.8.8.8
2 |
3 | username test123 password testabc
4 |
5 | logging buffered
6 |
7 |
--------------------------------------------------------------------------------
/napalm/config_scripts/output_config_script_ios.py:
--------------------------------------------------------------------------------
1 | todd@ubuntu:~/automation/napalm_stuff$ python3 config_script_ios.py
2 | Connected to: r1
3 | Connected to: r3
4 | Connected to: r2
5 | Connected to: r4
6 | Connected to: r5
7 | ('config term\n'
8 | 'Enter configuration commands, one per line. End with CNTL/Z.\n'
9 | 'R1(config)#ip access-list extended test\n'
10 | 'R1(config-ext-nacl)# permit ip any any\n'
11 | 'R1(config-ext-nacl)#\n'
12 | 'R1(config-ext-nacl)#int loopback 2\n'
13 | 'R1(config-if)# ip access-group test in\n'
14 | 'R1(config-if)# ip access-group test out\n'
15 | 'R1(config-if)#end\n'
16 | 'R1#')
17 | ('config term\n'
18 | 'Enter configuration commands, one per line. End with CNTL/Z.\n'
19 | 'R3(config)#ip access-list extended test\n'
20 | 'R3(config-ext-nacl)# permit ip any any\n'
21 | 'R3(config-ext-nacl)#\n'
22 | 'R3(config-ext-nacl)#int loopback 2\n'
23 | 'R3(config-if)# ip access-group test in\n'
24 | 'R3(config-if)# ip access-group test out\n'
25 | 'R3(config-if)#end\n'
26 | 'R3#')
27 | ('config term\n'
28 | 'Enter configuration commands, one per line. End with CNTL/Z.\n'
29 | 'R2(config)#ip access-list extended test\n'
30 | 'R2(config-ext-nacl)# permit ip any any\n'
31 | 'R2(config-ext-nacl)#\n'
32 | 'R2(config-ext-nacl)#int loopback 2\n'
33 | 'R2(config-if)# ip access-group test in\n'
34 | 'R2(config-if)# ip access-group test out\n'
35 | 'R2(config-if)#end\n'
36 | 'R2#')
37 | ('config term\n'
38 | 'Enter configuration commands, one per line. End with CNTL/Z.\n'
39 | 'R4(config)#ip access-list extended test\n'
40 | 'R4(config-ext-nacl)# permit ip any any\n'
41 | 'R4(config-ext-nacl)#\n'
42 | 'R4(config-ext-nacl)#int loopback 2\n'
43 | 'R4(config-if)# ip access-group test in\n'
44 | 'R4(config-if)# ip access-group test out\n'
45 | 'R4(config-if)#end\n'
46 | 'R4#')
47 | ('config term\n'
48 | 'Enter configuration commands, one per line. End with CNTL/Z.\n'
49 | 'R5(config)#ip access-list extended test\n'
50 | 'R5(config-ext-nacl)# permit ip any any\n'
51 | 'R5(config-ext-nacl)#\n'
52 | 'R5(config-ext-nacl)#int loopback 2\n'
53 | 'R5(config-if)# ip access-group test in\n'
54 | 'R5(config-if)# ip access-group test out\n'
55 | 'R5(config-if)#end\n'
56 | 'R5#')
57 | ('config term\n'
58 | 'Enter configuration commands, one per line. End with CNTL/Z.\n'
59 | 'R1(config)#\n'
60 | 'R1(config)#ntp server 8.8.8.8\n'
61 | 'R1(config)#\n'
62 | 'R1(config)#username test123 password testabc\n'
63 | 'R1(config)#\n'
64 | 'R1(config)#logging buffered\n'
65 | 'R1(config)#\n'
66 | 'R1(config)#\n'
67 | 'R1(config)#end\n'
68 | 'R1#')
69 | ('config term\n'
70 | 'Enter configuration commands, one per line. End with CNTL/Z.\n'
71 | 'R3(config)#\n'
72 | 'R3(config)#ntp server 8.8.8.8\n'
73 | 'R3(config)#\n'
74 | 'R3(config)#username test123 password testabc\n'
75 | 'R3(config)#\n'
76 | 'R3(config)#logging buffered\n'
77 | 'R3(config)#\n'
78 | 'R3(config)#\n'
79 | 'R3(config)#end\n'
80 | 'R3#')
81 | ('config term\n'
82 | 'Enter configuration commands, one per line. End with CNTL/Z.\n'
83 | 'R2(config)#\n'
84 | 'R2(config)#ntp server 8.8.8.8\n'
85 | 'R2(config)#\n'
86 | 'R2(config)#username test123 password testabc\n'
87 | 'R2(config)#\n'
88 | 'R2(config)#logging buffered\n'
89 | 'R2(config)#\n'
90 | 'R2(config)#\n'
91 | 'R2(config)#end\n'
92 | 'R2#')
93 | ('config term\n'
94 | 'Enter configuration commands, one per line. End with CNTL/Z.\n'
95 | 'R4(config)#\n'
96 | 'R4(config)#ntp server 8.8.8.8\n'
97 | 'R4(config)#\n'
98 | 'R4(config)#username test123 password testabc\n'
99 | 'R4(config)#\n'
100 | 'R4(config)#logging buffered\n'
101 | 'R4(config)#\n'
102 | 'R4(config)#\n'
103 | 'R4(config)#end\n'
104 | 'R4#')
105 | ('config term\n'
106 | 'Enter configuration commands, one per line. End with CNTL/Z.\n'
107 | 'R5(config)#\n'
108 | 'R5(config)#ntp server 8.8.8.8\n'
109 | 'R5(config)#\n'
110 | 'R5(config)#username test123 password testabc\n'
111 | 'R5(config)#\n'
112 | 'R5(config)#logging buffered\n'
113 | 'R5(config)#\n'
114 | 'R5(config)#\n'
115 | 'R5(config)#end\n'
116 | 'R5#')
117 | [None, None, None, None, None]
118 | todd@ubuntu:~/automation/napalm_stuff$
119 |
--------------------------------------------------------------------------------
/napalm/napalm_eos_script_ex1.py:
--------------------------------------------------------------------------------
1 | from napalm import get_network_driver
2 | from pprint import pprint
3 | from getpass import getpass
4 |
5 | def main():
6 | ips = input("Enter the ips of the devices to connect to seperated by spaces\n")
7 | un = input("Username: ")
8 | pw = getpass("Password: ")
9 | ipadd = ips.split()
10 | for ip in ipadd:
11 | print("Connecting to EOS Device:", ip)
12 | driver = get_network_driver("eos")
13 | sw = driver(ip, un, pw)
14 | sw.open()
15 | pprint(sw.get_facts())
16 | pprint(sw.get_arp_table())
17 | pprint(sw.get_config())
18 | pprint(sw.get_environment())
19 | pprint(sw.get_interfaces_ip())
20 | pprint(sw.get_lldp_neighbors_detail())
21 |
22 | if __name__ == "__main__":
23 | main()
24 |
--------------------------------------------------------------------------------
/napalm/napalm_script1.py:
--------------------------------------------------------------------------------
1 |
2 | from napalm_base import get_network_driver
3 | import napalm_ios
4 | from pprint import pprint
5 |
6 | def main():
7 | ips = input("Routers to run through (Use a space between each router): ")
8 | ipadd = ips.split()
9 | for ip in ipadd:
10 | print("connecting to router", ip)
11 | driver = get_network_driver('ios')
12 | rtr = driver(ip, 'automate', 'automation')
13 | rtr.open()
14 | pprint(rtr.get_config())
15 | interfaces = rtr.get_interfaces()
16 | pprint(interfaces)
17 | pprint(rtr.get_facts())
18 |
19 |
20 | if __name__ == "__main__":
21 | main()
22 |
23 |
--------------------------------------------------------------------------------
/napalm/script_get_cfg.py:
--------------------------------------------------------------------------------
1 | from napalm import get_network_driver
2 | from multiprocessing import Pool
3 | import json
4 |
5 | #router = input("Enter router seperated by spaces: ")
6 | #host_list = router.split()
7 |
8 | with open('/home/todd/automation/napalm_stuff/host_file') as f:
9 | host_list = f.read().splitlines()
10 |
11 | un = "admin"
12 | pw = "automate"
13 |
14 | error_list = []
15 | cmd_fail = []
16 |
17 | driver = get_network_driver('ios')
18 |
19 | def run_script(host):
20 | rtr = driver(host, un, pw)
21 | try:
22 | rtr.open()
23 | print("Connected to " + host)
24 | except:
25 | print("Unables to connect to host " + host)
26 | error_list.append(host)
27 |
28 | try:
29 | with open('config_'+ host + '.json', 'w', encoding='utf-8') as conf:
30 | rtr_configs = rtr.get_config()
31 | print(host , "startup and running config saved")
32 | json.dump(rtr_configs, conf, sort_keys = True, indent=4 , separators=(',', ': '))
33 | print("*" * 52)
34 | except Exception as cmd_err:
35 | print("Command failed", host)
36 | print(cmd_err)
37 | cmd_fail.append(cmd_err)
38 | pass
39 |
40 | return error_list, cmd_fail
41 |
42 |
43 | if __name__ == "__main__":
44 | with Pool(5) as p:
45 | print("*********************************************************************")
46 | print("This script will save the startup and running configs in json format")
47 | print("*********************************************************************")
48 | print(p.map(run_script, host_list))
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/napalm/script_get_facts.py:
--------------------------------------------------------------------------------
1 | import json
2 | from napalm import get_network_driver
3 | from multiprocessing import Pool
4 | from pprint import pprint as pp
5 |
6 | #router = input("Enter router seperated by spaces: ")
7 | #host_list = router.split()
8 |
9 | with open('host_file') as f:
10 | host_list = f.read().splitlines()
11 |
12 | un = "admin"
13 | pw = "automate"
14 |
15 | error_list = []
16 |
17 | driver = get_network_driver('ios')
18 |
19 | def run_script(host):
20 | rtr = driver(host, un, pw)
21 | try:
22 | rtr.open()
23 | print("Connected to " + host)
24 | except:
25 | print("Unables to connect to host " + host)
26 | error_list.append(host)
27 |
28 | try:
29 | with open('device_facts_'+ host + '.json', 'w', encoding='utf-8') as device:
30 | rtr_facts = rtr.get_facts()
31 | pp(rtr.get_facts())
32 | json.dump(rtr_facts, device, sort_keys = True, indent=4 , separators=(',', ': '))
33 | pp("*" * 52)
34 | except:
35 | pass
36 |
37 | return error_list
38 |
39 | if __name__ == "__main__":
40 | with Pool(5) as p:
41 | print(p.map(run_script, host_list))
42 |
--------------------------------------------------------------------------------
/napalm/svc_now/discovery_ios_svc_now.py:
--------------------------------------------------------------------------------
1 | import json
2 | from napalm import get_network_driver
3 | from multiprocessing import Pool
4 | from pprint import pprint as pp
5 |
6 | with open('host_file') as f:
7 | host_list = f.read().splitlines()
8 |
9 | un = "admin"
10 | pw = "automate"
11 |
12 | error_list = []
13 |
14 | driver = get_network_driver('ios')
15 |
16 | def run_script(host):
17 | rtr = driver(host, un, pw)
18 | try:
19 | rtr.open()
20 | print("Connected to " + host)
21 | except:
22 | print("Unables to connect to host " + host)
23 | error_list.append(host)
24 |
25 | try:
26 | with open('snow_device_facts_'+ host + '.json', 'w', encoding='utf-8') as device:
27 | rtr_facts = rtr.get_facts()
28 | rtr_facts["ip_address"] = host
29 | rtr_interface_ips = rtr.get_interfaces_ip()
30 | rtr_interfaces = rtr.get_interfaces()
31 | rtr_snmp = rtr.get_snmp_information()
32 | rtr_all = {**rtr_facts, **rtr_interface_ips, **rtr_snmp, **rtr_interfaces}
33 | pp(rtr_all)
34 | json.dump(rtr_all, device, sort_keys = True, indent=4 , separators=(',', ': '))
35 | except:
36 | pass
37 |
38 | return error_list
39 |
40 | if __name__ == "__main__":
41 | with Pool(5) as p:
42 | print(p.map(run_script, host_list))
43 |
--------------------------------------------------------------------------------
/napalm/svc_now/post_svc_now_rest_api.py:
--------------------------------------------------------------------------------
1 | import requests
2 | from getpass import getpass
3 | from pprint import pprint as pp
4 |
5 | user = ''
6 | pwd = getpass("enter password: " )
7 |
8 | with open('host_file2') as f:
9 | host_list = f.read().splitlines()
10 |
11 | print(host_list)
12 |
13 | for host in host_list:
14 | with open('snow_device_facts_'+ host + '.json', 'r', encoding='utf-8') as device:
15 | # Set the request parameters
16 | url = 'https://<>.<>.com/api/adx/external_ci_import/createCI'
17 | #url = 'https://<>.<>.com/api/now/table/cmdb_ci_netgear'
18 | # Set proper headers
19 | headers = {"Content-Type":"application/json","Accept":"application/json"}
20 | # Do the HTTP request
21 | print(device)
22 | print(host)
23 | response = requests.post(url, auth=(user, pwd), headers=headers , data=device)
24 | # Check for HTTP codes
25 | print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
26 | data = response.json()
27 | print(data)
28 |
29 |
--------------------------------------------------------------------------------
/netconf/README.md:
--------------------------------------------------------------------------------
1 | This is a work in progress.
2 |
--------------------------------------------------------------------------------
/netconf/netconf_config_bkup.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | import xml.dom.minidom
3 |
4 | HOSTS = ['ios-xe-mgmt-latest.cisco.com', 'ios-xe-mgmt.cisco.com']
5 | PORT = 10000
6 | USER = 'developer'
7 | PASS = 'C1sco12345'
8 |
9 |
10 | def main():
11 | for HOST in HOSTS:
12 | with manager.connect(host=HOST, port=PORT, username=USER,
13 | password=PASS, hostkey_verify=False,
14 | device_params={'name': 'default'},
15 | look_for_keys=False, allow_agent=False) as m:
16 | print(HOST, "- running-config copied ")
17 | config = m.get_config('running')
18 | xml_data = xml.dom.minidom.parseString(config.xml)
19 | router_configs = xml_data.toprettyxml(indent = " ")
20 | #print(router_configs)
21 | with open("config_bkups/" + HOST + "_running_config.txt", 'w') as file:
22 | file.write(router_configs)
23 |
24 |
25 | if __name__ == "__main__":
26 | main()
27 |
--------------------------------------------------------------------------------
/netconf/netconf_config_bkup_output.txt:
--------------------------------------------------------------------------------
1 | pi@RaspPi4:~/Coding/Python_folder/netOps/devnet_stuff $ cd config_bkups/
2 | pi@RaspPi4:~/Coding/Python_folder/netOps/devnet_stuff/config_bkups $ ls -l
3 | total 0
4 | pi@RaspPi4:~/Coding/Python_folder/netOps/devnet_stuff/config_bkups $ cd ..
5 | pi@RaspPi4:~/Coding/Python_folder/netOps/devnet_stuff $ python3 netconf_config_bkup.py
6 | ios-xe-mgmt-latest.cisco.com - running-config copied
7 | ios-xe-mgmt.cisco.com - running-config copied
8 | pi@RaspPi4:~/Coding/Python_folder/netOps/devnet_stuff $ cd config_bkups/
9 | pi@RaspPi4:~/Coding/Python_folder/netOps/devnet_stuff/config_bkups $ ls -l
10 | total 104
11 | -rw-r--r-- 1 pi pi 30299 Apr 9 09:40 ios-xe-mgmt.cisco.com_running_config.txt
12 | -rw-r--r-- 1 pi pi 71490 Apr 9 09:39 ios-xe-mgmt-latest.cisco.com_running_config.txt
13 | pi@RaspPi4:~/Coding/Python_folder/netOps/devnet_stuff/config_bkups $
14 |
--------------------------------------------------------------------------------
/netconf/netconf_config_device.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 |
3 |
4 | config_data = '''
5 |
6 |
7 |
8 |
9 | 70
10 | netconf is a whole lot of work to config an interface!!!!
11 |
12 |
13 |
14 | 1.1.1.70
15 | 255.255.255.255
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | '''
24 | HOST = 'ios-xe-mgmt-latest.cisco.com'
25 | PORT = 10000
26 | USER = 'developer'
27 | PASS = 'C1sco12345'
28 |
29 | def main():
30 | with manager.connect(host=HOST,
31 | port = PORT,
32 | username = USER,
33 | password = PASS,
34 | hostkey_verify=False,
35 | device_params={'name':'default'}) as m:
36 |
37 | print("This is the config to send", config_data)
38 |
39 | netconf_reply = m.edit_config(config_data, target="running")
40 |
41 | print(netconf_reply)
42 |
43 | if __name__ == "__main__":
44 | main()
45 |
--------------------------------------------------------------------------------
/netconf/netconf_config_device_output.txt:
--------------------------------------------------------------------------------
1 | pi@RaspPi4:~/Coding/Python_folder/netOps/devnet_stuff $ python3 netconf_config_device.py
2 | This is the config to send
3 |
4 |
5 |
6 |
7 | 70
8 | netconf is a whole lot of work to config an interface!!!!
9 |
10 |
11 |
12 | 1.1.1.70
13 | 255.255.255.255
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | pi@RaspPi4:~/Coding/Python_folder/netOps/devnet_stuff $
25 |
--------------------------------------------------------------------------------
/netconf/netconf_ex1.py:
--------------------------------------------------------------------------------
1 |
2 | from ncclient import manager
3 |
4 | conn = manager.connect(
5 | host='ios-xe-mgmt.cisco.com',
6 | port=10000,
7 | username="root",
8 | password="D_Vay!_10&",
9 | hostkey_verify=False,
10 | device_params={'name': 'default'},
11 | look_for_keys=False)
12 |
13 | print("Netconf_Server_capabilities")
14 | for data in conn.server_capabilities:
15 | print(data)
16 |
17 | print("*" * 50)
18 |
19 | print("Netconf_Client_capabilities")
20 | for data in conn.client_capabilities:
21 | print(data)
22 |
--------------------------------------------------------------------------------
/netconf/netconf_iosxe_cfg_bkup.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | import xml.dom.minidom
3 |
4 | USER = 'developer'
5 | PASS = 'C1sco12345'
6 |
7 |
8 |
9 | def connect(host_ip, portnum, user, pwd):
10 | with manager.connect(host=host_ip, port=portnum, username=user,
11 | password=pwd, hostkey_verify=False,
12 | device_params={'name': 'default'},
13 | look_for_keys=False, allow_agent=False) as m:
14 | print(host_ip, "- running-config copied ")
15 | config = m.get_config('running')
16 | xml_data = xml.dom.minidom.parseString(config.xml)
17 | router_configs = xml_data.toprettyxml(indent = " ")
18 | #print(router_configs)
19 | with open("config_bkups/" + host_ip + "_running_config.txt", 'w') as file:
20 | file.write(router_configs)
21 |
22 |
23 | def main():
24 | connect('sandbox-iosxe-latest-1.cisco.com', 830, USER, PASS)
25 | connect('ios-xe-mgmt.cisco.com', 10000, USER, PASS)
26 |
27 |
28 | if __name__ == "__main__":
29 | main()
30 |
31 |
32 |
33 | '''
34 | i@RaspPi4:~/Coding/Python_folder/netOps/netconf $ cd config_bkups
35 | pi@RaspPi4:~/Coding/Python_folder/netOps/netconf/config_bkups $ ls -l
36 | total 0
37 | pi@RaspPi4:~/Coding/Python_folder/netOps/netconf/config_bkups $ cd ..
38 | pi@RaspPi4:~/Coding/Python_folder/netOps/netconf $ python3 netconf_iosxe_cfg_bkup.py
39 | sandbox-iosxe-latest-1.cisco.com - running-config copied
40 | ios-xe-mgmt.cisco.com - running-config copied
41 | pi@RaspPi4:~/Coding/Python_folder/netOps/netconf $ ls -l config_bkups/
42 | total 64
43 | -rw-r--r-- 1 pi pi 17861 Jan 25 19:47 ios-xe-mgmt.cisco.com_running_config.txt
44 | -rw-r--r-- 1 pi pi 42620 Jan 25 19:47 sandbox-iosxe-latest-1.cisco.com_running_config.txt
45 | pi@RaspPi4:~/Coding/Python_folder/netOps/netconf $
46 |
47 | '''
48 |
--------------------------------------------------------------------------------
/netconf/netconf_svr_capability.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 |
3 | HOSTS = ['ios-xe-mgmt-latest.cisco.com', 'ios-xe-mgmt.cisco.com']
4 |
5 | for HOST in HOSTS:
6 | m = manager.connect(
7 | host= HOST,
8 | port=10000,
9 | username="developer",
10 | password="C1sco12345",
11 | hostkey_verify=False,
12 | device_params={'name': 'default'},
13 | look_for_keys=False)
14 |
15 | print("#" * 100)
16 | print("*" * 100)
17 | print("Netconf_Server_capabilities on :", HOST)
18 | linenum = 0
19 | for data in m.server_capabilities:
20 | linenum += 1
21 | if "http://cisco.com/ns/yang/Cisco-IOS-XE-native" in data:
22 | print(linenum, "HERES THE XMLNS YOUR USING:" ,"-----", data)
23 | else:
24 | print(linenum, data)
25 |
26 | print("Done with host: ", HOST)
27 | print("*" * 100)
28 | print("#" * 100)
29 |
--------------------------------------------------------------------------------
/netmiko/Juniper/config.txt:
--------------------------------------------------------------------------------
1 | set system host-name v-junos
2 | set interfaces et-0/0/0 description Layne_Staley
3 | set interfaces xe-0/0/1 description Mike_Patton
4 | set interfaces xe-0/0/2 description Travis_Bracht
5 | set interfaces xe-0/0/3 description Johnathon_Davis
6 |
7 |
--------------------------------------------------------------------------------
/netmiko/Juniper/juniper_conf_from_file.py:
--------------------------------------------------------------------------------
1 | #The purpose of this script is to show how to configure a juniper from a seperate config file
2 | from netmiko import ConnectHandler
3 |
4 |
5 | rtr1 = {
6 | 'device_type': 'juniper',
7 | 'ip': '127.0.0.1',
8 | 'username': 'admin',
9 | 'password': 'Juniper',
10 | 'port': 2222,
11 | 'verbose': False
12 | }
13 |
14 | net_connect = ConnectHandler(**rtr1)
15 | print("************Show commands*************")
16 | output1 = net_connect.send_command("show config| display set")
17 | output2 = net_connect.send_command("show system information | match Hostname:")
18 | print(output1)
19 | print(output2)
20 | print("*******" * 10)
21 | print("***********Config mode********")
22 | config_output = net_connect.send_config_from_file("config.txt")
23 | print(config_output)
24 | config_output1 = net_connect.config_mode()
25 | print(config_output1)
26 | config_output2 = net_connect.send_command("show|compare")
27 | print(config_output2)
28 | validate = input("Does everything look correct? (y/n): ")
29 | if validate == 'y':
30 | commit = net_connect.commit()
31 | print(commit)
32 | output3 = net_connect.disconnect()
33 | print(output3)
34 | else:
35 | output4 = net_connect.disconnect()
36 | print(output4)
37 | print("Somethings wrong with your config")
38 |
--------------------------------------------------------------------------------
/netmiko/Juniper/juniper_script1.py:
--------------------------------------------------------------------------------
1 | from netmiko import ConnectHandler
2 |
3 | # This example shows how to issue show and config commands on a juniper device
4 |
5 | rtr1 = {
6 | 'device_type': 'juniper',
7 | 'ip': '127.0.0.1',
8 | 'username': 'admin',
9 | 'password': 'Juniper',
10 | 'port': 2222,
11 | 'verbose': False
12 | }
13 |
14 | # This is the same device in my lab just using it to demonstrate what multiple devices would look like
15 | rtr2 = {
16 | 'device_type': 'juniper',
17 | 'ip': '127.0.0.1',
18 | 'username': 'admin',
19 | 'password': 'Juniper',
20 | 'port': 2222,
21 | 'verbose': False
22 | }
23 |
24 |
25 | routers = [rtr1, rtr2]
26 |
27 | for dev in routers:
28 | net_connect = ConnectHandler(**dev)
29 | print("************Show commands*************")
30 | output1 = net_connect.send_command("show config| display set")
31 | output2 = net_connect.send_command("show system information | match Hostname:")
32 | print(output1)
33 | print(output2)
34 | print("*******" * 10)
35 | print("***********Config mode********")
36 | net_connect.config_mode()
37 | config_output1 = net_connect.send_command("set interfaces et-0/0/0 description netmiko_juniper_test_script")
38 | print(config_output1)
39 | #Commit commands
40 | commit = net_connect.commit(and_quit=True)
41 | print(commit)
42 | print("************Show command*************")
43 | output3 = net_connect.send_command("show interfaces description")
44 | print(output3)
45 |
46 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/host_file_and_script/archive/discovery_script.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #(c) 2017 Todd Riemenschneider
3 | #
4 | #Enable Multiprocessing
5 | from multiprocessing import Pool
6 | #getpass will not display password
7 | from getpass import getpass
8 | #ConnectionHandler is the function used by netmiko to connect to devices
9 | from netmiko import ConnectHandler
10 | #Time tracker
11 | from time import time
12 |
13 | #create variables for username and password
14 | #create variables for configs and hosts
15 | uname = input("Username: ")
16 | passwd = getpass("Password: ")
17 | # Interactively add the hosts
18 | #host = input("Enter the host IPs seperate with space: ")
19 |
20 | #This will allow you to just press enter
21 | #This sets default values Not recommanded in any place but a lab
22 | if len(uname) < 1 : uname = "admin"
23 | if len(passwd) < 1 : passwd = "automate"
24 |
25 | #This will put hosts and commands entered into list format
26 | #hosts = host.split()
27 | # To manually add hosts to scripts just follow the format below
28 | #hosts = ["1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4"]
29 | # use hostfile
30 |
31 | with open('host_file.txt') as f:
32 | hosts = f.read().splitlines()
33 |
34 | starting_time = time()
35 |
36 | #Each member of the pool of 5 will be run through this function
37 | def run_script(host_ip):
38 | ios_rtr = {
39 | "device_type": "cisco_ios",
40 | "ip": host_ip,
41 | "username": uname,
42 | "password": passwd,
43 | }
44 | err_host = []
45 | nl = "\n"
46 | #connect to the device via ssh
47 | try:
48 | net_connect = ConnectHandler(**ios_rtr)
49 | host_name = net_connect.find_prompt()
50 | # This is the first command issued
51 | output1 = net_connect.send_command('show version', use_textfsm=False)
52 | print("Connected to host:", host_ip)
53 | print(output1)
54 | host_id = "Connected to host: " + host_ip
55 | print('\n---- Elapsed time=', time()-starting_time)
56 | # This is the second command issued
57 | output2 = net_connect.send_command('show cdp nei', use_textfsm=False)
58 | print("Connected to host:", host_ip)
59 | print(output2)
60 | host_id = "Connected to host: " + host_ip
61 | print('\n---- Elapsed time=', time()-starting_time)
62 | # This is the third command issued
63 | output3 = net_connect.send_command('show inventory', use_textfsm=False)
64 | print("Connected to host:", host_ip)
65 | print(output3)
66 | host_id = "Connected to host: " + host_ip
67 | print('\n---- Elapsed time=', time()-starting_time)
68 | # This is the fourth command issued
69 | output4 = net_connect.send_command('show run', use_textfsm=False)
70 | print("Connected to host:", host_ip)
71 | print(output4)
72 | host_id = "Connected to host: " + host_ip
73 | print('\n---- Elapsed time=', time()-starting_time)
74 | with open(host_ip + "_discovery_file.txt", 'w') as file:
75 | file.write(host_id)
76 | file.write(nl)
77 | file.write(host_name)
78 | file.write(nl)
79 | file.write(output1)
80 | file.write(nl)
81 | file.write(host_id)
82 | file.write(nl)
83 | file.write(host_name)
84 | file.write(nl)
85 | file.write(output2)
86 | file.write(nl)
87 | file.write(host_id)
88 | file.write(nl)
89 | file.write(host_name)
90 | file.write(nl)
91 | file.write(output3)
92 | file.write(nl)
93 | file.write(host_id)
94 | file.write(nl)
95 | file.write(host_name)
96 | file.write(nl)
97 | file.write(output4)
98 | file.write(nl)
99 | except Exception as unknown_error:
100 | # Error handling - Print output to screen
101 | print("************************************")
102 | print("Unable to log into this device:", host_ip)
103 | print(unknown_error)
104 | print("************************************")
105 | # Error handling - record to file
106 | with open("Connection_Errors", "a") as err_log:
107 | err_log.write("Error connecting to the following devices")
108 | err_log.write(nl)
109 | err_log.write(str(unknown_error))
110 | err_log.write(nl)
111 | err_log.write(host_ip)
112 | err_log.write(nl)
113 |
114 |
115 | if __name__ == "__main__":
116 | # Pool(5) means 5 process will be run at a time, more hosts will go in the next group
117 | with Pool(5) as p:
118 | print(p.map(run_script, hosts))
119 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/host_file_and_script/auto_detect_script.py:
--------------------------------------------------------------------------------
1 | # This script will go out and detect the device_type for any devices supported by netmiko
2 | # (c) 2018 Todd Riemenschneider
3 |
4 | from multiprocessing import Pool
5 | from netmiko.ssh_autodetect import SSHDetect
6 | from netmiko.ssh_dispatcher import ConnectHandler
7 | from getpass import getpass
8 |
9 | uname = input("Username: ")
10 | passwd = getpass("Password: ")
11 |
12 | if len(uname) < 1 : uname = "admin"
13 | if len(passwd) < 1 : passwd = "automate"
14 |
15 |
16 | with open('host_file.txt') as f:
17 | hosts = f.read().splitlines()
18 |
19 |
20 | def run_script(host_ip):
21 | remote_device = {"device_type":"autodetect",
22 | "host": host_ip,
23 | "username": uname,
24 | "password": passwd
25 | }
26 | try:
27 | guesser = SSHDetect(**remote_device)
28 | best_match = guesser.autodetect()
29 | print(best_match + " is the device_type for " + host_ip)
30 | except:
31 | print("Error connecting to " + host_ip)
32 | pass
33 |
34 | if __name__ == "__main__":
35 | # Pool(5) means 5 process will be run at a time, more hosts will go in the next group
36 | with Pool(5) as p:
37 | print(p.map(run_script, hosts))
38 |
39 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/host_file_and_script/host_file.txt:
--------------------------------------------------------------------------------
1 | r1
2 | r2
3 | bogus_rtr
4 | r3
5 | r4
6 | r5
7 | r6
8 | r7
9 | r8
10 | r9
11 | r10
12 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/host_file_and_script/ios_discovery_enable_mode.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #(c) 2017 Todd Riemenschneider
3 | #
4 | #Enable Multiprocessing
5 | from multiprocessing import Pool
6 | #getpass will not display password
7 | from getpass import getpass
8 | #ConnectionHandler is the function used by netmiko to connect to devices
9 | from netmiko import ConnectHandler
10 | #Time tracker
11 | from time import time
12 |
13 | #create variables for username and password
14 | #create variables for configs and hosts
15 | uname = input("Username: ")
16 | passwd = getpass("Password: ")
17 | enpwd = getpass("Enable Password: ")
18 |
19 | #This will allow you to just press enter
20 | #This sets default values Not recommanded in any place but a lab
21 | if len(uname) < 1 : uname = "admin"
22 | if len(passwd) < 1 : passwd = "automate"
23 |
24 | # To manually add hosts to scripts just follow the format below
25 | #hosts = ["1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4"]
26 |
27 | # Pull target hosts from host_file
28 | with open('host_file.txt') as f:
29 | hosts = f.read().splitlines()
30 |
31 | #cmds = ['show running-config', 'show version', 'show inventory', 'show interface description',
32 | # 'show ip arp', 'show ip route summary', 'show vlan brief', 'show vtp status',
33 | # 'show cdp neighbor', 'show lldp neighbor', 'show ip bgp summ', 'show ip ospf nei',
34 | # 'show ip eigrp nei', 'show interface status', 'show trunk', 'show int trunk', 'show etherchannel summ',
35 | # 'show mac address-table', 'show ip route 0.0.0.0', 'show spanning-tree brief']
36 |
37 |
38 | commands = '''
39 | show run | i hostname
40 | show run | i 255.255.
41 | dir all-filesystems
42 | show mac address-table
43 | show mac-address-table
44 | show arp
45 | show ip arp
46 | show clock
47 | show clock detail
48 | show version
49 | show boot
50 | show interfaces status
51 | show interfaces description
52 | show interfaces trunk
53 | show interfaces
54 | show interfaces transceiver detail
55 | show interfaces counters errors
56 | show int status | e not
57 | show int private-vlan mapping
58 | show vlan brief
59 | show vlan
60 | show vlan internal usage
61 | show rep topology
62 | show rep topology detail
63 | show standby brief
64 | show standby all
65 | show standby internal
66 | show standby capability
67 | show ip igmp snooping
68 | show ip igmp snooping groups
69 | show ip igmp snooping querier
70 | show ip device tracking all
71 | show running-config
72 | show run all
73 | show startup-config
74 | show spanning-tree
75 | show spanning-tree detail
76 | show spanning-tree blockedports
77 | show spanning-tree inconsistentports
78 | show logging
79 | show errdisable detect
80 | show errdisable recovery
81 | show cdp neighbors
82 | show cdp neighbors detail
83 | show lldp traffic
84 | show lldp neighbors
85 | show ip interface
86 | show ip interface brief
87 | show ip route
88 | show env all
89 | show power
90 | show sync status
91 | show switch
92 | show switch stack-ports
93 | show switch stack-ring
94 | show switch stack-ring speed
95 | show switch stack-ring activity
96 | show platform stack manager all
97 | show switch neighbors
98 | show inventory
99 | show switch detail
100 | show etherchannel summary
101 | show etherchannel detail
102 | show etherchannel protocol
103 | show memory allocating-process totals
104 | show processes cpu sorted
105 | show processes cpu sorted 5sec
106 | show processes cpu sorted 5sec | ex 0.00%_0.00%_0.00%
107 | show processes memory sorted
108 | show controller cpu-interface
109 | show ip route summary
110 | show ip traffic
111 | show platform ip unicast counts
112 | show platform ip unicast statistics
113 | show platform port-asic stats drop
114 | show platform tcam utilization
115 | show processes cpu history
116 | show sdm templates all
117 | show mls qos interface statistics
118 | show mls qos maps
119 | show diagnostic result module all
120 | show diagnostic result switch all
121 | show post
122 | show switch virtual link
123 | show switch virtual link port-channel
124 | show switch virtual link port
125 | show controllers utilization
126 | show tech-support
127 | show udld neighbors
128 | show udld fast-hello
129 | show udld fast-hello detail
130 | show dlr ring
131 | show ip dhcp binding
132 | show dlr ring 1 dhcp reference-table
133 | show dlr ring 2 dhcp reference-table
134 | show dlr ring 3 dhcp reference-table
135 | '''
136 |
137 | cmds = commands.splitlines()
138 |
139 | starting_time = time()
140 |
141 | #Each member of the pool of 5 will be run through this function
142 | def run_script(host_ip):
143 | ios_rtr = {
144 | "device_type": "cisco_ios",
145 | "ip": host_ip,
146 | "username": uname,
147 | "password": passwd,
148 | "secret": enpwd,
149 | }
150 | nl = "\n"
151 | try:
152 | #Connect to the device via ssh
153 | net_connect = ConnectHandler(**ios_rtr)
154 | net_connect.enable()
155 | host_name = net_connect.find_prompt()
156 | print("Connected to host:", host_ip)
157 | host_id = "Connected to host: " + host_ip
158 | print('\n---- Elapsed time=', time()-starting_time)
159 | for cmd in cmds:
160 | cmd_output = net_connect.send_command(cmd, use_textfsm=False)
161 | #Uncomment below to see all commands being run
162 | #print(cmd_output)
163 | with open(host_ip + "_cmds_file.txt", 'a') as file:
164 | file.write(host_id)
165 | file.write(nl)
166 | file.write(host_name)
167 | file.write(nl)
168 | file.write(cmd)
169 | file.write(nl)
170 | file.write(cmd_output)
171 | file.write(nl)
172 | file.write("**************************************")
173 | file.write(nl)
174 |
175 | except Exception as unknown_error:
176 | # Error handling - Print output to screen
177 | print("************************************")
178 | print("Unable to log into this device:", host_ip)
179 | print(unknown_error)
180 | print("************************************")
181 | # Error handling - record to file
182 | with open("Connection_Errors", "a") as err_log:
183 | err_log.write("Error connecting to the following devices")
184 | err_log.write(nl)
185 | err_log.write(str(unknown_error))
186 | err_log.write(nl)
187 | err_log.write(host_ip)
188 | err_log.write(nl)
189 |
190 |
191 |
192 |
193 |
194 | if __name__ == "__main__":
195 | # Pool(5) means 5 process will be run at a time, more hosts will go in the next group
196 | with Pool(5) as p:
197 | print(p.map(run_script, hosts))
198 |
199 |
200 |
201 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/host_file_and_script/ios_discovery_script.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #(c) 2017 Todd Riemenschneider
3 | #
4 | #Enable Multiprocessing
5 | from multiprocessing import Pool
6 | #getpass will not display password
7 | from getpass import getpass
8 | #ConnectionHandler is the function used by netmiko to connect to devices
9 | from netmiko import ConnectHandler
10 | #Time tracker
11 | from time import time
12 |
13 | #create variables for username and password
14 | #create variables for configs and hosts
15 | uname = input("Username: ")
16 | passwd = getpass("Password: ")
17 |
18 | #This will allow you to just press enter
19 | #This sets default values Not recommanded in any place but a lab
20 | if len(uname) < 1 : uname = "admin"
21 | if len(passwd) < 1 : passwd = "automate"
22 |
23 | # To manually add hosts to scripts just follow the format below
24 | #hosts = ["1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4"]
25 |
26 | # Pull target hosts from host_file
27 | with open('host_file.txt') as f:
28 | hosts = f.read().splitlines()
29 |
30 | #cmds = ['show running-config', 'show version', 'show inventory', 'show interface description',
31 | # 'show ip arp', 'show ip route summary', 'show vlan brief', 'show vtp status',
32 | # 'show cdp neighbor', 'show lldp neighbor', 'show ip bgp summ', 'show ip ospf nei',
33 | # 'show ip eigrp nei', 'show interface status', 'show trunk', 'show int trunk', 'show etherchannel summ',
34 | # 'show mac address-table', 'show ip route 0.0.0.0', 'show spanning-tree brief']
35 |
36 | commands = '''
37 | show run | i hostname
38 | show run | i 255.255.
39 | dir all-filesystems
40 | show mac address-table
41 | show mac-address-table
42 | show arp
43 | show ip arp
44 | show clock
45 | show clock detail
46 | show version
47 | show boot
48 | show interfaces status
49 | show interfaces description
50 | show interfaces trunk
51 | show interfaces
52 | show interfaces transceiver detail
53 | show interfaces counters errors
54 | show int status | e not
55 | show int private-vlan mapping
56 | show vlan brief
57 | show vlan
58 | show vlan internal usage
59 | show rep topology
60 | show rep topology detail
61 | show standby brief
62 | show standby all
63 | show standby internal
64 | show standby capability
65 | show ip igmp snooping
66 | show ip igmp snooping groups
67 | show ip igmp snooping querier
68 | show ip device tracking all
69 | show running-config
70 | show run all
71 | show startup-config
72 | show spanning-tree
73 | show spanning-tree detail
74 | show spanning-tree blockedports
75 | show spanning-tree inconsistentports
76 | show logging
77 | show errdisable detect
78 | show errdisable recovery
79 | show cdp neighbors
80 | show cdp neighbors detail
81 | show lldp traffic
82 | show lldp neighbors
83 | show ip interface
84 | show ip interface brief
85 | show ip route
86 | show env all
87 | show power
88 | show sync status
89 | show switch
90 | show switch stack-ports
91 | show switch stack-ring
92 | show switch stack-ring speed
93 | show switch stack-ring activity
94 | show platform stack manager all
95 | show switch neighbors
96 | show inventory
97 | show switch detail
98 | show etherchannel summary
99 | show etherchannel detail
100 | show etherchannel protocol
101 | show memory allocating-process totals
102 | show processes cpu sorted
103 | show processes cpu sorted 5sec
104 | show processes cpu sorted 5sec | ex 0.00%_0.00%_0.00%
105 | show processes memory sorted
106 | show controller cpu-interface
107 | show ip route summary
108 | show ip traffic
109 | show platform ip unicast counts
110 | show platform ip unicast statistics
111 | show platform port-asic stats drop
112 | show platform tcam utilization
113 | show processes cpu history
114 | show sdm templates all
115 | show mls qos interface statistics
116 | show mls qos maps
117 | show diagnostic result module all
118 | show diagnostic result switch all
119 | show post
120 | show switch virtual link
121 | show switch virtual link port-channel
122 | show switch virtual link port
123 | show controllers utilization
124 | show tech-support
125 | show udld neighbors
126 | show udld fast-hello
127 | show udld fast-hello detail
128 | show dlr ring
129 | show ip dhcp binding
130 | show dlr ring 1 dhcp reference-table
131 | show dlr ring 2 dhcp reference-table
132 | show dlr ring 3 dhcp reference-table
133 | '''
134 |
135 | cmds = commands.splitlines()
136 |
137 | starting_time = time()
138 |
139 | #Each member of the pool of 5 will be run through this function
140 | def run_script(host_ip):
141 | ios_rtr = {
142 | "device_type": "cisco_ios",
143 | "ip": host_ip,
144 | "username": uname,
145 | "password": passwd,
146 | }
147 | nl = "\n"
148 | try:
149 | #Connect to the device via ssh
150 | net_connect = ConnectHandler(**ios_rtr)
151 | host_name = net_connect.find_prompt()
152 | print("Connected to host:", host_ip)
153 | host_id = "Connected to host: " + host_ip
154 | print('\n---- Elapsed time=', time()-starting_time)
155 | for cmd in cmds:
156 | cmd_output = net_connect.send_command(cmd, use_textfsm=False)
157 | #Uncomment below to see all commands being run
158 | #print(cmd_output)
159 | with open(host_ip + "_cmds_file.txt", 'a') as file:
160 | file.write(host_id)
161 | file.write(nl)
162 | file.write(host_name)
163 | file.write(nl)
164 | file.write(cmd)
165 | file.write(nl)
166 | file.write(cmd_output)
167 | file.write(nl)
168 | file.write("**************************************")
169 | file.write(nl)
170 |
171 | except Exception as unknown_error:
172 | # Error handling - Print output to screen
173 | print("************************************")
174 | print("Unable to log into this device:", host_ip)
175 | print(unknown_error)
176 | print("************************************")
177 | # Error handling - record to file
178 | with open("Connection_Errors", "a") as err_log:
179 | err_log.write("Error connecting to the following devices")
180 | err_log.write(nl)
181 | err_log.write(str(unknown_error))
182 | err_log.write(nl)
183 | err_log.write(host_ip)
184 | err_log.write(nl)
185 |
186 |
187 | if __name__ == "__main__":
188 | # Pool(5) means 5 process will be run at a time, more hosts will go in the next group
189 | with Pool(5) as p:
190 | print(p.map(run_script, hosts))
191 |
192 |
193 |
194 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/host_file_and_script/script_output.txt:
--------------------------------------------------------------------------------
1 |
2 | todd@ubuntu:~/automation/netmiko_stuff$ ls -l
3 | total 96
4 | -rw-rw-r-- 1 todd todd 3331 Jul 30 17:28 archive_discovery_script2.py
5 | -rw-rw-r-- 1 todd todd 3395 Jul 30 17:40 archive_discovery_script3.py
6 | -rw-rw-r-- 1 todd todd 1023 Nov 14 14:03 auto_detect_script.py
7 | -rw-rw-r-- 1 todd todd 468 Nov 14 14:04 auto_detect_script_results.txt
8 | -rw-rw-r-- 1 todd todd 5690 Nov 14 13:45 Connection_Errors
9 | -rw-rw-r-- 1 todd todd 5684 Nov 14 11:41 dell_discovery_script.py
10 | -rw-rw-r-- 1 todd todd 10043 Oct 26 11:03 discovery_script2.py
11 | -rw-rw-r-- 1 todd todd 10619 Oct 26 11:28 discovery_script3.py
12 | -rw-rw-r-- 1 todd todd 4053 Oct 25 15:41 discovery_script.py
13 | -rw-rw-r-- 1 todd todd 41 Jul 31 13:41 host_file.txt
14 | -rw-rw-r-- 1 todd todd 5688 Nov 14 11:46 hp_discovery_script.py
15 | -rw-rw-r-- 1 todd todd 5683 Nov 14 13:46 ios_discovery_script.py
16 | -rw-rw-r-- 1 todd todd 1574 Jul 31 11:50 show_commands.py
17 | -rw-rw-r-- 1 todd todd 151 Oct 26 09:29 test_host
18 | -rw-rw-r-- 1 todd todd 5677 Oct 29 08:05 test_script_001.py
19 | todd@ubuntu:~/automation/netmiko_stuff$ python3 ios_discovery_script.py
20 | Username:
21 | Password:
22 | ************************************
23 | Unable to log into this device: bogus_rtr
24 | Connection to device timed-out: cisco_ios bogus_rtr:22
25 | ************************************
26 | Connected to host: r3
27 |
28 | ---- Elapsed time= 5.3688037395477295
29 | Connected to host: r4
30 |
31 | ---- Elapsed time= 5.393296241760254
32 | Connected to host: r1
33 |
34 | ---- Elapsed time= 5.74307918548584
35 | Connected to host: r2
36 |
37 | ---- Elapsed time= 5.878320932388306
38 | Connected to host: r5
39 |
40 | ---- Elapsed time= 6.15932035446167
41 | Connected to host: r6
42 |
43 | ---- Elapsed time= 88.73258543014526
44 | Connected to host: r7
45 |
46 | ---- Elapsed time= 89.67249798774719
47 | Connected to host: r8
48 |
49 | ---- Elapsed time= 91.1974241733551
50 | Connected to host: r9
51 |
52 | ---- Elapsed time= 93.47259020805359
53 | Connected to host: r10
54 |
55 | ---- Elapsed time= 104.87565612792969
56 | [None, None, None, None, None, None, None, None, None, None, None]
57 | todd@ubuntu:~/automation/netmiko_stuff$ ls -l
58 | total 4376
59 | -rw-rw-r-- 1 todd todd 3331 Jul 30 17:28 archive_discovery_script2.py
60 | -rw-rw-r-- 1 todd todd 3395 Jul 30 17:40 archive_discovery_script3.py
61 | -rw-rw-r-- 1 todd todd 1023 Nov 14 14:03 auto_detect_script.py
62 | -rw-rw-r-- 1 todd todd 468 Nov 14 14:04 auto_detect_script_results.txt
63 | -rw-rw-r-- 1 todd todd 5797 Nov 14 14:22 Connection_Errors
64 | -rw-rw-r-- 1 todd todd 5684 Nov 14 11:41 dell_discovery_script.py
65 | -rw-rw-r-- 1 todd todd 10043 Oct 26 11:03 discovery_script2.py
66 | -rw-rw-r-- 1 todd todd 10619 Oct 26 11:28 discovery_script3.py
67 | -rw-rw-r-- 1 todd todd 4053 Oct 25 15:41 discovery_script.py
68 | -rw-rw-r-- 1 todd todd 41 Jul 31 13:41 host_file.txt
69 | -rw-rw-r-- 1 todd todd 5688 Nov 14 11:46 hp_discovery_script.py
70 | -rw-rw-r-- 1 todd todd 5683 Nov 14 13:46 ios_discovery_script.py
71 | -rw-rw-r-- 1 todd todd 433203 Nov 14 14:26 r10_cmds_file.txt
72 | -rw-rw-r-- 1 todd todd 440992 Nov 14 14:24 r1_cmds_file.txt
73 | -rw-rw-r-- 1 todd todd 441972 Nov 14 14:24 r2_cmds_file.txt
74 | -rw-rw-r-- 1 todd todd 434677 Nov 14 14:24 r3_cmds_file.txt
75 | -rw-rw-r-- 1 todd todd 436756 Nov 14 14:24 r4_cmds_file.txt
76 | -rw-rw-r-- 1 todd todd 435341 Nov 14 14:24 r5_cmds_file.txt
77 | -rw-rw-r-- 1 todd todd 434058 Nov 14 14:25 r6_cmds_file.txt
78 | -rw-rw-r-- 1 todd todd 435011 Nov 14 14:25 r7_cmds_file.txt
79 | -rw-rw-r-- 1 todd todd 439256 Nov 14 14:25 r8_cmds_file.txt
80 | -rw-rw-r-- 1 todd todd 432354 Nov 14 14:26 r9_cmds_file.txt
81 | -rw-rw-r-- 1 todd todd 1574 Jul 31 11:50 show_commands.py
82 | -rw-rw-r-- 1 todd todd 151 Oct 26 09:29 test_host
83 | -rw-rw-r-- 1 todd todd 5677 Oct 29 08:05 test_script_001.py
84 | todd@ubuntu:~/automation/netmiko_stuff$
85 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/same_config_multi_device.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -----------------------------
3 | # (c) 2017 Todd Riemenschneider
4 | # -----------------------------
5 | # This script will allow up to update a group of hosts with common config shared by all
6 | # Enable Multiprocessing
7 | from multiprocessing import Pool
8 | # getpass will not display password
9 | from getpass import getpass
10 | # ConnectionHandler is the function used by netmiko to connect to devices
11 | from netmiko import ConnectHandler
12 | # Time tracker
13 | from time import time
14 |
15 | #create variables for username and password
16 | #create variables for configs and hosts
17 | uname = input("Username: ")
18 | passwd = getpass("Password: ")
19 | cmd = input("Enter config commands seperated by ',': ")
20 | host = input("Enter the host IPs seperate with space: ")
21 |
22 | #This will allow you to just press enter
23 | #This sets default values Not recommanded in any place but a lab
24 | if len(uname) < 1 : uname = "admin"
25 | if len(passwd) < 1 : passwd = "automate"
26 |
27 | #create lists of hosts and cmds to iterate through
28 | #This list can contain show or config commands show commands require "do + command"
29 | hosts = host.split()
30 | cmds = cmd.split(",")
31 |
32 | starting_time = time()
33 |
34 | #Each member of the pool of 5 will be run through this function
35 | def run_script(host_ip):
36 | ios_rtr = {
37 | "device_type": "cisco_ios",
38 | "ip": host_ip,
39 | "username": uname,
40 | "password": passwd,
41 | }
42 | #connect to the device via ssh
43 | net_connect = ConnectHandler(**ios_rtr)
44 | #print the device IP to identify which device is being configured
45 | print("Connected to host:", host_ip)
46 | #this variable is used to capture the output of cmds sent to device
47 | output = net_connect.send_config_set(cmds)
48 | #print the output
49 | print(output)
50 | print('\n---- Elapsed time=', time()-starting_time)
51 |
52 | if __name__ == "__main__":
53 | # Pool(5) means 5 process / devices will be run at a time, until youve gone through the device list
54 | with Pool(5) as p:
55 | print(p.map(run_script, hosts))
56 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/show_cdp_neighbor.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # --------------------------------------------------------------
3 | # (c) 2018 Todd Riemenschneider
4 | # This script will run through all hosts in the host file
5 | # --------------------------------------------------------------
6 | from getpass import getpass
7 | from netmiko import ConnectHandler
8 | from multiprocessing import Pool
9 | from time import time
10 |
11 | # Login info
12 | username = input('Enter username: ')
13 | password = getpass('Enter password: ')
14 |
15 | # Useful in a lab setting not production
16 | if len(username) < 1 : username = "admin"
17 | if len(password) < 1 : password = "automate"
18 |
19 | # Target hosts
20 | with open('host_file') as f:
21 | host_file = f.read().splitlines()
22 |
23 | show_commands = "show cdp neighbor"
24 | err_host = []
25 |
26 | print("----The devices being configured----")
27 | print(host_file)
28 |
29 | starting_time = time()
30 |
31 | # Updated /etc/hosts to use host names rather than host ips
32 |
33 | def run_script(hostname):
34 | print ('Connecting to device: ' + hostname)
35 | ios_device = {
36 | 'device_type': 'cisco_ios',
37 | 'ip': hostname,
38 | 'username': username,
39 | 'password': password
40 | }
41 | try:
42 | net_connect = ConnectHandler(**ios_device)
43 | except Exception as unknown_error:
44 | print("************************************")
45 | print("Unable to log into this device:", hostname)
46 | print(unknown_error)
47 | err_host.append(hostname)
48 | print("Errors logging into:", err_host)
49 | print("************************************")
50 | pass
51 |
52 | try:
53 | output = net_connect.send_command(show_commands)
54 | print("++++++++++++++++++++++++++++++++++++++++")
55 | print("Connected to host: ", hostname)
56 | print("Command issued:",show_commands)
57 | print("++++++++++++++++++++++++++++++++++++++++")
58 | print(output)
59 | print("++++++++++++++++++++++++++++++++++++++++")
60 | print("End of configs for device", hostname)
61 | print("****************************************")
62 | except Exception as unknown_error:
63 | pass
64 | print("Errors logging into:" , err_host)
65 | # Used to determine how long it takes for the script to run/complete
66 | print('\n---- Elapsed time=', time()-starting_time)
67 |
68 | #Used to set up MP Pools to increase performance
69 | #Specify number of process in the pool to run at same time
70 | #There is no recommendation really trial error as to the right number
71 | if __name__ == "__main__":
72 | with Pool(5) as p:
73 | print(p.map(run_script, host_file))
74 |
75 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/show_commands.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #(c) 2017 Todd Riemenschneider
3 | #
4 | #This script will allow for user pick hosts and enter show commands interactively
5 | #
6 | #Enable Multiprocessing
7 | from multiprocessing import Pool
8 | #
9 | #getpass will not display password
10 | from getpass import getpass
11 | #ConnectionHandler is the function used by netmiko to connect to devices
12 | from netmiko import ConnectHandler
13 | #Time tracker
14 | from time import time
15 |
16 | #create variables for username and password
17 | #create variables for configs and hosts
18 | uname = input("Username: ")
19 | passwd = getpass("Password: ")
20 | cmd = input("Enter commands seperated by ',': ")
21 | host = input("Enter the host IPs seperate with space: ")
22 |
23 | #This will allow you to just press enter
24 | #This sets default values Not recommanded in any place but a lab
25 | if len(uname) < 1 : uname = "admin"
26 | if len(passwd) < 1 : passwd = "automate"
27 |
28 | #This will put hosts and commands entered into list format
29 | hosts = host.split()
30 | cmds = cmd.split(",")
31 |
32 | starting_time = time()
33 |
34 | #Each member of the pool of 5 will be run through this function
35 | def run_script(host_ip):
36 | ios_rtr = {
37 | "device_type": "cisco_xe",
38 | "ip": host_ip,
39 | "username": uname,
40 | "password": passwd,
41 | "port" : 8181
42 | }
43 | #connect to the device via ssh
44 | net_connect = ConnectHandler(**ios_rtr)
45 | #print the device IP or Hostname
46 | print("Connected to host:", host_ip)
47 | #this for loop is used to iterate through the show commands
48 | for show_commands in cmds:
49 | output = net_connect.send_command(show_commands)
50 | print("Connected to host:", host_ip)
51 | print("Command: ", show_commands, "\n", output)
52 | print('\n---- Elapsed time=', time()-starting_time)
53 |
54 | if __name__ == "__main__":
55 | # Pool(5) means 5 process will be run at a time, more hosts will go in the next group
56 | with Pool(5) as p:
57 | print(p.map(run_script, hosts))
58 |
59 |
60 | #This is the key to sending show commands vs config commands
61 | #show commands --> net_connect.send_command()
62 | #config commmands --> net_connect.send_config_set()
63 |
64 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/show_ip_bgp_summ.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # --------------------------------------------------------------
3 | # (c) 2018 Todd Riemenschneider
4 | # Script will run through all hosts in the host_file
5 | # --------------------------------------------------------------
6 | from getpass import getpass
7 | from netmiko import ConnectHandler
8 | from multiprocessing import Pool
9 | from time import time
10 |
11 | # Login info
12 | username = input('Enter username: ')
13 | password = getpass('Enter password: ')
14 |
15 | # Useful in a lab setting not production
16 | if len(username) < 1 : username = "admin"
17 | if len(password) < 1 : password = "automate"
18 |
19 | # Target hosts
20 | with open('host_file') as f:
21 | host_file = f.read().splitlines()
22 |
23 | show_commands = "show ip bgp summary"
24 | err_host = []
25 |
26 | print("----The devices being configured----")
27 | print(host_file)
28 |
29 | starting_time = time()
30 |
31 | # Updated /etc/hosts to use host names rather than host ips
32 |
33 | def run_script(hostname):
34 | print ('Connecting to device: ' + hostname)
35 | ios_device = {
36 | 'device_type': 'cisco_ios',
37 | 'ip': hostname,
38 | 'username': username,
39 | 'password': password
40 | }
41 | try:
42 | net_connect = ConnectHandler(**ios_device)
43 | except Exception as unknown_error:
44 | print("************************************")
45 | print("Unable to log into this device:", hostname)
46 | print(unknown_error)
47 | err_host.append(hostname)
48 | print("Errors logging into:", err_host)
49 | print("************************************")
50 | pass
51 |
52 |
53 | try:
54 | output = net_connect.send_command(show_commands)
55 | print("++++++++++++++++++++++++++++++++++++++++")
56 | print("Connected to host: ", hostname)
57 | print("Command issued:",show_commands)
58 | print("++++++++++++++++++++++++++++++++++++++++")
59 | print(output)
60 | print("++++++++++++++++++++++++++++++++++++++++")
61 | print("End of configs for device", hostname)
62 | print("****************************************")
63 | except Exception as unknown_error:
64 | pass
65 | print("Errors logging into:" , err_host)
66 | # Used to determine how long it takes for the script to run/complete
67 | print('\n---- Elapsed time=', time()-starting_time)
68 |
69 | #Used to set up MP Pools to increase performance
70 | #Specify number of process in the pool to run at same time
71 | #There is no recommendation really trial error as to the right number
72 | if __name__ == "__main__":
73 | with Pool(5) as p:
74 | print(p.map(run_script, host_file))
75 |
76 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/show_ip_int_brief:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # --------------------------------------------------------------
3 | # (c) 2018 Todd Riemenschneider
4 | # Script will run through all hosts in the host_file
5 | # --------------------------------------------------------------
6 | from getpass import getpass
7 | from netmiko import ConnectHandler
8 | from multiprocessing import Pool
9 | from time import time
10 |
11 | # Login info
12 | username = input('Enter username: ')
13 | password = getpass('Enter password: ')
14 |
15 | # Useful in a lab setting not production
16 | if len(username) < 1 : username = "admin"
17 | if len(password) < 1 : password = "automate"
18 |
19 | # Target hosts
20 | with open('host_file') as f:
21 | host_file = f.read().splitlines()
22 |
23 | show_commands = "show ip int brief"
24 | err_host = []
25 |
26 | print("----The devices being configured----")
27 | print(host_file)
28 |
29 | starting_time = time()
30 |
31 | # Updated /etc/hosts to use host names rather than host ips
32 |
33 | def run_script(hostname):
34 | print ('Connecting to device: ' + hostname)
35 | ios_device = {
36 | 'device_type': 'cisco_ios',
37 | 'ip': hostname,
38 | 'username': username,
39 | 'password': password
40 | }
41 | try:
42 | net_connect = ConnectHandler(**ios_device)
43 | except Exception as unknown_error:
44 | print("************************************")
45 | print("Unable to log into this device:", hostname)
46 | print(unknown_error)
47 | err_host.append(hostname)
48 | print("Errors logging into:", err_host)
49 | print("************************************")
50 | pass
51 |
52 | try:
53 | output = net_connect.send_command(show_commands)
54 | print("++++++++++++++++++++++++++++++++++++++++")
55 | print("Connected to host: ", hostname)
56 | print("Command issued:",show_commands)
57 | print("++++++++++++++++++++++++++++++++++++++++")
58 | print(output)
59 | print("++++++++++++++++++++++++++++++++++++++++")
60 | print("End of configs for device", hostname)
61 | print("****************************************")
62 | except Exception as unknown_error:
63 | pass
64 | print("Errors logging into:" , err_host)
65 | # Used to determine how long it takes for the script to run/complete
66 | print('\n---- Elapsed time=', time()-starting_time)
67 |
68 | #Used to set up MP Pools to increase performance
69 | #Specify number of process in the pool to run at same time
70 | #There is no recommendation really trial error as to the right number
71 | if __name__ == "__main__":
72 | with Pool(7) as p:
73 | print(p.map(run_script, host_file))
74 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/show_ip_route.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # --------------------------------------------------------------
3 | # (c) 2018 Todd Riemenschneider
4 | # This script will run through all hosts in the host_file
5 | # --------------------------------------------------------------
6 | from getpass import getpass
7 | from netmiko import ConnectHandler
8 | from multiprocessing import Pool
9 | from time import time
10 |
11 | # Login info
12 | username = input('Enter username: ')
13 | password = getpass('Enter password: ')
14 |
15 | # Useful in a lab setting not production
16 | if len(username) < 1 : username = "admin"
17 | if len(password) < 1 : password = "automate"
18 |
19 | # Target hosts
20 | with open('host_file') as f:
21 | host_file = f.read().splitlines()
22 |
23 | show_commands = "show ip route"
24 | err_host = []
25 |
26 | print("----The devices being configured----")
27 | print(host_file)
28 |
29 | starting_time = time()
30 |
31 | # Updated /etc/hosts to use host names rather than host ips
32 |
33 | def run_script(hostname):
34 | print ('Connecting to device: ' + hostname)
35 | ios_device = {
36 | 'device_type': 'cisco_ios',
37 | 'ip': hostname,
38 | 'username': username,
39 | 'password': password
40 | }
41 | try:
42 | net_connect = ConnectHandler(**ios_device)
43 | except Exception as unknown_error:
44 | print("************************************")
45 | print("Unable to log into this device:", hostname)
46 | print(unknown_error)
47 | err_host.append(hostname)
48 | print("Errors logging into:", err_host)
49 | print("************************************")
50 | pass
51 |
52 | try:
53 | output = net_connect.send_command(show_commands)
54 | print("++++++++++++++++++++++++++++++++++++++++")
55 | print("Connected to host: ", hostname)
56 | print("Command issued:",show_commands)
57 | print("++++++++++++++++++++++++++++++++++++++++")
58 | print(output)
59 | print("++++++++++++++++++++++++++++++++++++++++")
60 | print("End of configs for device", hostname)
61 | print("****************************************")
62 | except Exception as unknown_error:
63 | pass
64 | print("Errors logging into:" , err_host)
65 | # Used to determine how long it takes for the script to run/complete
66 | print('\n---- Elapsed time=', time()-starting_time)
67 |
68 | #Used to set up MP Pools to increase performance
69 | #Specify number of process in the pool to run at same time
70 | #There is no recommendation really trial error as to the right number
71 | if __name__ == "__main__":
72 | with Pool(5) as p:
73 | print(p.map(run_script, host_file))
74 |
75 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/show_run.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # --------------------------------------------------------------
3 | # (c) 2018 Todd Riemenschneider
4 | # script will run through all hosts in the host_file
5 | # --------------------------------------------------------------
6 | from getpass import getpass
7 | from netmiko import ConnectHandler
8 | from multiprocessing import Pool
9 | from time import time
10 |
11 | # Login info
12 | username = input('Enter username: ')
13 | password = getpass('Enter password: ')
14 |
15 | # Useful in a lab setting not production
16 | if len(username) < 1 : username = "admin"
17 | if len(password) < 1 : password = "automate"
18 |
19 | # Target hosts
20 | with open('host_file') as f:
21 | host_file = f.read().splitlines()
22 |
23 | show_commands = "show run"
24 | err_host = []
25 |
26 | print("----The devices being configured----")
27 | print(host_file)
28 |
29 | starting_time = time()
30 |
31 | # Updated /etc/hosts to use host names rather than host ips
32 |
33 | def run_script(hostname):
34 | print ('Connecting to device: ' + hostname)
35 | ios_device = {
36 | 'device_type': 'cisco_ios',
37 | 'ip': hostname,
38 | 'username': username,
39 | 'password': password
40 | }
41 | try:
42 | net_connect = ConnectHandler(**ios_device)
43 | except Exception as unknown_error:
44 | print("************************************")
45 | print("Unable to log into this device:", hostname)
46 | print(unknown_error)
47 | err_host.append(hostname)
48 | print("Errors logging into:", err_host)
49 | print("************************************")
50 | pass
51 |
52 | try:
53 | output = net_connect.send_command(show_commands)
54 | print("++++++++++++++++++++++++++++++++++++++++")
55 | print("Connected to host: ", hostname)
56 | print("Command issued:",show_commands)
57 | print("++++++++++++++++++++++++++++++++++++++++")
58 | print(output)
59 | print("++++++++++++++++++++++++++++++++++++++++")
60 | print("End of configs for device", hostname)
61 | print("****************************************")
62 | except Exception as unknown_error:
63 | pass
64 | print("Errors logging into:" , err_host)
65 | # Used to determine how long it takes for the script to run/complete
66 | print('\n---- Elapsed time=', time()-starting_time)
67 |
68 | #Used to set up MP Pools to increase performance
69 | #Specify number of process in the pool to run at same time
70 | #There is no recommendation really trial error as to the right number
71 | if __name__ == "__main__":
72 | with Pool(5) as p:
73 | print(p.map(run_script, host_file))
74 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/show_uptime.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # --------------------------------------------------------------
3 | # (c) 2018 Todd Riemenschneider
4 | # This script will run through all the hosts in the host_file
5 | # --------------------------------------------------------------
6 | from getpass import getpass
7 | from netmiko import ConnectHandler
8 | from multiprocessing import Pool
9 | from time import time
10 |
11 | # Login info
12 | username = input('Enter username: ')
13 | password = getpass('Enter password: ')
14 |
15 | # Useful in a lab setting not production
16 | if len(username) < 1 : username = "admin"
17 | if len(password) < 1 : password = "automate"
18 |
19 | # Target hosts
20 | with open('host_file') as f:
21 | host_file = f.read().splitlines()
22 |
23 | show_commands = "show version | inc uptime"
24 | err_host = []
25 |
26 | print("----The devices being configured----")
27 | print(host_file)
28 |
29 | starting_time = time()
30 |
31 | # Updated /etc/hosts to use host names rather than host ips
32 |
33 | def run_script(hostname):
34 | print ('Connecting to device: ' + hostname)
35 | ios_device = {
36 | 'device_type': 'cisco_ios',
37 | 'ip': hostname,
38 | 'username': username,
39 | 'password': password
40 | }
41 | try:
42 | net_connect = ConnectHandler(**ios_device)
43 | except Exception as unknown_error:
44 | print("************************************")
45 | print("Unable to log into this device:", hostname)
46 | print(unknown_error)
47 | err_host.append(hostname)
48 | print("Errors logging into:", err_host)
49 | print("************************************")
50 | pass
51 | try:
52 | output = net_connect.send_command(show_commands)
53 | print("++++++++++++++++++++++++++++++++++++++++")
54 | print("Connected to host: ", hostname)
55 | print("Command issued:",show_commands)
56 | print("++++++++++++++++++++++++++++++++++++++++")
57 | print(output)
58 | print("++++++++++++++++++++++++++++++++++++++++")
59 | print("End of configs for device", hostname)
60 | print("****************************************")
61 | except Exception as unknown_error:
62 | pass
63 | print("Errors logging into:" , err_host)
64 | # Used to determine how long it takes for the script to run/complete
65 | print('\n---- Elapsed time=', time()-starting_time)
66 |
67 | #Used to set up MP Pools to increase performance
68 | #Specify number of process in the pool to run at same time
69 | #There is no recommendation really trial error as to the right number
70 | if __name__ == "__main__":
71 | with Pool(5) as p:
72 | print(p.map(run_script, host_file))
73 |
74 |
--------------------------------------------------------------------------------
/netmiko/NetworkDiscovery/show_version.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # --------------------------------------------------------------
3 | # (c) 2018 Todd Riemenschneider
4 | # This script will run through all hosts in the host_file
5 | # --------------------------------------------------------------
6 | from getpass import getpass
7 | from netmiko import ConnectHandler
8 | from multiprocessing import Pool
9 | from time import time
10 |
11 | # Login info
12 | username = input('Enter username: ')
13 | password = getpass('Enter password: ')
14 |
15 | # Useful in a lab setting not production
16 | if len(username) < 1 : username = "admin"
17 | if len(password) < 1 : password = "automate"
18 |
19 | # Target hosts
20 | with open('host_file') as f:
21 | host_file = f.read().splitlines()
22 |
23 | show_commands = "show version"
24 | err_host = []
25 |
26 | print("----The devices being configured----")
27 | print(host_file)
28 |
29 | starting_time = time()
30 |
31 | # Updated /etc/hosts to use host names rather than host ips
32 |
33 | def run_script(hostname):
34 | print ('Connecting to device: ' + hostname)
35 | ios_device = {
36 | 'device_type': 'cisco_ios',
37 | 'ip': hostname,
38 | 'username': username,
39 | 'password': password
40 | }
41 | try:
42 | net_connect = ConnectHandler(**ios_device)
43 | except Exception as unknown_error:
44 | print("************************************")
45 | print("Unable to log into this device:", hostname)
46 | print(unknown_error)
47 | err_host.append(hostname)
48 | print("Errors logging into:", err_host)
49 | print("************************************")
50 | pass
51 |
52 | try:
53 | output = net_connect.send_command(show_commands)
54 | print("++++++++++++++++++++++++++++++++++++++++")
55 | print("Connected to host: ", hostname)
56 | print("Command issued:",show_commands)
57 | print("++++++++++++++++++++++++++++++++++++++++")
58 | print(output)
59 | print("++++++++++++++++++++++++++++++++++++++++")
60 | print("End of configs for device", hostname)
61 | print("****************************************")
62 | except Exception as unknown_error:
63 | pass
64 | print("Errors logging into:" , err_host)
65 | # Used to determine how long it takes for the script to run/complete
66 | print('\n---- Elapsed time=', time()-starting_time)
67 |
68 | #Used to set up MP Pools to increase performance
69 | #Specify number of process in the pool to run at same time
70 | #There is no recommendation really trial error as to the right number
71 | if __name__ == "__main__":
72 | with Pool(5) as p:
73 | print(p.map(run_script, host_file))
74 |
75 |
--------------------------------------------------------------------------------
/netmiko/Normal processing vs multi-processing pools:
--------------------------------------------------------------------------------
1 | **************************************
2 | With out multiprocessing Pools enabled
3 | **************************************
4 |
5 | root@debian:/home/todd/gns3# ./netmiko_script3.py
6 | Username:
7 | Password:
8 | Enter config commands seperated by ',': interface loopback 0, description this is a test
9 | Enter the host IPs seperate with space: r1 r2 r3 r4 r5
10 | Connected to host: r1
11 | config term
12 | Enter configuration commands, one per line. End with CNTL/Z.
13 | R1(config)#interface loopback 0
14 | R1(config-if)# description this is a test
15 | R1(config-if)#end
16 | R1#
17 |
18 | ---- Elapsed time= 8.551600694656372
19 | Connected to host: r2
20 | config term
21 | Enter configuration commands, one per line. End with CNTL/Z.
22 | R2(config)#interface loopback 0
23 | R2(config-if)# description this is a test
24 | R2(config-if)#end
25 | R2#
26 |
27 | ---- Elapsed time= 17.07494831085205
28 | Connected to host: r3
29 | config term
30 | Enter configuration commands, one per line. End with CNTL/Z.
31 | R3(config)#interface loopback 0
32 | R3(config-if)# description this is a test
33 | R3(config-if)#end
34 | R3#
35 |
36 | ---- Elapsed time= 25.575489044189453
37 | Connected to host: r4
38 | config term
39 | Enter configuration commands, one per line. End with CNTL/Z.
40 | R4(config)#interface loopback 0
41 | R4(config-if)# description this is a test
42 | R4(config-if)#end
43 | R4#
44 |
45 | ---- Elapsed time= 34.04974317550659
46 | Connected to host: r5
47 | config term
48 | Enter configuration commands, one per line. End with CNTL/Z.
49 | R5(config)#interface loopback 0
50 | R5(config-if)# description this is a test
51 | R5(config-if)#end
52 | R5#
53 |
54 | ---- Elapsed time= 42.538753032684326
55 |
56 | **********************************
57 | With Multiprocessing pools enabled
58 | **********************************
59 |
60 | root@debian:/home/todd/gns3# ./netmiko_conf_mp_pools.py
61 | Username:
62 | Password:
63 | Enter config commands seperated by ',': interface loopback 1, description this is a test
64 | Enter the host IPs seperate with space: r1 r2 r3 r4 r5
65 | Connected to host: r3
66 | Connected to host: r2
67 | Connected to host: r1
68 | Connected to host: r5
69 | Connected to host: r4
70 | config term
71 | Enter configuration commands, one per line. End with CNTL/Z.
72 | R3(config)#interface loopback 1
73 | R3(config-if)# description this is a test
74 | R3(config-if)#end
75 | R3#
76 |
77 | ---- Elapsed time= 8.392916917800903
78 | config term
79 | Enter configuration commands, one per line. End with CNTL/Z.
80 | R2(config)#interface loopback 1
81 | R2(config-if)# description this is a test
82 | R2(config-if)#end
83 | R2#
84 |
85 | ---- Elapsed time= 8.500743627548218
86 | config term
87 | Enter configuration commands, one per line. End with CNTL/Z.
88 | R1(config)#interface loopback 1
89 | R1(config-if)# description this is a test
90 | R1(config-if)#end
91 | R1#
92 |
93 | ---- Elapsed time= 8.696260690689087
94 | config term
95 | Enter configuration commands, one per line. End with CNTL/Z.
96 | R5(config)#interface loopback 1
97 | R5(config-if)# description this is a test
98 | R5(config-if)#end
99 | R5#
100 |
101 | ---- Elapsed time= 8.971424341201782
102 | config term
103 | Enter configuration commands, one per line. End with CNTL/Z.
104 | R4(config)#interface loopback 1
105 | R4(config-if)# description this is a test
106 | R4(config-if)#end
107 | R4#
108 |
109 | ---- Elapsed time= 9.040150880813599
110 | [None, None, None, None, None]
111 | root@debian:/home/todd/gns3#
112 |
--------------------------------------------------------------------------------
/netmiko/archive/clean_up_lab.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # --------------------------------------------------------------
3 | #(c) 2017 Todd Riemenschneider
4 | # This script will allow you to configure multiple devices with
5 | # different configurations on each
6 | # --------------------------------------------------------------
7 | from getpass import getpass
8 | from netmiko import ConnectHandler
9 | from multiprocessing import Pool
10 | from time import time
11 |
12 | # Login info
13 | username = input('Enter username: ')
14 | password = getpass('Enter password: ')
15 |
16 | # Useful in a lab setting not production
17 | if len(username) < 1 : username = "admin"
18 | if len(password) < 1 : password = "automate"
19 |
20 | # Command files
21 | with open('remove_commands_file_r1') as f:
22 | remove_commands_list_r1 = f.read().splitlines()
23 |
24 | with open('remove_commands_file_r2') as f:
25 | remove_commands_list_r2 = f.read().splitlines()
26 |
27 | with open('remove_commands_file_r3') as f:
28 | remove_commands_list_r3 = f.read().splitlines()
29 |
30 | with open('remove_commands_file_r4') as f:
31 | remove_commands_list_r4 = f.read().splitlines()
32 |
33 | with open('remove_commands_file_r5') as f:
34 | remove_commands_list_r5 = f.read().splitlines()
35 |
36 | #with open('commands_file_r6') as f:
37 | # commands_list_r6 = f.read().splitlines()
38 |
39 | #with open('commands_file_r7') as f:
40 | # commands_list_r7 = f.read().splitlines()
41 |
42 | # Target hosts
43 | with open('host_file') as f:
44 | host_file = f.read().splitlines()
45 |
46 | print("----The devices being configured----")
47 | print(host_file)
48 |
49 | starting_time = time()
50 |
51 | # Updated /etc/hosts to use host names rather than host ips
52 |
53 | def run_script(hostname):
54 | print ('Connecting to device: ' + hostname)
55 | ios_device = {
56 | 'device_type': 'cisco_ios',
57 | 'ip': hostname,
58 | 'username': username,
59 | 'password': password
60 | }
61 | # Command to connect to hosts
62 | net_connect = ConnectHandler(**ios_device)
63 |
64 | # Logic used to connect host to configuration file
65 | # Updated host_file with hostname like r1 r2 r3 r4 r5
66 | # If we went by ip address we would need to update hostname == "10.0.0.1" for r1
67 | #if hostname == '10.0.0.1':
68 | # print("hostname == 10.0.0.1:", hostname == '10.0.0.1')
69 | # output = net_connect.send_config_set(commands_list_r1)
70 | # print(output)
71 | if hostname == 'r1':
72 | print("hostname == r1:", hostname == 'r1')
73 | output = net_connect.send_config_set(remove_commands_list_r1)
74 | print(output)
75 | elif hostname == 'r2':
76 | print ("hostname == r2:", hostname == 'r2')
77 | output = net_connect.send_config_set(remove_commands_list_r2)
78 | print(output)
79 | elif hostname == 'r3':
80 | print ("hostname == r3: ", hostname == 'r3')
81 | output = net_connect.send_config_set(remove_commands_list_r3)
82 | print(output)
83 | elif hostname == 'r4':
84 | print ("hostname == r4:", hostname == 'r4')
85 | output = net_connect.send_config_set(remove_commands_list_r4)
86 | print(output)
87 | elif hostname == 'r5':
88 | print ("hostname == r5:", hostname == 'r5')
89 | output = net_connect.send_config_set(remove_commands_list_r5)
90 | print(output)
91 | # elif hostname == 'r6':
92 | # print ("hostname == r6: ", hostname == 'r6')
93 | # output = net_connect.send_config_set(commands_list_r6)
94 | # print(output)
95 | # elif hostname == 'r7':
96 | # print ("hostname == r7: ", hostname == 'r7')
97 | # output = net_connect.send_config_set(commands_list_r7)
98 | # print(output)
99 | # Used to determine how long it takes for the script to run/complete
100 | print('\n---- Elapsed time=', time()-starting_time)
101 |
102 | #Used to set up MP Pools to increase performance
103 | #Specify number of process in the pool to run at same time
104 | #There is no recommendation really trial error as to the right number
105 | if __name__ == "__main__":
106 | with Pool(7) as p:
107 | print(p.map(run_script, host_file))
108 |
--------------------------------------------------------------------------------
/netmiko/archive/netmiko_script2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #(c) 2017 Todd Riemenschneider
3 |
4 | #getpass will not display password
5 | from getpass import getpass
6 | #ConnectionHandler is the function used by netmiko to connect to devices
7 | from netmiko import ConnectHandler
8 |
9 | #create variables for username and password
10 | uname = input("Username: ")
11 | passwd = getpass("Password: ")
12 | cmds = input("Enter file name of configuration file: ")
13 | hostfile = input("Enter the name of file that has the devices: ")
14 |
15 | #This will allow you to just press enter
16 | #This sets default values Not recommanded in any place but a lab
17 | if len(uname) < 1 : uname = "automate"
18 | if len(passwd) < 1 : passwd = "automation"
19 | if len(cmds) < 1 : cmds = "commands.txt"
20 | if len(hostfile) < 1 : hostfile = "devices.txt"
21 |
22 | #with is used to open and automatically close files
23 | #The commands.txt has all configuration commands
24 | #To view status use the do + show command
25 | with open(cmds) as f:
26 | cmds_to_send = f.read().splitlines()
27 |
28 | with open(hostfile) as f:
29 | hosts = f.read().splitlines()
30 |
31 |
32 | #use a for loop to iterate through the devices
33 | for host in hosts:
34 | host_ip = host
35 | ios_rtr = {
36 | "device_type": "cisco_ios",
37 | "ip": host_ip,
38 | "username": uname,
39 | "password": passwd,
40 | }
41 |
42 | #connect to the device via ssh
43 | net_connect = ConnectHandler(**ios_rtr)
44 | #print the device IP to identify which device is being configured
45 | print("Connected to host:", host_ip)
46 | #this variable is used to capture the output of cmds sent to device
47 | output = net_connect.send_config_set(cmds_to_send)
48 | #print the output
49 | print(output)
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/netmiko/archive/netmiko_script3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #(c) 2017 Todd Riemenschneider
3 | #This script will allow up to update a group of hosts with common config shared by all
4 | #
5 | #getpass will not display password
6 | from getpass import getpass
7 | #ConnectionHandler is the function used by netmiko to connect to devices
8 | from netmiko import ConnectHandler
9 |
10 | #create variables for username and password
11 | #create variables for configs and hosts
12 | uname = input("Username: ")
13 | passwd = getpass("Password: ")
14 | cmd = input("Enter config commands seperated by ',': ")
15 | host = input("Enter the DNS hostnames or IPs seperated by a space: ")
16 |
17 | #This will allow you to just press enter
18 | #This sets default values Not recommanded in any place but a lab
19 | if len(uname) < 1 : uname = "automate"
20 | if len(passwd) < 1 : passwd = "automation"
21 |
22 | #create lists of hosts and cmds to iterate through
23 | #This list can contain show or config commands show commands require "do + command"
24 | hosts = host.split()
25 | cmds = cmd.split(",")
26 |
27 | #For loop used to iterate through the devices
28 | for host in hosts:
29 | host_ip = host
30 | ios_rtr = {
31 | "device_type": "cisco_ios",
32 | "ip": host_ip,
33 | "username": uname,
34 | "password": passwd,
35 | }
36 | #connect to the device via ssh
37 | net_connect = ConnectHandler(**ios_rtr)
38 | #print the device IP to identify which device is being configured
39 | print("Connected to host:", host_ip)
40 | #this variable is used to capture the output of cmds sent to device
41 | output = net_connect.send_config_set(cmds)
42 | #print the output
43 | print(output)
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/netmiko/archive/output_netmiko_multi_dev_cfg:
--------------------------------------------------------------------------------
1 | root@debian:/home/todd/gns3/GoldConf# python3 netmiko_multi_dev_cfg.py
2 | Enter username:
3 | Enter password:
4 | ----The devices being configured----
5 | ['r4', 'r2', 'r3', 'r1', 'r5', 'r6', 'r7']
6 | Connecting to device: r4
7 | Connecting to device: r2
8 | Connecting to device: r3
9 | Connecting to device: r1
10 | Connecting to device: r5
11 | Connecting to device: r6
12 | Connecting to device: r7
13 | hostname == r2: True
14 | hostname == r5: True
15 | hostname == r1: True
16 | hostname == r3: True
17 | hostname == r7: True
18 | hostname == r4: True
19 | hostname == r6: True
20 | config term
21 | Enter configuration commands, one per line. End with CNTL/Z.
22 | R2(config)#int loopback 0
23 | R2(config-if)# ip address 2.2.2.2 255.255.255.255
24 | R2(config-if)# description automated configuration
25 | R2(config-if)#end
26 | R2#
27 |
28 | ---- Elapsed time= 10.415027141571045
29 | config term
30 | Enter configuration commands, one per line. End with CNTL/Z.
31 | r5(config)#int loopback 0
32 | r5(config-if)# ip address 5.5.5.5 255.255.255.255
33 | r5(config-if)# description automated configuration
34 | r5(config-if)#end
35 | r5#
36 |
37 | ---- Elapsed time= 10.665486097335815
38 | config term
39 | Enter configuration commands, one per line. End with CNTL/Z.
40 | R3(config)#int loopback 0
41 | R3(config-if)# ip address 3.3.3.3 255.255.255.255
42 | R3(config-if)# description automated configuration
43 | R3(config-if)#end
44 | R3#
45 |
46 | ---- Elapsed time= 10.851855039596558
47 | config term
48 | Enter configuration commands, one per line. End with CNTL/Z.
49 | R1(config)#int loopback 0
50 | R1(config-if)# ip address 1.1.1.1 255.255.255.255
51 | R1(config-if)# description automated configuration
52 | R1(config-if)#end
53 | R1#
54 |
55 | ---- Elapsed time= 10.866304636001587
56 | config term
57 | Enter configuration commands, one per line. End with CNTL/Z.
58 | R4(config)#int loopback 0
59 | R4(config-if)# ip address 4.4.4.4 255.255.255.255
60 | R4(config-if)# description automated configuration
61 | R4(config-if)#end
62 | R4#
63 |
64 | ---- Elapsed time= 10.902701616287231
65 | config term
66 | Enter configuration commands, one per line. End with CNTL/Z.
67 | r6(config)#int loopback 0
68 | r6(config-if)# ip address 6.6.6.6 255.255.255.255
69 | r6(config-if)# description automated configuration
70 | r6(config-if)#
71 | r6(config-if)#int tun0
72 | r6(config-if)# ip address 157.130.0.6 255.255.255.254
73 | r6(config-if)# tunnel source 6.6.6.6
74 | r6(config-if)# tunnel destination 7.7.7.7
75 | r6(config-if)#
76 | r6(config-if)#router bgp 65006
77 | r6(config-router)# neighbor 157.130.0.7 remote-as 65007
78 | r6(config-router)#
79 | r6(config-router)#end
80 | r6#
81 |
82 | ---- Elapsed time= 15.61635708808899
83 | config term
84 | Enter configuration commands, one per line. End with CNTL/Z.
85 | r7(config)#int loopback 0
86 | r7(config-if)# ip address 7.7.7.7 255.255.255.255
87 | r7(config-if)# description automated configuration
88 | r7(config-if)#
89 | r7(config-if)#
90 | r7(config-if)#
91 | r7(config-if)#int tun0
92 | r7(config-if)# ip address 157.130.0.7 255.255.255.254
93 | r7(config-if)# tunnel
94 | r7(config-if)# tunnel source 7.7.7.7
95 | r7(config-if)# tunnel destination 6.6.6.6
96 | r7(config-if)#
97 | r7(config-if)#router bgp 65007
98 | r7(config-router)# neighbor 157.130.0.6 remote-as 65006
99 | r7(config-router)#end
100 | r7#
101 |
102 | ---- Elapsed time= 15.997164726257324
103 | [None, None, None, None, None, None, None]
104 |
--------------------------------------------------------------------------------
/netmiko/archive/output_netmiko_script5.py:
--------------------------------------------------------------------------------
1 | root@debian:/home/todd/gns3# ./netmiko_script5.py
2 | Username:
3 | Password:
4 | Enter config commands seperated by ',': interface loopback 1, description this is a test
5 | Enter the host IPs seperate with space: r1 r2 r3 r4 r5
6 | Connected to host: r3
7 | Connected to host: r2
8 | Connected to host: r1
9 | Connected to host: r5
10 | Connected to host: r4
11 | config term
12 | Enter configuration commands, one per line. End with CNTL/Z.
13 | R3(config)#interface loopback 1
14 | R3(config-if)# description this is a test
15 | R3(config-if)#end
16 | R3#
17 |
18 | ---- Elapsed time= 8.392916917800903
19 | config term
20 | Enter configuration commands, one per line. End with CNTL/Z.
21 | R2(config)#interface loopback 1
22 | R2(config-if)# description this is a test
23 | R2(config-if)#end
24 | R2#
25 |
26 | ---- Elapsed time= 8.500743627548218
27 | config term
28 | Enter configuration commands, one per line. End with CNTL/Z.
29 | R1(config)#interface loopback 1
30 | R1(config-if)# description this is a test
31 | R1(config-if)#end
32 | R1#
33 |
34 | ---- Elapsed time= 8.696260690689087
35 | config term
36 | Enter configuration commands, one per line. End with CNTL/Z.
37 | R5(config)#interface loopback 1
38 | R5(config-if)# description this is a test
39 | R5(config-if)#end
40 | R5#
41 |
42 | ---- Elapsed time= 8.971424341201782
43 | config term
44 | Enter configuration commands, one per line. End with CNTL/Z.
45 | R4(config)#interface loopback 1
46 | R4(config-if)# description this is a test
47 | R4(config-if)#end
48 | R4#
49 |
50 | ---- Elapsed time= 9.040150880813599
51 | [None, None, None, None, None]
52 | root@debian:/home/todd/gns3#
53 |
54 |
55 | **************
56 | Adding an ACL
57 | **************
58 |
59 | todd@debian:~/gns3$ ./netmiko_script5.py
60 | Username:
61 | Password:
62 | Enter config commands seperated by ',': ip access-list extended test_acl, permit tcp any any log, permit udp any any log
63 | Enter the host IPs seperate with space: r1 r2 r3 r4 r5
64 | Connected to host: r2
65 | Connected to host: r4
66 | Connected to host: r5
67 | Connected to host: r3
68 | Connected to host: r1
69 | config term
70 | Enter configuration commands, one per line. End with CNTL/Z.
71 | R5(config)#ip access-list extended test_acl
72 | R5(config-ext-nacl)# permit tcp any any log
73 | R5(config-ext-nacl)# permit udp any any log
74 | R5(config-ext-nacl)#end
75 | R5#
76 |
77 | ---- Elapsed time= 9.461827039718628
78 | config term
79 | Enter configuration commands, one per line. End with CNTL/Z.
80 | R3(config)#ip access-list extended test_acl
81 | R3(config-ext-nacl)# permit tcp any any log
82 | R3(config-ext-nacl)# permit udp any any log
83 | R3(config-ext-nacl)#end
84 | R3#
85 |
86 | ---- Elapsed time= 9.696628332138062
87 | config term
88 | Enter configuration commands, one per line. End with CNTL/Z.
89 | R1(config)#ip access-list extended test_acl
90 | R1(config-ext-nacl)# permit tcp any any log
91 | R1(config-ext-nacl)# permit udp any any log
92 | R1(config-ext-nacl)#end
93 | R1#
94 |
95 | ---- Elapsed time= 9.735490322113037
96 | config term
97 | Enter configuration commands, one per line. End with CNTL/Z.
98 | R4(config)#ip access-list extended test_acl
99 | R4(config-ext-nacl)# permit tcp any any log
100 | R4(config-ext-nacl)# permit udp any any log
101 | R4(config-ext-nacl)#end
102 | R4#
103 |
104 | ---- Elapsed time= 9.76802921295166
105 | config term
106 | Enter configuration commands, one per line. End with CNTL/Z.
107 | R2(config)#ip access-list extended test_acl
108 | R2(config-ext-nacl)# permit tcp any any log
109 | R2(config-ext-nacl)# permit udp any any log
110 | R2(config-ext-nacl)#end
111 | R2#
112 |
113 | ---- Elapsed time= 9.791200399398804
114 | [None, None, None, None, None]
115 | todd@debian:~/gns3$
116 |
--------------------------------------------------------------------------------
/netmiko/archive/placeholder:
--------------------------------------------------------------------------------
1 | ...
2 |
--------------------------------------------------------------------------------
/netmiko/basic_ssh_script.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #(c) 2017 Todd Riemenschneider
3 | from getpass import getpass
4 | from netmiko import ConnectionHandler
5 |
6 | uname = input("Username: ")
7 | passwd = getpass("Password: ")
8 | cmd = input("Enter show commands separated by ',': ")
9 | host = input("Enter the host IPs separate with space: ")
10 |
11 | #host = """"""
12 |
13 | if len(uname) < 1: uname = ""
14 | if len(passwd) < 1: passwd = ""
15 |
16 | hosts = host.split()
17 | cmds = cmd.split(",")
18 |
19 | err_host = []
20 |
21 | for ip in hosts:
22 | hp_rtr = {
23 | "device_type": "hp_procurve",
24 | "ip" : ip,
25 | "username" : uname,
26 | "password" : passwd,
27 | }
28 | try:
29 | net_connect = ConnectHandler(**hp_rtr)
30 | except Exception as unknown_error:
31 | print("************************************")
32 | print("Unable to log into this device:", ip)
33 | print(unknown_error)
34 | err_host.append(ip)
35 | print("Errors logging into:", err_host)
36 | print("************************************")
37 | continue
38 |
39 | print("Connected to host: ", ip)
40 | for show_commands in cmds:
41 | output = net_connect.send_command(show_commands)
42 | print("Command issued:",show_commands)
43 | print(output)
44 | print("+++++++++++++++++++++++++++++++++++++++++++++++")
45 | print("End of configs for device", ip)
46 | print("************************************")
47 | print("Errors logging into:" , err_host)
48 |
49 |
--------------------------------------------------------------------------------
/netmiko/config_scripts/interactive_config_script.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -----------------------------
3 | # (c) 2018 Todd Riemenschneider
4 | # -----------------------------
5 | import netmiko
6 | #from pprint import pprint as pp
7 |
8 | devs_to_cfg = input("Number of devices to configure: " )
9 | count = int(devs_to_cfg)
10 |
11 | commands = {}
12 | err_host = []
13 |
14 | for i in range(count):
15 | hosts = input("Enter host device: ")
16 | cmds = input('Enter commands for device seperate with ",": ')
17 | cmd_items = cmds.split(',')
18 | print(cmd_items)
19 | commands[hosts]= cmd_items
20 | print("")
21 | print("")
22 |
23 | print(""" This is the dictionary before the loop""", commands)
24 |
25 | for k,v in commands.items():
26 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
27 | print("Pre-change State: ", k)
28 | try:
29 | ios_rtr = {
30 | "device_type": "cisco_ios",
31 | "ip": k,
32 | "username": "admin",
33 | "password": "automate",
34 | }
35 | net_connect = netmiko.ConnectHandler(**ios_rtr)
36 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
37 | except Exception as unknown_error:
38 | print("************************************")
39 | print("Unable to log into this device:", k)
40 | print(unknown_error)
41 | err_host.append(k)
42 | print("Errors logging into:", err_host)
43 | print("************************************")
44 | continue
45 | try:
46 | # Remove comments (#) if you want to compare pre and post change
47 | # print("Pre-change state", k)
48 | # pre_change01 = net_connect.send_command('show running-config')
49 | # pp(pre_change01)
50 | print("************************************")
51 | configs01 = net_connect.send_config_set(v)
52 | print(configs01)
53 | print("++++++++++++++++++++++++++++++++++++")
54 | # print("Post-change state: ", k)
55 | # post_change01 = net_connect.send_command('show running-config')
56 | # pp(post_change01)
57 | except Exception as cmd_error:
58 | print("Command not working, make sure syntax is correct")
59 | print("Problem with commands on: ", k)
60 | print(cmd_error)
61 | continue
62 |
63 | print('Problems connecting to these hosts: ', err_host)
64 |
--------------------------------------------------------------------------------
/netmiko/config_scripts/multiple_device_config_script.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # --------------------------------------------------------------
3 | #(c) 2017 Todd Riemenschneider
4 | # This script will allow you to configure multiple devices with
5 | # different configurations on each
6 | # --------------------------------------------------------------
7 | from getpass import getpass
8 | from netmiko import ConnectHandler
9 | from multiprocessing import Pool
10 | from time import time
11 |
12 | # Login info
13 | username = input('Enter username: ')
14 | password = getpass('Enter password: ')
15 |
16 | # Useful in a lab setting not production
17 | if len(username) < 1 : username = "admin"
18 | if len(password) < 1 : password = "automate"
19 |
20 | # Command files
21 | with open('commands_file_r1') as f:
22 | commands_list_r1 = f.read().splitlines()
23 |
24 | with open('commands_file_r2') as f:
25 | commands_list_r2 = f.read().splitlines()
26 |
27 | with open('commands_file_r3') as f:
28 | commands_list_r3 = f.read().splitlines()
29 |
30 | with open('commands_file_r4') as f:
31 | commands_list_r4 = f.read().splitlines()
32 |
33 | with open('commands_file_r5') as f:
34 | commands_list_r5 = f.read().splitlines()
35 |
36 | #with open('commands_file_r6') as f:
37 | # commands_list_r6 = f.read().splitlines()
38 |
39 | #with open('commands_file_r7') as f:
40 | # commands_list_r7 = f.read().splitlines()
41 |
42 | # Target hosts
43 | with open('host_file') as f:
44 | host_file = f.read().splitlines()
45 |
46 | print("----The devices being configured----")
47 | print(host_file)
48 |
49 | starting_time = time()
50 |
51 | # Updated /etc/hosts to use host names rather than host ips
52 |
53 | def run_script(hostname):
54 | print ('Connecting to device: ' + hostname)
55 | ios_device = {
56 | 'device_type': 'cisco_ios',
57 | 'ip': hostname,
58 | 'username': username,
59 | 'password': password
60 | }
61 | # Command to connect to hosts
62 | net_connect = ConnectHandler(**ios_device)
63 |
64 | # Logic used to connect host to configuration file
65 | # Updated host_file with hostname like r1 r2 r3 r4 r5
66 | # If we went by ip address we would need to update hostname == "10.0.0.1" for r1
67 | #if hostname == '10.0.0.1':
68 | # print("hostname == 10.0.0.1:", hostname == '10.0.0.1')
69 | # output = net_connect.send_config_set(commands_list_r1)
70 | # print(output)
71 | if hostname == 'r1':
72 | print("hostname == r1:", hostname == 'r1')
73 | output = net_connect.send_config_set(commands_list_r1)
74 | print(output)
75 | elif hostname == 'r2':
76 | print ("hostname == r2:", hostname == 'r2')
77 | output = net_connect.send_config_set(commands_list_r2)
78 | print(output)
79 | elif hostname == 'r3':
80 | print ("hostname == r3: ", hostname == 'r3')
81 | output = net_connect.send_config_set(commands_list_r3)
82 | print(output)
83 | elif hostname == 'r4':
84 | print ("hostname == r4:", hostname == 'r4')
85 | output = net_connect.send_config_set(commands_list_r4)
86 | print(output)
87 | elif hostname == 'r5':
88 | print ("hostname == r5:", hostname == 'r5')
89 | output = net_connect.send_config_set(commands_list_r5)
90 | print(output)
91 | # elif hostname == 'r6':
92 | # print ("hostname == r6: ", hostname == 'r6')
93 | # output = net_connect.send_config_set(commands_list_r6)
94 | # print(output)
95 | # elif hostname == 'r7':
96 | # print ("hostname == r7: ", hostname == 'r7')
97 | # output = net_connect.send_config_set(commands_list_r7)
98 | # print(output)
99 | # Used to determine how long it takes for the script to run/complete
100 | print('\n---- Elapsed time=', time()-starting_time)
101 |
102 | #Used to set up MP Pools to increase performance
103 | #Specify number of process in the pool to run at same time
104 | #There is no recommendation really trial error as to the right number
105 | if __name__ == "__main__":
106 | with Pool(7) as p:
107 | print(p.map(run_script, host_file))
108 |
--------------------------------------------------------------------------------
/netmiko/config_scripts/push_same_cfg_multi_devs.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -----------------------------
3 | # (c) 2017 Todd Riemenschneider
4 | # -----------------------------
5 | # This script will allow up to update a group of hosts with common config shared by all
6 | # Enable Multiprocessing
7 | from multiprocessing import Pool
8 | # getpass will not display password
9 | from getpass import getpass
10 | # ConnectionHandler is the function used by netmiko to connect to devices
11 | from netmiko import ConnectHandler
12 | # Time tracker
13 | from time import time
14 |
15 | #create variables for username and password
16 | #create variables for configs and hosts
17 | uname = input("Username: ")
18 | passwd = getpass("Password: ")
19 | cmd = input("Enter config commands seperated by ',': ")
20 | host = input("Enter the host IPs seperate with space: ")
21 |
22 | #This will allow you to just press enter
23 | #This sets default values Not recommanded in any place but a lab
24 | if len(uname) < 1 : uname = "admin"
25 | if len(passwd) < 1 : passwd = "automate"
26 |
27 | #create lists of hosts and cmds to iterate through
28 | #This list can contain show or config commands show commands require "do + command"
29 | hosts = host.split()
30 | cmds = cmd.split(",")
31 |
32 | starting_time = time()
33 |
34 | #Each member of the pool of 5 will be run through this function
35 | def run_script(host_ip):
36 | ios_rtr = {
37 | "device_type": "cisco_ios",
38 | "ip": host_ip,
39 | "username": uname,
40 | "password": passwd,
41 | }
42 | #connect to the device via ssh
43 | net_connect = ConnectHandler(**ios_rtr)
44 | #print the device IP to identify which device is being configured
45 | print("Connected to host:", host_ip)
46 | #this variable is used to capture the output of cmds sent to device
47 | output = net_connect.send_config_set(cmds)
48 | #print the output
49 | print(output)
50 | print('\n---- Elapsed time=', time()-starting_time)
51 |
52 | if __name__ == "__main__":
53 | # Pool(5) means 5 process / devices will be run at a time, until youve gone through the device list
54 | with Pool(5) as p:
55 | print(p.map(run_script, hosts))
56 |
--------------------------------------------------------------------------------
/netmiko/jinja_example/bgp_template_r4.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | asn: 4
3 | loop0_ip: 4.4.4.4
4 | neighbor_address: 10.0.4.5
5 | peer_asn: 5
6 | remote_router_name: r5
7 | password: real_secure_pass
8 |
--------------------------------------------------------------------------------
/netmiko/jinja_example/bgp_template_r5.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | asn: 5
3 | loop0_ip: 5.5.5.5
4 | neighbor_address: 10.0.4.4
5 | peer_asn: 4
6 | remote_router_name: r4
7 | password: real_secure_pass
8 |
9 |
--------------------------------------------------------------------------------
/netmiko/jinja_example/conf_bgp_r4_r5_using_class_obj.py:
--------------------------------------------------------------------------------
1 | from netmiko import Netmiko
2 | from getpass import getpass
3 | from jinja2 import Environment, FileSystemLoader
4 | from pprint import pprint
5 |
6 |
7 | ENV = Environment(loader=FileSystemLoader('.'))
8 | template = ENV.get_template("ebgp_neighbor_template.j2")
9 |
10 |
11 | class bgp_conf(object):
12 |
13 | def __init__(self, asn, loop0_ip, neighbor_address, peer_asn, remote_router_name, password):
14 | self.asn = asn
15 | self.loop0_ip = loop0_ip
16 | self.neighbor_address = neighbor_address
17 | self.peer_asn = peer_asn
18 | self.remote_router_name = remote_router_name
19 | self.password = password
20 |
21 | '''
22 | This is just being used for reference to help you build your class definition
23 |
24 | router bgp {{ bgp.asn }}
25 | bgp log-neighbor-changes
26 | network {{ bgp.loop0_ip }} mask 255.255.255.255
27 | neighbor {{ bgp.neighbor_address }} remote-as {{ bgp.peer_asn }}
28 | neighbor {{ bgp.neighbor_address }} description ebgp-to-{{ bgp.remote_router_name }}
29 | neighbor {{ bgp.neighbor_address }} password {{ bgp.password }}
30 | neighbor {{ bgp.neighbor_address }} timers 1 3
31 | neighbor {{ bgp.neighbor_address }} advertisement-interval 1
32 |
33 | '''
34 |
35 | my_device = {
36 | "host": "r4",
37 | "username": "admin",
38 | "password": "automate",
39 | "device_type": "cisco_ios"
40 | }
41 |
42 | net_conn = Netmiko(**my_device)
43 |
44 | print(net_conn.find_prompt())
45 |
46 | # Populating variables in class bgp_conf()
47 | bgp_cfg_r4 = bgp_conf("4", "4.4.4.4", "10.0.4.5", "5", "r5", "real_secure_pass")
48 |
49 | output = template.render(bgp=bgp_cfg_r4)
50 |
51 | print(output)
52 | print(type(output))
53 |
54 | pprint(net_conn.send_config_set(output))
55 | show_run_r4 = net_conn.send_command("show run | beg router bgp")
56 | show_ip_bgp_summ_r4 = net_conn.send_command("show ip bgp summ")
57 |
58 |
59 | ENV = Environment(loader=FileSystemLoader('.'))
60 | template = ENV.get_template("ebgp_neighbor_template.j2")
61 |
62 | my_device = {
63 | "host": "r5",
64 | "username": "admin",
65 | "password": "automate",
66 | "device_type": "cisco_ios"
67 | }
68 |
69 | net_conn = Netmiko(**my_device)
70 |
71 | print(net_conn.find_prompt())
72 |
73 | # Populating variables in class bgp_conf()
74 | bgp_cfg_r5 = bgp_conf("5", "5.5.5.5", "10.0.4.4", "4", "r4", "real_secure_pass")
75 |
76 | print(bgp_cfg_r5)
77 |
78 | output = template.render(bgp=bgp_cfg_r5)
79 |
80 | print(output)
81 | print(type(output))
82 |
83 | pprint(net_conn.send_config_set(output))
84 |
85 | print("*" * 50)
86 | print("Configuration verification step")
87 |
88 |
89 | show_run_r4 = net_conn.send_command("show run | beg router bgp")
90 | show_ip_bgp_summ_r4 = net_conn.send_command("show ip bgp summ")
91 |
92 | pprint(show_run_r4)
93 | pprint(show_ip_bgp_summ_r4)
94 |
95 | print("*" * 50)
96 | print("Configuration verification step")
97 |
98 |
99 |
100 | show_run_r5 = net_conn.send_command("show run | beg router bgp")
101 | show_ip_bgp_summ_r5 = net_conn.send_command("show ip bgp summ")
102 |
103 | pprint(show_run_r5)
104 | pprint(show_ip_bgp_summ_r5)
105 |
--------------------------------------------------------------------------------
/netmiko/jinja_example/conf_bgp_r4_r5_using_dict.py:
--------------------------------------------------------------------------------
1 | from netmiko import Netmiko
2 | from jinja2 import Environment, FileSystemLoader
3 | from pprint import pprint
4 | import time
5 |
6 | ENV = Environment(loader=FileSystemLoader('.'))
7 | template = ENV.get_template("ebgp_neighbor_template.j2")
8 |
9 | my_device = {
10 | "host": "r4",
11 | "username": "admin",
12 | "password": "automate",
13 | "device_type": "cisco_ios"
14 | }
15 |
16 | net_conn_r4 = Netmiko(**my_device)
17 |
18 | print(net_conn_r4.find_prompt())
19 |
20 | r4_bgp_nei_dict = {
21 | "asn": "4",
22 | "loop0_ip": "4.4.4.4",
23 | "neighbor_address": "10.0.4.5",
24 | "peer_asn": "5",
25 | "remote_router_name": "r5",
26 | "password": "real_secure_pass",
27 | }
28 |
29 | '''
30 | This is just being used for reference to help you build your dictionary
31 |
32 | router bgp {{ bgp.asn }}
33 | bgp log-neighbor-changes
34 | network {{ bgp.loop0_ip }} mask 255.255.255.255
35 | neighbor {{ bgp.neighbor_address }} remote-as {{ bgp.peer_asn }}
36 | neighbor {{ bgp.neighbor_address }} description ebgp-to-{{ bgp.remote_router_name }}
37 | neighbor {{ bgp.neighbor_address }} password {{ bgp.password }}
38 | neighbor {{ bgp.neighbor_address }} timers 1 3
39 | neighbor {{ bgp.neighbor_address }} advertisement-interval 1
40 |
41 | '''
42 |
43 |
44 | print(r4_bgp_nei_dict)
45 |
46 |
47 | output = template.render(bgp=r4_bgp_nei_dict)
48 |
49 | print(output)
50 | print(type(output))
51 |
52 | pprint(net_conn_r4.send_config_set(output))
53 |
54 |
55 | print("****" * 25)
56 |
57 | ENV = Environment(loader=FileSystemLoader('.'))
58 | template = ENV.get_template("ebgp_neighbor_template.j2")
59 |
60 | my_device = {
61 | "host": "r5",
62 | "username": "admin",
63 | "password": "automate",
64 | "device_type": "cisco_ios"
65 | }
66 |
67 | net_conn_r5 = Netmiko(**my_device)
68 |
69 | print(net_conn_r5.find_prompt())
70 |
71 |
72 | r5_bgp_nei_dict = {
73 | "asn": "5",
74 | "loop0_ip": "5.5.5.5",
75 | "neighbor_address": "10.0.4.4",
76 | "peer_asn": "4",
77 | "remote_router_name": "r4",
78 | "password": "real_secure_pass",
79 | }
80 |
81 | '''
82 | This is just begin used for reference to help you build your dictionary
83 |
84 | router bgp {{ bgp.asn }}
85 | bgp log-neighbor-changes
86 | network {{ bgp.loop0_ip }} mask 255.255.255.255
87 | neighbor {{ bgp.neighbor_address }} remote-as {{ bgp.peer_asn }}
88 | neighbor {{ bgp.neighbor_address }} description ebgp-to-{{ bgp.remote_router_name }}
89 | neighbor {{ bgp.neighbor_address }} password {{ bgp.password }}
90 | neighbor {{ bgp.neighbor_address }} timers 1 3
91 | neighbor {{ bgp.neighbor_address }} advertisement-interval 1
92 |
93 | '''
94 |
95 |
96 |
97 | print(r5_bgp_nei_dict)
98 |
99 | output = template.render(bgp=r5_bgp_nei_dict)
100 |
101 | print(output)
102 | print(type(output))
103 |
104 | pprint(net_conn_r5.send_config_set(output))
105 |
106 | print("****" * 25)
107 |
108 |
109 | print("****" * 25)
110 | print("Configuration verification step for r4")
111 | print("Waiting 10 secs for bgp to come up")
112 | time.sleep(10)
113 |
114 | show_ip_bgp_summ_r4 = net_conn_r4.send_command("show ip bgp summ")
115 | show_ip_rt_r4 = net_conn_r4.send_command("show ip route")
116 |
117 | pprint(show_ip_bgp_summ_r4)
118 | pprint(show_ip_rt_r4)
119 |
120 | print("****" * 25)
121 | print("Configuration verification step for r5")
122 | print("Waiting 5 secs for bgp to come up")
123 | time.sleep(5)
124 |
125 |
126 | show_ip_bgp_summ_r5 = net_conn_r5.send_command("show ip bgp summ")
127 | show_ip_rt_r5 = net_conn_r5.send_command("show ip route")
128 |
129 | pprint(show_ip_bgp_summ_r5)
130 | pprint(show_ip_rt_r5)
131 |
--------------------------------------------------------------------------------
/netmiko/jinja_example/conf_bgp_yaml_jinja2.py:
--------------------------------------------------------------------------------
1 | from jinja2 import Environment, FileSystemLoader
2 | import yaml
3 | from pprint import pprint as pp
4 | from netmiko import Netmiko
5 |
6 | ENV = Environment(loader=FileSystemLoader('.'))
7 | template = ENV.get_template("ebgp_neighbor_template.j2")
8 |
9 |
10 | with open("bgp_template_r4.yaml") as r4:
11 | r4_bgp = yaml.load(r4)
12 | print(r4_bgp)
13 |
14 | with open("bgp_template_r5.yaml") as r5:
15 | r5_bgp = yaml.load(r5)
16 | print(r5_bgp)
17 |
18 |
19 |
20 | output_r4 = template.render(bgp=r4_bgp)
21 | output_r5 = template.render(bgp=r5_bgp)
22 |
23 |
24 | my_device_r4 = {
25 | "host": "r4",
26 | "username": "admin",
27 | "password": "automate",
28 | "device_type": "cisco_ios"
29 | }
30 |
31 | my_device_r5 = {
32 | "host": "r5",
33 | "username": "admin",
34 | "password": "automate",
35 | "device_type": "cisco_ios"
36 | }
37 |
38 | net_conn_r4 = Netmiko(**my_device_r4)
39 |
40 | print(net_conn_r4.find_prompt())
41 |
42 | pp(net_conn_r4.send_config_set(output_r4))
43 |
44 | net_conn_r5 = Netmiko(**my_device_r5)
45 |
46 | print(net_conn_r5.find_prompt())
47 |
48 | pp(net_conn_r5.send_config_set(output_r5))
49 |
50 |
--------------------------------------------------------------------------------
/netmiko/jinja_example/ebgp_neighbor_template.j2:
--------------------------------------------------------------------------------
1 | router bgp {{ bgp.asn }}
2 | bgp log-neighbor-changes
3 | network {{ bgp.loop0_ip }} mask 255.255.255.255
4 | neighbor {{ bgp.neighbor_address }} remote-as {{ bgp.peer_asn }}
5 | neighbor {{ bgp.neighbor_address }} description ebgp-to-{{ bgp.remote_router_name }}
6 | neighbor {{ bgp.neighbor_address }} password {{ bgp.password }}
7 | neighbor {{ bgp.neighbor_address }} timers 1 3
8 | neighbor {{ bgp.neighbor_address }} advertisement-interval 1
9 |
--------------------------------------------------------------------------------
/netmiko/netmiko_multi_dev_cfg.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # --------------------------------------------------------------
3 | #(c) 2017 Todd Riemenschneider
4 | # This script will allow you to configure multiple devices with
5 | # different configurations on each
6 | # --------------------------------------------------------------
7 | from getpass import getpass
8 | from netmiko import ConnectHandler
9 | from multiprocessing import Pool
10 | from time import time
11 |
12 | # Login info
13 | username = input('Enter username: ')
14 | password = getpass('Enter password: ')
15 |
16 | # Useful in a lab setting not production
17 | if len(username) < 1 : username = "automate"
18 | if len(password) < 1 : password = "automation"
19 |
20 | # Command files
21 | with open('commands_file_r1') as f:
22 | commands_list_r1 = f.read().splitlines()
23 |
24 | with open('commands_file_r2') as f:
25 | commands_list_r2 = f.read().splitlines()
26 |
27 | with open('commands_file_r3') as f:
28 | commands_list_r3 = f.read().splitlines()
29 |
30 | with open('commands_file_r4') as f:
31 | commands_list_r4 = f.read().splitlines()
32 |
33 | with open('commands_file_r5') as f:
34 | commands_list_r5 = f.read().splitlines()
35 |
36 | with open('commands_file_r6') as f:
37 | commands_list_r6 = f.read().splitlines()
38 |
39 | with open('commands_file_r7') as f:
40 | commands_list_r7 = f.read().splitlines()
41 |
42 | # Target hosts
43 | with open('host_file') as f:
44 | host_file = f.read().splitlines()
45 |
46 | print("----The devices being configured----")
47 | print(host_file)
48 |
49 | starting_time = time()
50 |
51 | # Updated /etc/hosts to use host names rather than host ips
52 |
53 | def run_script(hostname):
54 | print ('Connecting to device: ' + hostname)
55 | ios_device = {
56 | 'device_type': 'cisco_ios',
57 | 'ip': hostname,
58 | 'username': username,
59 | 'password': password
60 | }
61 | # Command to connect to hosts
62 | net_connect = ConnectHandler(**ios_device)
63 |
64 | # Logic used to connect host to configuration file
65 | if hostname == 'r1':
66 | print("hostname == r1:", hostname == 'r1')
67 | output = net_connect.send_config_set(commands_list_r1)
68 | print(output)
69 | elif hostname == 'r2':
70 | print ("hostname == r2:", hostname == 'r2')
71 | output = net_connect.send_config_set(commands_list_r2)
72 | print(output)
73 | elif hostname == 'r3':
74 | print ("hostname == r3: ", hostname == 'r3')
75 | output = net_connect.send_config_set(commands_list_r3)
76 | print(output)
77 | elif hostname == 'r4':
78 | print ("hostname == r4:", hostname == 'r4')
79 | output = net_connect.send_config_set(commands_list_r4)
80 | print(output)
81 | elif hostname == 'r5':
82 | print ("hostname == r5:", hostname == 'r5')
83 | output = net_connect.send_config_set(commands_list_r5)
84 | print(output)
85 | elif hostname == 'r6':
86 | print ("hostname == r6: ", hostname == 'r6')
87 | output = net_connect.send_config_set(commands_list_r6)
88 | print(output)
89 | elif hostname == 'r7':
90 | print ("hostname == r7: ", hostname == 'r7')
91 | output = net_connect.send_config_set(commands_list_r7)
92 | print(output)
93 | # Used to determine how long it takes for the script to run/complete
94 | print('\n---- Elapsed time=', time()-starting_time)
95 |
96 | #Used to set up MP Pools to increase performance
97 | #Specify number of process in the pool to run at same time
98 | #There is no recommendation really trial error as to the right number
99 | if __name__ == "__main__":
100 | with Pool(7) as p:
101 | print(p.map(run_script, host_file))
102 |
--------------------------------------------------------------------------------
/netmiko/netmiko_script5.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #(c) 2017 Todd Riemenschneider
3 | #This script will allow up to update a group of hosts with common config shared by all
4 | #Enable Multiprocessing
5 | from multiprocessing import Pool
6 | #getpass will not display password
7 | from getpass import getpass
8 | #ConnectionHandler is the function used by netmiko to connect to devices
9 | from netmiko import ConnectHandler
10 | #Time tracker
11 | from time import time
12 |
13 | #create variables for username and password
14 | #create variables for configs and hosts
15 | uname = input("Username: ")
16 | passwd = getpass("Password: ")
17 | cmd = input("Enter config commands seperated by ',': ")
18 | host = input("Enter the host IPs seperate with space: ")
19 |
20 | #This will allow you to just press enter
21 | #This sets default values Not recommanded in any place but a lab
22 | if len(uname) < 1 : uname = "automate"
23 | if len(passwd) < 1 : passwd = "automation"
24 |
25 | #create lists of hosts and cmds to iterate through
26 | #This list can contain show or config commands show commands require "do + command"
27 | hosts = host.split()
28 | cmds = cmd.split(",")
29 |
30 | starting_time = time()
31 |
32 | #Each member of the pool of 5 will be run through this function
33 | def run_script(host_ip):
34 | ios_rtr = {
35 | "device_type": "cisco_ios",
36 | "ip": host_ip,
37 | "username": uname,
38 | "password": passwd,
39 | }
40 | #connect to the device via ssh
41 | net_connect = ConnectHandler(**ios_rtr)
42 | #print the device IP to identify which device is being configured
43 | print("Connected to host:", host_ip)
44 | #this variable is used to capture the output of cmds sent to device
45 | output = net_connect.send_config_set(cmds)
46 | #print the output
47 | print(output)
48 | print('\n---- Elapsed time=', time()-starting_time)
49 |
50 | if __name__ == "__main__":
51 | # Pool(5) means 5 process / devices will be run at a time, until youve gone through the device list
52 | with Pool(5) as p:
53 | print(p.map(run_script, hosts))
54 |
--------------------------------------------------------------------------------
/netmiko/netmiko_show_cmds.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #(c) 2017 Todd Riemenschneider
3 | #
4 | #This script will allow for user pick hosts and enter show commands interactively
5 | #
6 | #Enable Multiprocessing
7 | from multiprocessing import Pool
8 | #
9 | #getpass will not display password
10 | from getpass import getpass
11 | #ConnectionHandler is the function used by netmiko to connect to devices
12 | from netmiko import ConnectHandler
13 | #Time tracker
14 | from time import time
15 |
16 | #create variables for username and password
17 | #create variables for configs and hosts
18 | uname = input("Username: ")
19 | passwd = getpass("Password: ")
20 | cmd = input("Enter show commands seperated by ',': ")
21 | host = input("Enter the host IPs seperate with space: ")
22 |
23 | #This will allow you to just press enter
24 | #This sets default values Not recommanded in any place but a lab
25 | if len(uname) < 1 : uname = "admin"
26 | if len(passwd) < 1 : passwd = "automate"
27 |
28 | #This will put hosts and commands entered into list format
29 | hosts = host.split()
30 | cmds = cmd.split(",")
31 |
32 | starting_time = time()
33 |
34 | #Each member of the pool of 5 will be run through this function
35 | def run_script(host_ip):
36 | ios_rtr = {
37 | "device_type": "cisco_ios",
38 | "ip": host_ip,
39 | "username": uname,
40 | "password": passwd,
41 | }
42 | #connect to the device via ssh
43 | net_connect = ConnectHandler(**ios_rtr)
44 | #print the device IP or Hostname
45 | print("Connected to host:", host_ip)
46 | #this for loop is used to iterate through the show commands
47 | for show_commands in cmds:
48 | output = net_connect.send_command(show_commands)
49 | print("Connected to host:", host_ip)
50 | print(output)
51 | print('\n---- Elapsed time=', time()-starting_time)
52 |
53 | if __name__ == "__main__":
54 | # Pool(5) means 5 process will be run at a time, more hosts will go in the next group
55 | with Pool(5) as p:
56 | print(p.map(run_script, hosts))
57 |
58 |
59 | #This is the key to sending show commands vs config commands
60 | #show commands --> net_connect.send_command()
61 | #config commmands --> net_connect.send_config_set()
62 |
--------------------------------------------------------------------------------
/netmiko/scp/ceos/ceos1.config:
--------------------------------------------------------------------------------
1 | localhost#sh run
2 | ! Command: show running-config
3 | ! device: localhost (cEOSSim, EOS-4.20.5F)
4 | !
5 | transceiver qsfp default-mode 4x10G
6 | !
7 | spanning-tree mode mstp
8 | ! This command is needed for scp to work on ceos
9 | aaa authorization exec default local
10 | !
11 | no aaa root
12 | !
13 | username arista privilege 15 secret sha512 $6$KFUUrXkZSw1l3aTl$Oco1hciDD4Wqw8Wc.GFjzRR6GfZ2lOydR38JjcPwK9in6Ylyy0pWJGHAs7Mvp0extKwiTauSWgAaeXfWwPwzp0
14 | !
15 | no ip routing
16 | !
17 | management api http-commands
18 | no shutdown
19 | !
20 | end
21 |
--------------------------------------------------------------------------------
/netmiko/scp/ceos/ceos2.config:
--------------------------------------------------------------------------------
1 | localhost#sh run
2 | ! Command: show running-config
3 | ! device: localhost (cEOSSim, EOS-4.20.5F)
4 | !
5 | transceiver qsfp default-mode 4x10G
6 | !
7 | spanning-tree mode mstp
8 | ! This command is needed for scp to work on ceos
9 | aaa authorization exec default local
10 | !
11 | no aaa root
12 | !
13 | username arista privilege 15 secret sha512 $6$wG3foX14jGdS.zyr$6s2x.sM7sACXoihJIaKnGfFloIOD4kQqHYm4ubXSR46pte4auDj51HD9XrZx43gt8ddvEZ7LJTo4cE7KyVbt0.
14 | !
15 | no ip routing
16 | !
17 | management api http-commands
18 | protocol https port 8443
19 | no shutdown
20 | !
21 | end
22 |
--------------------------------------------------------------------------------
/netmiko/scp/ceos/info.text:
--------------------------------------------------------------------------------
1 | This test was performed using containerized eos or ceos
2 |
--------------------------------------------------------------------------------
/netmiko/scp/ceos/scp_file_arista.output.txt:
--------------------------------------------------------------------------------
1 | Todds-MBP-3:netmiko_stuff toddriemenschneider$ python3 scp_file_arista.py
2 |
3 | {'file_exists': True, 'file_transferred': True, 'file_verified': True}
4 | Hit enter to continue:
5 |
6 | {'file_exists': True, 'file_transferred': True, 'file_verified': True}
7 | Hit enter to continue:
8 | Todds-MBP-3:netmiko_stuff toddriemenschneider$
9 | ssh -p 2023 arista@127.0.0.1
10 | Password:
11 | Last login: Mon Sep 10 15:16:15 2018 from 172.17.0.1
12 | localhost#dir
13 | Directory of flash:/
14 |
15 | -rw- 77 Sep 10 14:14 SsuRestore.log
16 | drwx 4096 Sep 10 14:14 debug
17 | drwx 4096 Sep 10 14:15 persist
18 | drwx 4096 Sep 10 14:15 schedule
19 | -rw- 478 Sep 10 15:15 startup-config
20 | -rw- 40 Sep 10 15:16 test_file.txt
21 | -rw- 13 Apr 16 22:57 zerotouch-config
22 |
23 | 62725623808 bytes total (56898256896 bytes free)
24 | localhost#more test_file.txt
25 | This is an scp file transfer test file!
26 | localhost#exit
27 |
--------------------------------------------------------------------------------
/netmiko/scp/ceos/scp_file_arista.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | from netmiko import ConnectHandler, file_transfer
3 |
4 |
5 | eos1 = {
6 | 'device_type': 'arista_eos',
7 | 'host': 'localhost',
8 | 'username': 'arista',
9 | 'password': 'arista',
10 | 'file_system': '/mnt/flash',
11 | 'port': 2022
12 | }
13 |
14 | eos2 = {
15 | 'device_type': 'arista_eos',
16 | 'host': 'localhost',
17 | 'username': 'arista',
18 | 'password': 'arista',
19 | 'file_system': '/mnt/flash',
20 | 'port': 2023
21 | }
22 |
23 | source_file = "test_file.txt"
24 | dest_file = "test_file.txt"
25 | direction = 'put'
26 |
27 | for net_device in (eos1, eos2):
28 | file_system = net_device.pop('file_system')
29 | ssh_conn = ConnectHandler(**net_device)
30 | transfer_dict = file_transfer(ssh_conn,
31 | source_file=source_file,
32 | dest_file=dest_file,
33 | file_system=file_system,
34 | direction=direction,
35 | overwrite_file=True)
36 | print(transfer_dict)
37 | pause = input("Hit enter to continue: ")
38 |
--------------------------------------------------------------------------------
/netmiko/scp/ceos/test_file.txt:
--------------------------------------------------------------------------------
1 | This is an scp file transfer test file!
2 |
--------------------------------------------------------------------------------
/netmiko/scp/info.txt:
--------------------------------------------------------------------------------
1 | This test was done from vagrant lab
2 |
--------------------------------------------------------------------------------
/netmiko/scp/netmiko_scp_script.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | from netmiko import ConnectHandler, file_transfer
3 |
4 |
5 | eos1 = {
6 | 'device_type': 'arista_eos',
7 | 'host': 'localhost',
8 | 'username': 'arista',
9 | 'password': 'arista',
10 | 'file_system': '/mnt/flash',
11 | 'port': 12201
12 | }
13 |
14 | eos2 = {
15 | 'device_type': 'arista_eos',
16 | 'host': 'localhost',
17 | 'username': 'arista',
18 | 'password': 'arista',
19 | 'file_system': '/mnt/flash',
20 | 'port': 13201
21 | }
22 |
23 | source_file = "test_file.txt"
24 | dest_file = "test_file.txt"
25 | direction = 'put'
26 |
27 | for net_device in (eos1, eos2):
28 | file_system = net_device.pop('file_system')
29 | ssh_conn = ConnectHandler(**net_device)
30 | transfer_dict = file_transfer(ssh_conn,
31 | source_file=source_file,
32 | dest_file=dest_file,
33 | file_system=file_system,
34 | direction=direction,
35 | overwrite_file=True)
36 | print(transfer_dict)
37 | pause = input("Hit enter to continue: ")
38 |
--------------------------------------------------------------------------------
/netmiko/scp/output_netmiko_scp_script.txt:
--------------------------------------------------------------------------------
1 | Todds-MacBook-Pro-3:netmiko_vagrant toddriemenschneider$ ./netmiko_scp_script.py
2 | {'file_exists': True, 'file_transferred': True, 'file_verified': True}
3 | Hit enter to continue:
4 | {'file_exists': True, 'file_transferred': True, 'file_verified': True}
5 | Hit enter to continue:
6 | Todds-MacBook-Pro-3:netmiko_vagrant toddriemenschneider$
7 |
--------------------------------------------------------------------------------
/netmiko/scp/test_file.txt:
--------------------------------------------------------------------------------
1 | this is a test file for testing scp
2 |
--------------------------------------------------------------------------------
/netmiko/script_requests/req_config_script_07292020.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #(c) 2020 Todd Riemenschneider
3 | #
4 | """
5 | Wrote this script based off of a request I got:
6 |
7 | I am looking script which will run below command and provide output
8 | Conf t
9 | ip http client connection forceclose
10 | end
11 | sh ip http client all
12 |
13 | this I want to run on multiple IP and want to create an output file for all file can I use script shown
14 | """
15 | #Enable Multiprocessing
16 | from multiprocessing import Pool
17 | #getpass will not display password
18 | from getpass import getpass
19 | #ConnectionHandler is the function used by netmiko to connect to devices
20 | from netmiko import ConnectHandler
21 | #Time tracker
22 | from time import time
23 |
24 | #create variables for username and password
25 | #create variables for configs and hosts
26 | uname = input("Username: ")
27 | passwd = getpass("Password: ")
28 |
29 | #This will allow you to just press enter
30 | #This sets default values Not recommanded in any place but a lab
31 | if len(uname) < 1 : uname = "developer"
32 | if len(passwd) < 1 : passwd = "C1sco12345"
33 |
34 |
35 | # Pull target hosts from host_file
36 | with open('host_file.txt') as f:
37 | hosts = f.read().splitlines()
38 |
39 | config_cmd = ["ip http client connection forceclose",]
40 |
41 |
42 | commands = 'show ip http client all'
43 |
44 | starting_time = time()
45 |
46 | #Each member of the pool of 5 will be run through this function
47 | def run_script(host_ip):
48 | ios_rtr = {
49 | "device_type": "cisco_ios",
50 | "host": host_ip,
51 | "port": 8181,
52 | "username": uname,
53 | "password": passwd,
54 | }
55 | nl = "\n"
56 | try:
57 | #Connect to the device via ssh
58 | net_connect = ConnectHandler(**ios_rtr)
59 | host_name = net_connect.find_prompt()
60 | print("Connected to host:", host_ip)
61 | host_id = "Connected to host: " + host_ip
62 | print('\n---- Elapsed time=', time()-starting_time)
63 | cmd_output = net_connect.send_command(commands)
64 | print(f"Pre-config state:{cmd_output}")
65 | cfg_output = net_connect.send_config_set(config_cmd)
66 | print(f"Config:{cmd_output}")
67 | cmd_output2 = net_connect.send_command(commands)
68 | print(f"Post-config state:{cmd_output2}")
69 | print(cfg_output)
70 | with open(host_ip + "_.txt", 'a') as file:
71 | file.write(host_id)
72 | file.write(nl)
73 | file.write(host_name)
74 | file.write(nl)
75 | file.write(cmd_output)
76 | file.write(nl)
77 | file.write(str(config_cmd))
78 | file.write(nl)
79 | file.write(cfg_output)
80 | file.write(nl)
81 | file.write(cmd_output2)
82 | file.write(nl)
83 | file.write("**************************************")
84 | file.write(nl)
85 |
86 |
87 | except Exception as unknown_error:
88 | # Error handling - Print output to screen
89 | print("************************************")
90 | print("Unable to log into this device:", host_ip)
91 | print(unknown_error)
92 | print("************************************")
93 | # Error handling - record to file
94 | with open("Connection_Errors", "a") as err_log:
95 | err_log.write("Error connecting to the following devices")
96 | err_log.write(nl)
97 | err_log.write(str(unknown_error))
98 | err_log.write(nl)
99 | err_log.write(host_ip)
100 | err_log.write(nl)
101 |
102 |
103 | if __name__ == "__main__":
104 | # Pool(5) means 5 process will be run at a time, more hosts will go in the next group
105 | with Pool(5) as p:
106 | print(p.map(run_script, hosts))
107 |
108 |
109 |
--------------------------------------------------------------------------------
/netmiko/ssh_sandbox.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #(c) 2018 Todd Riemenschneider
3 | import netmiko
4 | from pprint import pprint as pp
5 |
6 | # This will enter the number of devices as a string
7 | devs_to_cfg = input("Number of devices to configure: " )
8 | # This will turn the string into an integer
9 | count = int(devs_to_cfg)
10 |
11 | # create empty dictionary to be used with the list of commands
12 | commands = {}
13 | # create empty list that will be used to keep track problem hosts
14 | err_host = []
15 |
16 | # This will be used to determine how many devices to log into
17 | for i in range(count):
18 | # Create list of hosts will be in string format
19 | hosts = input("Enter host device: ")
20 | # Create list of commands will be in string format
21 | cmds = input('Enter commands for device seperate with ",": ')
22 | # Put commands in list format
23 | cmd_items = cmds.split(',')
24 | # Sanity check on commands printed to screen
25 | print(cmd_items)
26 | # Add to empty dictionary hosts are keys commands are values
27 | commands[hosts]= cmd_items
28 | print("")
29 | print("")
30 |
31 | print(""" This is the dictionary before the loop""", commands)
32 |
33 | # k = hosts v = commands
34 | for k,v in commands.items():
35 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
36 | print("Pre-change State: ", k)
37 | try:
38 | ios_rtr = {
39 | "device_type": "cisco_ios",
40 | "ip": k,
41 | "username": "admin",
42 | "password": "automate",
43 | }
44 | # Used to connect to hosts using parameters in ios_rtr dictionary
45 | net_connect = netmiko.ConnectHandler(**ios_rtr)
46 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
47 | except Exception as unknown_error:
48 | # Error handling - connecting to hosts
49 | print("************************************")
50 | print("Unable to log into this device:", k)
51 | print(unknown_error)
52 | err_host.append(k)
53 | print("Errors logging into:", err_host)
54 | print("************************************")
55 | continue
56 | try:
57 | # This can be used for pre-change status check (turn off with #)
58 | print("Pre-change state", k)
59 | pre_change01 = net_connect.send_command('show running-config')
60 | pp(pre_change01)
61 | print("************************************")
62 | configs01 = net_connect.send_config_set(v)
63 | pp(configs01)
64 | print("++++++++++++++++++++++++++++++++++++")
65 | # This can be used for post-change status check (turn off with #)
66 | print("Post-change state: ", k)
67 | post_change01 = net_connect.send_command('show running-config')
68 | pp(post_change01)
69 | except Exception as cmd_error:
70 | # Error handling - command syntax issues
71 | print("Command not working, make sure syntax is correct")
72 | print("Problem with commands on: ", k)
73 | print(cmd_error)
74 | continue
75 |
76 | print('Problems connecting to these hosts: ', err_host)
77 |
--------------------------------------------------------------------------------
/netmiko/test_stuff/interactive_script.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -----------------------------
3 | # (c) 2020 Todd Riemenschneider
4 | # -----------------------------
5 | # This script is prompting user to determine if they plan on configuring the devices or gathering info using show commands.
6 | # Script tries to be a one stop shop for lab use.
7 | # Its soo painfully slow may end up ditching it or adding MP processing.
8 | #
9 | import netmiko
10 | from pprint import pprint as pp
11 |
12 | type_of_interaction = input("Is this going to be a config or show command? (Type config or show): ")
13 | devs_to_cfg = input("Number of devices you going to access: " )
14 | count = int(devs_to_cfg)
15 |
16 | commands = {}
17 | err_host = []
18 |
19 | for i in range(count):
20 | # ports = input("Enter Port to connect with:" )
21 | # port = int(ports)
22 | hosts = input("Enter host device: ")
23 | cmds = input('Enter commands for device seperate with ",": ')
24 | cmd_items = cmds.split(',')
25 | print(cmd_items)
26 | commands[hosts]= cmd_items
27 | print("")
28 | print("")
29 |
30 | print(""" This is the dictionary before the loop""", commands)
31 |
32 | for k,v in commands.items():
33 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
34 | print("Pre-change State: ", k)
35 | try:
36 | rtr = {
37 | "device_type": "cisco_xe",
38 | "ip": k,
39 | "username": "developer",
40 | "password": "C1sco12345",
41 | "port": 8181,
42 | "verbose": True,
43 | }
44 | net_connect = netmiko.ConnectHandler(**rtr)
45 | print(net_connect.enable())
46 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
47 | except Exception as unknown_error:
48 | print("************************************")
49 | print("Unable to log into this device:", k)
50 | print(unknown_error)
51 | err_host.append(k)
52 | print("Errors logging into:", err_host)
53 | print("************************************")
54 | continue
55 | try:
56 | #Remove comments (#) if you want to compare pre and post change
57 | # print("Pre-change state", k)
58 | # pre_change01 = net_connect.send_command('show running-config')
59 | # pp(pre_change01)
60 | print(v)
61 | print("************************************")
62 | if type_of_interaction.strip() == "config":
63 | configs01 = net_connect.send_config_set(v)
64 | else:
65 | for cmd in cmd_items:
66 | print("Command:", cmd,"\n", net_connect.send_command(cmd))
67 | print(configs01)
68 | print("++++++++++++++++++++++++++++++++++++")
69 | print("Post-change state: ", k)
70 | post_change01 = net_connect.send_command('show running-config')
71 | # pp(post_change01)
72 | except Exception as cmd_error:
73 | print("Command not working, make sure syntax is correct")
74 | print("Problem with commands on: ", k)
75 | print(cmd_error)
76 | continue
77 |
78 | print('Problems connecting to these hosts: ', err_host)
79 |
--------------------------------------------------------------------------------
/network_controller/get_device_info.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | # Get authentication ticket first
5 |
6 | url = "http://localhost:58000/api/v1"
7 |
8 | headers = {"Content-Type": "application/json"}
9 | data = json.dumps({"username": "admin", "password": "cisco123!"})
10 |
11 | resp = requests.post(url + "/ticket", data=data, headers=headers)
12 |
13 | result = resp.json()
14 |
15 | ticket = result["response"]["serviceTicket"]
16 | print(f"\nTicket value to use is {ticket}\n")
17 |
18 | # Get network device info
19 |
20 | headers = {"X-Auth-Token": ticket}
21 | resp = requests.get(url+"/network-device", headers=headers)
22 |
23 | print(f"\nStatus Code: {resp.status_code}\n")
24 |
25 | result = resp.json()
26 |
27 | count = 1
28 | for i in result["response"]:
29 | print(f"Device {count}")
30 | try:
31 | deviceInfo = i["hostname"]+" "+i["type"]+" "+i["serialNumber"]+" "+i["softwareVersion"]+" "+i["productId"]
32 | print(deviceInfo)
33 | except:
34 | print(f"Unable to read device {count}")
35 | count += 1
36 |
37 | ##########################
38 | #To see all device info
39 | #print(json.dumps(i, indent=4))
40 |
41 | '''
42 | % python3 get_device_info.py
43 |
44 | Ticket value to use is NC-79-571f3a0a96fe41af8dc5-nbi
45 |
46 |
47 | Status Code: 200
48 |
49 | Device 1
50 | a10_s1 Switch CAT10102UG4- 15.0 2960-24TT
51 | Device 2
52 | Unable to read device 2
53 | Device 3
54 | Unable to read device 3
55 | Device 4
56 | core_r2 Router FDO1302WPFM- 15.4 ISR4321
57 | Device 5
58 | core2 MultiLayerSwitch CAT1010JRE1- 16.3.2 3650-24PS
59 | Device 6
60 | Core1 MultiLayerSwitch CAT101089TI- 16.3.2 3650-24PS
61 | Device 7
62 | core_r1 Router FDO1302887G- 15.4 ISR4321
63 | Device 8
64 | Unable to read device 8
65 |
66 | '''
67 |
--------------------------------------------------------------------------------
/network_controller/update_device_config.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 |
5 | url = "http://localhost:58000/api/v1"
6 |
7 | headers = {"Content-Type": "application/json"}
8 | data = json.dumps({"username": "admin", "password": "cisco123!"})
9 | resp = requests.post(url + "/ticket", data=data, headers=headers)
10 |
11 | print(f"\nStatus code: {resp.status_code}\n")
12 | result = resp.json()
13 | #print(json.dumps(result, indent=4))
14 |
15 | ticket = result["response"]["serviceTicket"]
16 | print(f"\nTicket value to use is {ticket}\n")
17 |
18 | # Add a serversg
19 |
20 | headers = {"X-Auth-Token": ticket, "Content-Type": "application/json"}
21 | data = json.dumps({
22 | "aaa": {
23 | "ipAddress": "10.10.0.22",
24 | "key": "Test_key"
25 | },
26 | "dns": {
27 | "ipAddress": "10.10.0.22",
28 | "name": "test.lab"
29 | },
30 | "netflow": {
31 | "port": "9995",
32 | "reflectionIp": "10.10.0.22"
33 | },
34 |
35 | "ntp" : {"serverIp": "10.10.0.22"},
36 | "syslog" : [
37 | {"serverIp": "5.5.5.5"},
38 | {"serverIp": "6.6.6.6"},
39 | {"serverIp": "7.7.7.7"},
40 | ],
41 | })
42 |
43 | resp = requests.put(url+"/wan/network-wide-setting", headers=headers, data=data)
44 |
45 | print(f"\nStatus code: {resp.status_code}\n")
46 | result = resp.json()
47 | print(json.dumps(result, indent=4))
48 |
49 | """
50 | Results
51 | toddriemenschneider@Todds-MacBook-Pro-2 % python3 update_device_config.py
52 |
53 | Status code: 201
54 |
55 |
56 | Ticket value to use is NC-106-e3b589a5608649ec8b0e-nbi
57 |
58 |
59 | Status code: 200
60 |
61 | {
62 | "response": {
63 | "aaa": {
64 | "ipAddress": "10.10.0.22",
65 | "key": "Test_key"
66 | },
67 | "dns": {
68 | "ipAddress": "10.10.0.22",
69 | "name": "test.lab"
70 | },
71 | "netflow": {
72 | "port": "9995",
73 | "reflectionIp": "10.10.0.22"
74 | },
75 | "ntp": {
76 | "serverIp": "10.10.0.22"
77 | },
78 | "syslog": [
79 | {
80 | "serverIp": "5.5.5.5"
81 | },
82 | {
83 | "serverIp": "6.6.6.6"
84 | },
85 | {
86 | "serverIp": "7.7.7.7"
87 | }
88 | ]
89 | },
90 | "version": "1.0"
91 | }
92 | toddriemenschneider@Todds-MacBook-Pro-2 %
93 | """
94 |
--------------------------------------------------------------------------------
/nxapi/nxapi_script02.py:
--------------------------------------------------------------------------------
1 | """
2 | File - nxapi_script02.py
3 | Author - Todd Riemenschneider
4 | Date - 03.26.2020
5 | """
6 | # Requests library is necessary to interface with nxapi
7 | import requests
8 | # Json is the data format we are using to communicate over http/https
9 | import json
10 | # Getpass is optional and is used to hide passwords
11 | from getpass import getpass
12 | # pprint is used to improve json readability
13 | from pprint import pprint as pp
14 | # This was used to disable annoying SSL Warning legitament or otherwise
15 | from requests.packages.urllib3.exceptions import InsecureRequestWarning
16 | # This line actually disabled the warning
17 | requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
18 |
19 | #Hard code Lab Creds
20 | UN = <>
21 | PW = <>
22 | target = <>
23 | #Prod Creds
24 | #UN = input("Username: ")
25 | #PW = getpass("Password: ")
26 | #target = input("target host ip or dns name: ")
27 |
28 | #default target good for lab testing
29 | #if len(target) <= 0:
30 | # target = <>
31 |
32 | # This is where you enter your commands
33 | commands = input('Commands seperate with ",": ')
34 | # This turns your text strings into list format separating commands on the ","
35 | cmds = commands.split(',')
36 |
37 | # This is the target hosts your connecting to
38 | url='https://' + target + '/ins'
39 | print(url)
40 |
41 | # This lets the target host know what type of data to expect
42 | myheaders={'content-type':'application/json-rpc'}
43 | # Created empty list to hold dictionary that will be expanding as we iterate through commands
44 | payload = []
45 | # This was used to number the json instance id's as well iterate through the commands
46 | instance_id = 0
47 | # iterate through the cmds lists
48 | for command in cmds:
49 | # add one to instance_id to number json instance
50 | instance_id += 1
51 | # This dictionary will grow with each command that gets looped through
52 | payload_dict = {
53 | "jsonrpc": "2.0",
54 | "method": "cli",
55 | "params": {
56 | # This is where the individual command gets entered into the dictionary
57 | "cmd": command,
58 | "version": 1
59 | },
60 | # This is were the instance_id is applied to keep track of the json instances your commands create
61 | "id": instance_id,
62 | }
63 | # This command then applies the dictionary to the empty payload list that was created above the for loop
64 | # This gets added to every iteration through the for loop
65 | payload.append(payload_dict)
66 | pp(command)
67 |
68 | # This applied the commands to the target device to execute, also the verify=False is necessary to work in lab
69 | # SSL set up is ok for lab, you would potentially want the verify process in production
70 | response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(UN,PW),verify=False).json()
71 | #Prints output in a more readable way
72 | print(json.dumps(response, indent=2, sort_keys=True))
73 |
--------------------------------------------------------------------------------
/nxapi/nxapi_script1.py:
--------------------------------------------------------------------------------
1 | """
2 | File - nxapi_script1.py
3 | Author - Todd Riemenschneider
4 | Date - 06.23.2018
5 | """
6 | # Requests library is necessary to interface with nxapi
7 | import requests
8 | # Json is the data format we are using to communicate over http/https
9 | import json
10 | # Getpass is optional and is used to hide passwords
11 | from getpass import getpass
12 | # pprint is used to improve json readability
13 | from pprint import pprint as pp
14 | # This was used to disable annoying SSL Warning legitament or otherwise
15 | from requests.packages.urllib3.exceptions import InsecureRequestWarning
16 | # This line actually disabled the warning
17 | requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
18 |
19 | UN = input("Username: ")
20 | PW = getpass("Password: ")
21 | target = input("target host ip or dns name: ")
22 |
23 | if len(target) <= 0:
24 | target = '64.103.37.14'
25 |
26 | # This is where you enter your commands
27 | commands = input('Commands seperate with ",": ')
28 | # This turns your text strings into list format separating commands on the ","
29 | cmds = commands.split(',')
30 |
31 | # This is the target hosts your connecting to
32 | url='https://' + target + '/ins'
33 | print(url)
34 |
35 | # This lets the target host know what type of data to expect
36 | myheaders={'content-type':'application/json-rpc'}
37 | # Created empty list to hold dictionary that will be expanding as we iterate through commands
38 | payload = []
39 | # This was used to number the json instance id's as well iterate through the commands
40 | instance_id = 0
41 | # iterate through the cmds lists
42 | for command in cmds:
43 | # add one to instance_id to number json instance
44 | instance_id += 1
45 | # This dictionary will grow with each command that gets looped through
46 | payload_dict = {
47 | "jsonrpc": "2.0",
48 | "method": "cli",
49 | "params": {
50 | # This is where the individual command gets entered into the dictionary
51 | "cmd": command,
52 | "version": 1
53 | },
54 | # This is were the instance_id is applied to keep track of the json instances your commands create
55 | "id": instance_id,
56 | }
57 | # This command then applies the dictionary to the empty payload list that was created above the for loop
58 | # This gets added to every iteration through the for loop
59 | payload.append(payload_dict)
60 | pp(command)
61 |
62 | # This applied the commands to the target device to execute, also the verify=False is necessary to work in lab
63 | # SSL set up is ok for lab, you would potentially want the verify process in production
64 | response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(UN,PW),verify=False).json()
65 | pp(response)
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/pip3 freeze:
--------------------------------------------------------------------------------
1 | root@debian:/home/todd/gns3# pip3 freeze
2 | Brlapi==0.6.2
3 | Jinja2==2.9.6
4 | Mako==1.0.0
5 | MarkupSafe==0.23
6 | PyNaCl==1.1.2
7 | PyYAML==3.12
8 | Pygments==2.2.0
9 | VyattaConfParser==0.5.1
10 | ansible==2.3.2.0
11 | asn1crypto==0.22.0
12 | bcrypt==3.1.3
13 | cffi==1.11.0
14 | chainmap==1.0.2
15 | chardet==2.3.0
16 | colorama==0.3.2
17 | cryptography==2.0.3
18 | decorator==4.1.2
19 | future==0.16.0
20 | html5lib==0.999
21 | idna==2.6
22 | ipython==6.2.0
23 | ipython-genutils==0.2.0
24 | jedi==0.10.2
25 | jtextfsm==0.3.1
26 | junos-eznc==2.1.6
27 | librouteros==1.0.3
28 | louis==2.5.3
29 | napalm==1.2.0
30 | napalm-base==0.25.0
31 | napalm-eos==0.6.1
32 | napalm-fortios==0.4.0
33 | napalm-ios==0.7.0
34 | napalm-iosxr==0.5.4
35 | napalm-junos==0.12.0
36 | napalm-nxos==0.6.0
37 | napalm-panos==0.4.0
38 | napalm-pluribus==0.5.1
39 | napalm-ros==0.2.2
40 | napalm-vyos==0.1.3
41 | netaddr==0.7.19
42 | netmiko==1.4.2
43 | pan-python==0.12.0
44 | paramiko==2.3.0
45 | pexpect==4.2.1
46 | pickleshare==0.7.4
47 | prompt-toolkit==1.0.15
48 | ptyprocess==0.5.2
49 | pyIOSXR==0.52
50 | pyPluribus==0.3.1
51 | pyasn1==0.3.5
52 | pycparser==2.18
53 | pycrypto==2.6.1
54 | pyeapi==0.8.1
55 | pyfg==0.50
56 | pygobject==3.14.0
57 | pynxos==0.0.3
58 | python-apt==0.9.3.12
59 | python-debian==0.1.27
60 | pyxdg==0.25
61 | requests==2.4.3
62 | requests-toolbelt==0.8.0
63 | scp==0.10.2
64 | simplegeneric==0.8.1
65 | six==1.11.0
66 | traitlets==4.3.2
67 | typing==3.6.2
68 | urllib3==1.9.1
69 | wcwidth==0.1.7
70 | wheel==0.24.0
71 | xmltodict==0.11.0
72 | root@debian:/home/todd/gns3#
73 |
--------------------------------------------------------------------------------
/pyeapi/.eapi.conf:
--------------------------------------------------------------------------------
1 | # This file needs to be created in ~/.eapi.conf
2 | #
3 |
4 | [connection:sw1]
5 | host: 192.168.1.201
6 | username: todd
7 | password: todd
8 | transport: https
9 |
10 | #Replicate as needed for hosts
11 | #
12 | [connection:sw2]
13 | host: 192.168.1.202
14 | username: todd
15 | password: todd
16 | transport: https
17 |
--------------------------------------------------------------------------------
/pyeapi/archive/interactive_show_cmds.py:
--------------------------------------------------------------------------------
1 | #(c) 2017 Todd Riemenschneider
2 | import pyeapi
3 | from pprint import pprint as pp
4 |
5 |
6 | devs_to_connect = input("Number of devices to connect to: " )
7 | count = int(devs_to_connect)
8 |
9 | commands = {}
10 | err_host = []
11 |
12 | for i in range(count):
13 | hosts = input("Enter host device: ")
14 | cmds = input('Enter commands for device seperate with ",": ')
15 | cmd_items = cmds.split(',')
16 | print(cmd_items)
17 | commands[hosts]= cmd_items
18 | print("")
19 | print("")
20 |
21 | print(""" This is the dictionary before the loop""", commands)
22 |
23 | for k,v in commands.items():
24 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
25 | print("Connecting to: ", k)
26 | try:
27 | node = pyeapi.connect_to(k)
28 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
29 | except Exception as unknown_error:
30 | print("************************************")
31 | print("Unable to log into this device:", k)
32 | print(unknown_error)
33 | err_host.append(k)
34 | print("Errors logging into:", err_host)
35 | print("************************************")
36 | continue
37 | try:
38 | pp(node.enable(v))
39 | print("Post-change state: ", k)
40 | except Exception as cmd_error:
41 | print("Command not working, make sure syntax is correct")
42 | print("Problem with commands on: ", k)
43 | print(cmd_error)
44 | continue
45 |
46 | print('Problems connecting to these hosts: ', err_host)
47 |
--------------------------------------------------------------------------------
/pyeapi/archive/multi_dev_cfg_script.py:
--------------------------------------------------------------------------------
1 | #(c) 2017 Todd Riemenschneider
2 | import pyeapi
3 | from pprint import pprint as pp
4 |
5 | cmds1 = input('Enter commands for veos1 seperate with ",": ')
6 | cmds2 = input('Enter commands for veos2 seperate with ",": ')
7 | cmds3 = input('Enter commands for veos3 seperate with ",": ')
8 |
9 | hosts = input('Enter hosts seperated by spaces: ')
10 | devices = hosts.split()
11 | commands1 = cmds1.split(',')
12 | commands2 = cmds2.split(',')
13 | commands3 = cmds3.split(',')
14 |
15 | err_host = []
16 |
17 | for host in devices:
18 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
19 | print("Pre-change State: ", host)
20 | try:
21 | node = pyeapi.connect_to(host)
22 | pp(node.enable(['show running-config']))
23 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
24 | except Exception as unknown_error:
25 | print("************************************")
26 | print("Unable to log into this device:", host)
27 | print(unknown_error)
28 | err_host.append(host)
29 | print("Errors logging into:", err_host)
30 | print("************************************")
31 | continue
32 | if host == 'veos1':
33 | try:
34 | pp(node.config(commands1))
35 | print("Post-change state: ", host)
36 | pp(node.enable(['show running-config']))
37 | except Exception as cmd_error:
38 | print("Command not working, make sure syntax is correct")
39 | print("Problem with commands on: ", host)
40 | print(cmd_error)
41 | continue
42 | elif host == 'veos2':
43 | try:
44 | pp(node.config(commands1))
45 | print("Post-change state: ", host)
46 | pp(node.enable(['show running-config']))
47 | except Exception as cmd_error:
48 | print("Command not working, make sure syntax is correct")
49 | print("Problem with commands on: ", host)
50 | print(cmd_error)
51 | continue
52 | elif host == 'veos3':
53 | try:
54 | pp(node.config(commands1))
55 | print("Post-change state: ", host)
56 | pp(node.enable(['show running-config']))
57 | except Exception as cmd_error:
58 | print("Command not working, make sure syntax is correct")
59 | print("Problem with commands on: ", host)
60 | print(cmd_error)
61 | continue
62 |
63 | print('Problems connecting to these hosts: ', err_host)
64 |
--------------------------------------------------------------------------------
/pyeapi/archive/multi_dev_cfg_script2.py:
--------------------------------------------------------------------------------
1 | #(c) 2017 Todd Riemenschneider
2 | import pyeapi
3 | from pprint import pprint as pp
4 |
5 |
6 | devs_to_cfg = input("Number of devices to configure: " )
7 | count = int(devs_to_cfg)
8 |
9 | commands = {}
10 | err_host = []
11 |
12 | for i in range(count):
13 | hosts = input("Enter host device: ")
14 | cmds = input('Enter commands for device seperate with ",": ')
15 | cmd_items = cmds.split(',')
16 | print(cmd_items)
17 | commands[hosts]= cmd_items
18 | print("")
19 | print("")
20 |
21 | print(""" This is the dictionary before the loop""", commands)
22 |
23 | for k,v in commands.items():
24 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
25 | print("Pre-change State: ", k)
26 | try:
27 | node = pyeapi.connect_to(k)
28 | pp(node.enable(['show running-config']))
29 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
30 | except Exception as unknown_error:
31 | print("************************************")
32 | print("Unable to log into this device:", k)
33 | print(unknown_error)
34 | err_host.append(k)
35 | print("Errors logging into:", err_host)
36 | print("************************************")
37 | continue
38 | try:
39 | pp(node.config(v))
40 | print("Post-change state: ", k)
41 | pp(node.enable(['show running-config']))
42 | except Exception as cmd_error:
43 | print("Command not working, make sure syntax is correct")
44 | print("Problem with commands on: ", k)
45 | print(cmd_error)
46 | continue
47 |
48 | print('Problems connecting to these hosts: ', err_host)
49 |
--------------------------------------------------------------------------------
/pyeapi/ceos_demo/.eapi.conf:
--------------------------------------------------------------------------------
1 | [connection:ceos1]
2 | host=127.0.0.1
3 | username=arista
4 | password=arista
5 | transport=https
6 |
7 |
8 | [connection:ceos2]
9 | host=127.0.0.1
10 | username=arista
11 | password=arista
12 | transport=https
13 | port=8443
14 |
15 |
--------------------------------------------------------------------------------
/pyeapi/ceos_demo/script1.py:
--------------------------------------------------------------------------------
1 | import pyeapi
2 | from pprint import pprint as pp
3 |
4 | node1 = pyeapi.connect_to('ceos1')
5 | node2 = pyeapi.connect_to('ceos2')
6 |
7 | node1.api("ipinterfaces").create("Ethernet1")
8 | node2.api("ipinterfaces").create("Ethernet1")
9 |
10 | node1.config("ip name-server 8.8.8.8")
11 | node1.config("ip domain lookup source-interface loopback1")
12 |
13 | node2.config("ip name-server 8.8.8.8")
14 | node2.config("ip domain lookup source-interface loopback1")
15 |
16 | cmds = ["show version", "show running-config", "show management api http-commands"]
17 |
18 | pp(node1.run_commands(cmds))
19 | pp(node2.run_commands(cmds))
20 |
21 | configurations1 = [
22 | "hostname ceos1",
23 | "ip routing",
24 | "interface Ethernet1",
25 | "ip address 10.0.0.1/24",
26 | "no shutdown",
27 | "interface loopback 1",
28 | "description router-id",
29 | "ip address 1.1.1.1/32",
30 | "router ospf 1",
31 | "network 10.0.0.0 0.0.0.255 area 0",
32 | "network 1.1.1.1 0.0.0.0 area 0",
33 | "router-id 1.1.1.1",
34 | "management telnet",
35 | "no shutdown",
36 | ]
37 |
38 | configurations2 = [
39 | "hostname ceos2",
40 | "ip routing",
41 | "interface Ethernet1",
42 | "ip address 10.0.0.2/24",
43 | "no shutdown",
44 | "interface loopback 1",
45 | "description router-id",
46 | "ip address 2.2.2.2/32",
47 | "router ospf 1",
48 | "network 10.0.0.0 0.0.0.255 area 0",
49 | "network 2.2.2.2 0.0.0.0 area 0",
50 | "router-id 2.2.2.2",
51 | "management telnet",
52 | "no shutdown",
53 | ]
54 |
55 |
56 | node1.config(configurations1)
57 | node2.config(configurations2)
58 |
59 | pingHost = ["ping 1.1.1.1", "ping 2.2.2.2"]
60 |
61 | print("#" * 45)
62 | print("Printing results of ping to loopbacks advertised via ospf")
63 | pp(node1.run_commands(pingHost))
64 |
65 | print("Running-Config ceos1")
66 | pp(node1.get_config())
67 |
68 | print("#" * 45)
69 | print("Printing results of ping to loopbacks advertised via ospf")
70 | pp(node2.run_commands(pingHost))
71 |
72 | print("Running-Config ceos2")
73 | pp(node2.get_config())
74 |
75 | pp(node1.run_commands("ping 8.8.8.8"))
76 | pp(node2.run_commands("ping 8.8.8.8"))
77 |
78 |
--------------------------------------------------------------------------------
/pyeapi/ceos_demo/script2.py:
--------------------------------------------------------------------------------
1 | import pyeapi
2 | from pprint import pprint as pp
3 |
4 | node1 = pyeapi.connect_to('ceos1')
5 | node2 = pyeapi.connect_to('ceos2')
6 |
7 | cmds = ["show version", "show ip route", "show ip ospf neighbor"]
8 |
9 | pp(node1.run_commands(cmds))
10 | pp(node2.run_commands(cmds))
11 |
--------------------------------------------------------------------------------
/pyeapi/ceos_demo/script3.py:
--------------------------------------------------------------------------------
1 | import pyeapi
2 | from pprint import pprint as pp
3 |
4 | node1 = pyeapi.connect_to('ceos1')
5 | node2 = pyeapi.connect_to('ceos2')
6 |
7 | pp("*" * 40)
8 |
9 | pp("The Running-Config")
10 | pp(node1.get_config())
11 |
12 | pp("+" * 40)
13 |
14 | pp("The Startup-Config")
15 | pp(node1.startup_config)
16 |
17 | pp("***" * 40)
18 |
19 | pp("The Running-Config")
20 | pp(node2.get_config())
21 |
22 | pp("+" * 40)
23 |
24 | pp("The Startup-Config")
25 | pp(node2.startup_config)
26 |
27 |
28 | answer = input("Are running and startup configs the same y or n ?: ")
29 |
30 | if answer == 'y':
31 | print("Cool!")
32 |
33 | else:
34 | pp(node1.run_commands(commands="copy running-config startup-config"))
35 | pp(node2.run_commands(commands="copy running-config startup-config"))
36 | print("Now they are...")
37 |
38 |
39 |
--------------------------------------------------------------------------------
/pyeapi/ceos_lab_scripts/lab_config_script.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import pyeapi
4 | from pprint import pprint as pp
5 |
6 | #Command below is unneccessary if you are using .eapi.conf
7 | #pyeapi.load_config('nodes.conf')
8 |
9 | ans = input("Are you configuring more than one device with the same config? (y or n): ")
10 |
11 | if ans == 'y':
12 | devices = input("Enter device names seperated by spaces: ")
13 | dev_list = devices.split()
14 | cmds = input("Enter config lines separated by ',': ")
15 | configuration = cmds.split(',')
16 | for dev in dev_list:
17 | node = pyeapi.connect_to(dev)
18 | results = node.config(configuration)
19 | pp(results)
20 | pp(node.get_config())
21 | else:
22 | device = input("Enter device you would like to configure: ")
23 | config = input("Enter config commands seperate lines with ',': ")
24 | configuration = config.split(",")
25 | node1 = pyeapi.connect_to(device)
26 | results = node1.config(configuration)
27 | pp(results)
28 | pp(node1.get_config())
29 |
30 | print("End of Script!!")
31 |
32 |
--------------------------------------------------------------------------------
/pyeapi/ceos_lab_scripts/wr_mem_lab_configs.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import pyeapi
4 | from pprint import pprint as pp
5 |
6 | hosts = ['ceos1', 'ceos2', 'ceos3', 'ceos4']
7 |
8 | cmds = ["show running-config", 'write memory']
9 |
10 |
11 | for host in hosts:
12 | node = pyeapi.connect_to(host)
13 | pp(node.run_commands(cmds[0]))
14 | pp(node.run_commands(cmds[1]))
15 | print("\n\n\n")
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/pyeapi/demo/.eapi.conf:
--------------------------------------------------------------------------------
1 | [connection:veos5]
2 | host:veos5
3 | username: admin
4 | password: testpass
5 | transport: https
6 |
7 | [connection:veos6]
8 | host:veos6
9 | username: admin
10 | password: testpass
11 | transport: https
12 |
13 |
--------------------------------------------------------------------------------
/pyeapi/demo/script1.py:
--------------------------------------------------------------------------------
1 | import pyeapi
2 | from pprint import pprint as pp
3 |
4 | node1 = pyeapi.connect_to('veos5')
5 | node2 = pyeapi.connect_to('veos6')
6 |
7 | node1.api("ipinterfaces").create("Ethernet1")
8 | node2.api("ipinterfaces").create("Ethernet1")
9 |
10 | node1.config("ip name-server 8.8.8.8")
11 | node1.config("ip route 0.0.0.0/0 192.168.1.1")
12 |
13 | node2.config("ip name-server 8.8.8.8")
14 | node2.config("ip route 0.0.0.0/0 192.168.1.1")
15 |
16 | pp(node1.run_commands("ping cisco.com"))
17 | pp(node2.run_commands("ping cisco.com"))
18 |
19 | cmds = ["show version", "show running-config", "show management api http-commands"]
20 |
21 | pp(node1.run_commands(cmds))
22 | pp(node2.run_commands(cmds))
23 |
24 | configurations1 = [
25 | "ip routing",
26 | "interface Ethernet1",
27 | "ip address 10.0.0.1/24",
28 | "no shutdown",
29 | "interface loopback 1",
30 | "ip address 1.1.1.1/32",
31 | "router ospf 1",
32 | "network 10.0.0.0 0.0.0.255 area 0",
33 | "network 1.1.1.1 0.0.0.0 area 0",
34 | "router-id 1.1.1.1",
35 | ]
36 |
37 | configurations2 = [
38 | "ip routing",
39 | "interface Ethernet1",
40 | "ip address 10.0.0.2/24",
41 | "no shutdown",
42 | "interface loopback 1",
43 | "ip address 2.2.2.2/32",
44 | "router ospf 1",
45 | "network 10.0.0.0 0.0.0.255 area 0",
46 | "network 2.2.2.2 0.0.0.0 area 0",
47 | "router-id 2.2.2.2",
48 | ]
49 |
50 |
51 | node1.config(configurations1)
52 | node2.config(configurations2)
53 |
54 | pingHost = ["ping 1.1.1.1", "ping 2.2.2.2"]
55 |
56 | print("#" * 45)
57 | print("Printing results of ping to loopbacks advertised via ospf")
58 | pp(node1.run_commands(pingHost))
59 | pp(node1.run_commands("show running-config"))
60 |
61 | print("#" * 45)
62 | print("Printing results of ping to loopbacks advertised via ospf")
63 | pp(node2.run_commands(pingHost))
64 | pp(node2.run_commands("show running-config"))
65 |
--------------------------------------------------------------------------------
/pyeapi/demo/script2.py:
--------------------------------------------------------------------------------
1 | import pyeapi
2 | from pprint import pprint as pp
3 |
4 | node1 = pyeapi.connect_to('veos5')
5 | node2 = pyeapi.connect_to('veos6')
6 |
7 | cmds = ["show ip route", "show ip ospf neighbor"]
8 |
9 | pp(node1.run_commands(cmds))
10 | pp(node2.run_commands(cmds))
11 |
--------------------------------------------------------------------------------
/pyeapi/eapi_config_ex1.py:
--------------------------------------------------------------------------------
1 | import pyeapi
2 | from pprint import pprint as pp
3 |
4 | host1 = pyeapi.connect_to("sw1")
5 | host2 = pyeapi.connect_to("sw2")
6 |
7 | devices = [host1, host2]
8 |
9 | value = 0
10 |
11 | for host in devices:
12 | value += 1
13 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
14 | print("Pre-change State: ", host)
15 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
16 | pp(host.enable(['show running-config']))
17 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
18 | print("Post-Change State:", host)
19 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
20 | host.config(['interface loopback 0', 'ip address 1.1.1.{} 255.255.255.255'.format(value),
21 | 'description test', 'router ospf 1', 'network 0.0.0.0 255.255.255.255 area 0'])
22 | pp(host.enable(['show running-config']))
23 |
24 |
25 |
--------------------------------------------------------------------------------
/pyeapi/eapi_ex1.py:
--------------------------------------------------------------------------------
1 | import pyeapi
2 | from pprint import pprint as pp
3 |
4 | host1 = pyeapi.connect_to("sw1")
5 | host2 = pyeapi.connect_to("sw2")
6 |
7 | devices = [host1, host2]
8 |
9 | for host in devices:
10 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
11 | print("Connecting to: ", host)
12 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
13 | pp(host.enable('show version'))
14 | pp(host.enable('show running-config'))
15 |
16 |
--------------------------------------------------------------------------------
/pyeapi/eapi_ex2.py:
--------------------------------------------------------------------------------
1 | import pyeapi
2 | from pprint import pprint as pp
3 |
4 | host1 = pyeapi.connect_to("sw1")
5 | host2 = pyeapi.connect_to("sw2")
6 |
7 | devices = [host1, host2]
8 |
9 | value = 0
10 |
11 | for host in devices:
12 | value += 1
13 | print(str(value))
14 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
15 | print("Pre-change State: ", host)
16 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
17 | pp(host.enable(['show hostname', 'show running-config']))
18 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
19 | print("Post-Change State:", host)
20 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
21 | host.config(['interface loopback 0', 'ip address 1.1.1.{} 255.255.255.255'.format(value), 'description test', 'router ospf 1', 'network 0.0.0.0 255.255.255.255 area 0'])
22 | pp(host.enable(['show running-config', 'show ip route']))
23 |
24 |
25 |
--------------------------------------------------------------------------------
/pyeapi/eapi_validation_ex1.py:
--------------------------------------------------------------------------------
1 | import pyeapi
2 | from pprint import pprint as pp
3 |
4 | host1 = pyeapi.connect_to("sw1")
5 | host2 = pyeapi.connect_to("sw2")
6 |
7 | devices = [host1, host2]
8 |
9 | value = 0
10 |
11 | for host in devices:
12 | value += 1
13 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
14 | print("Current State: ", host)
15 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
16 | pp(host.enable(['show hostname', 'show running-config', 'show ip route', 'show ip ospf neighbor']))
17 |
18 |
19 |
--------------------------------------------------------------------------------
/pyeapi/interactive_scripts/pyeapi_config_script.py:
--------------------------------------------------------------------------------
1 | #(c) 2017 Todd Riemenschneider
2 | import pyeapi
3 | from pprint import pprint as pp
4 |
5 |
6 | devs_to_cfg = input("Number of devices to configure: " )
7 | count = int(devs_to_cfg)
8 |
9 | commands = {}
10 | err_host = []
11 |
12 | for i in range(count):
13 | hosts = input("Enter host device: ")
14 | cmds = input('Enter commands for device seperate with ",": ')
15 | cmd_items = cmds.split(',')
16 | print(cmd_items)
17 | commands[hosts]= cmd_items
18 | print("")
19 | print("")
20 |
21 | print(""" This is the dictionary before the loop""", commands)
22 |
23 | for k,v in commands.items():
24 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
25 | print("Pre-change State: ", k)
26 | try:
27 | node = pyeapi.connect_to(k)
28 | pp(node.enable(['show running-config']))
29 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
30 | except Exception as unknown_error:
31 | print("************************************")
32 | print("Unable to log into this device:", k)
33 | print(unknown_error)
34 | err_host.append(k)
35 | print("Errors logging into:", err_host)
36 | print("************************************")
37 | continue
38 | try:
39 | pp(node.config(v))
40 | print("Post-change state: ", k)
41 | pp(node.enable(['show running-config']))
42 | except Exception as cmd_error:
43 | print("Command not working, make sure syntax is correct")
44 | print("Problem with commands on: ", k)
45 | print(cmd_error)
46 | continue
47 |
48 | print('Problems connecting to these hosts: ', err_host)
49 |
--------------------------------------------------------------------------------
/pyeapi/interactive_scripts/pyeapi_show_cmds_script.py:
--------------------------------------------------------------------------------
1 | #(c) 2017 Todd Riemenschneider
2 | import pyeapi
3 | from pprint import pprint as pp
4 |
5 |
6 | devs_to_connect = input("Number of devices to connect to: " )
7 | count = int(devs_to_connect)
8 |
9 | commands = {}
10 | err_host = []
11 |
12 | for i in range(count):
13 | hosts = input("Enter host device: ")
14 | cmds = input('Enter commands for device seperate with ",": ')
15 | cmd_items = cmds.split(',')
16 | print(cmd_items)
17 | commands[hosts]= cmd_items
18 | print("")
19 | print("")
20 |
21 | print(""" This is the dictionary before the loop""", commands)
22 |
23 | for k,v in commands.items():
24 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
25 | print("Connecting to: ", k)
26 | try:
27 | node = pyeapi.connect_to(k)
28 | print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
29 | except Exception as unknown_error:
30 | print("************************************")
31 | print("Unable to log into this device:", k)
32 | print(unknown_error)
33 | err_host.append(k)
34 | print("Errors logging into:", err_host)
35 | print("************************************")
36 | continue
37 | try:
38 | pp(node.enable(v))
39 | print("Post-change state: ", k)
40 | except Exception as cmd_error:
41 | print("Command not working, make sure syntax is correct")
42 | print("Problem with commands on: ", k)
43 | print(cmd_error)
44 | continue
45 |
46 | print('Problems connecting to these hosts: ', err_host)
47 |
--------------------------------------------------------------------------------
/pyeapi/pyeapi_w_out_conf_file.py:
--------------------------------------------------------------------------------
1 | #Got a question asked of me if there was a way to configure pyeapi without the config file.
2 |
3 | import pyeapi
4 | conn = pyeapi.connect(host="127.0.0.1", transport="https", username="arista", password = "arista", port="8443")
5 | conn.execute(['show version'])
6 |
7 | ### It works...
8 |
--------------------------------------------------------------------------------
/restconf/create_intf.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | requests.packages.urllib3.disable_warnings()
4 |
5 | HOST = "ios-xe-mgmt.cisco.com:9443"
6 | USER = "developer"
7 | PW = "C1sco12345"
8 |
9 |
10 | url = "https://ios-xe-mgmt.cisco.com:9443/restconf/data/Cisco-IOS-XE-native:native/interface/"
11 |
12 | data = '''
13 | {
14 | "Cisco-IOS-XE-native:Loopback": {
15 | "name": 72,
16 | "description": "RESTCONF_TEST",
17 | "ip": {
18 | "address": {
19 | "primary": {
20 | "address": "72.72.72.72",
21 | "mask": "255.255.255.255"
22 | }
23 | }
24 | }
25 | }
26 | }
27 | '''
28 |
29 | headers = {
30 | 'Content-Type': 'application/yang-data+json',
31 | 'Accept': 'application/yang-data+json'
32 | }
33 |
34 | post_response = requests.post(url, auth=(USER, PW) , verify=False, headers=headers, data = data)
35 | get_response = requests.get(url, headers=headers, auth=(USER, PW), verify=False)
36 |
37 | print(post_response.text)
38 | print(get_response.text)
39 |
--------------------------------------------------------------------------------
/restconf/delete_intf.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | requests.packages.urllib3.disable_warnings()
4 |
5 | HOST = "ios-xe-mgmt.cisco.com:9443"
6 | USER = "developer"
7 | PW = "C1sco12345"
8 |
9 | url = "https://ios-xe-mgmt.cisco.com:9443/restconf/data/Cisco-IOS-XE-native:native/interface/"
10 | del_url = "https://ios-xe-mgmt.cisco.com:9443/restconf/data/Cisco-IOS-XE-native:native/interface/Loopback=72"
11 |
12 | headers = {
13 | 'Content-Type': 'application/yang-data+json',
14 | 'Accept': 'application/yang-data+json'
15 | }
16 |
17 | delete_response = requests.delete(url=del_url, auth=(USER, PW), verify=False, headers=headers)
18 | get_response = requests.get(url, headers=headers, auth=(USER, PW), verify=False)
19 |
20 | print(delete_response.text)
21 | print(get_response.text)
22 |
--------------------------------------------------------------------------------
/restconf/restconf_ex1.py:
--------------------------------------------------------------------------------
1 | # This is an example of restconf script hitting cisco devnet lab device (CSR1000V)
2 |
3 | import requests
4 |
5 | # disable warnings from SSL/TLS certificates
6 | requests.packages.urllib3.disable_warnings()
7 |
8 | # login creds
9 | HOST = "ios-xe-mgmt.cisco.com:9443"
10 | USER = 'root'
11 | PASS = 'D_Vay!_10&'
12 |
13 | # create a main() method
14 | def main():
15 | """Main method that retrieves info from the device using RESTCONF."""
16 | # Still trying to work through understanding yang models
17 | # url string to issue GET request
18 | #url = "https://{h}/restconf/data/ietf-interfaces:interfaces".format(h=HOST)
19 | #url = "https://{h}/restconf/data/Cisco-IOS-XE-native:native/interface?".format(h=HOST)
20 | # running config
21 | #url = "https://{h}/restconf//data/Cisco-IOS-XE-native:native?content=config&depth=65535".format(h=HOST)
22 | # Pull a bunch of yang modules + descriptions
23 | url = "https://{h}/restconf/data?fields=ietf-yang-library:modules-state/module".format(h=HOST)
24 | # Pull the vlans
25 | #url = "https://{h}/restconf/tailf/modules/Cisco-IOS-XE-vlan/2017-10-02".format(h=HOST)
26 | # Same as above - Pull a bunch of yang modules + descriptions
27 | #url = "https://{h}/restconf/data?fields=ietf-yang-library:modules-state/module(name;revision;schema;namespace)".format(h=HOST)
28 | #url = "https://{h}/restconf/data/ietf-restconf-monitoring:restconf-state/capabilities".format(h=HOST)
29 | # Just an example of scheme found in yang modules + descriptions
30 | #url = "https://{h}/restconf/tailf/modules/openconfig-network-instance-l3/2017-01-13".format(h=HOST)
31 |
32 |
33 | # RESTCONF media types for REST API headers
34 | headers = {'Content-Type': 'application/yang-data+json',
35 | 'Accept': 'application/yang-data+json'}
36 | # this statement performs a GET on the specified url
37 | response = requests.get(url, auth=(USER, PASS),
38 | headers=headers, verify=False)
39 |
40 | # print the json that is returned
41 | print(response.text)
42 |
43 | if __name__ == '__main__':
44 | main()
45 |
--------------------------------------------------------------------------------
/restconf/restconf_ex2.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import sys
3 | from pprint import pprint as pp
4 |
5 | # disable warnings from SSL/TLS certificates
6 | requests.packages.urllib3.disable_warnings()
7 |
8 | # use the IP address or hostname of your Cat9300
9 | HOST = 'ios-xe-mgmt.cisco.com:9443'
10 | USER = 'root'
11 | PASS = 'D_Vay!_10&'
12 |
13 |
14 | # create a main() method
15 | def main():
16 | """Main method that retrieves the Interface details from Cat9300 via RESTCONF."""
17 | # url string to issue GET request
18 | # get interfaces info
19 | url = "https://{h}/restconf/data/ietf-interfaces:interfaces".format(h=HOST)
20 | print(url)
21 | # RESTCONF media types for REST API headers
22 | headers = {'Content-Type': 'application/yang-data+json',
23 | 'Accept': 'application/yang-data+json'}
24 | # this statement performs a GET on the specified url
25 | # the response variable will store the data in a json format
26 | response = requests.get(url, auth=(USER, PASS),
27 | headers=headers, verify=False).json()
28 | # pretty print is used make reading the json output easier
29 | pp(response)
30 |
31 | if __name__ == '__main__':
32 | sys.exit(main())
33 |
--------------------------------------------------------------------------------
/telnetlib/script_output.txt:
--------------------------------------------------------------------------------
1 | root@debian:/home/todd/gns3# python3 telnet_py3.py
2 | Enter host IPs u want to connect to seperate using a space : 192.168.11.2
3 | Enter cmd seperate with a ',' : show ver, show ip int brief
4 | Username: cisco
5 | Password:
6 | Connecting to host: 192.168.11.2
7 |
8 | R2#term length 0
9 | R2#show ver
10 | Cisco IOS Software, 7200 Software (C7200-ADVENTERPRISEK9-M), Version 15.2(4)S7, RELEASE SOFTWARE (fc4)
11 | Technical Support: http://www.cisco.com/techsupport
12 | Copyright (c) 1986-2015 by Cisco Systems, Inc.
13 | Compiled Wed 01-Apr-15 20:30 by prod_rel_team
14 |
15 | ROM: ROMMON Emulation Microcode
16 | BOOTLDR: 7200 Software (C7200-ADVENTERPRISEK9-M), Version 15.2(4)S7, RELEASE SOFTWARE (fc4)
17 |
18 | R2 uptime is 1 hour, 20 minutes
19 | System returned to ROM by unknown reload cause - suspect boot_data[BOOT_COUNT] 0x0, BOOT_COUNT 0, BOOTDATA 19
20 | System image file is "tftp://255.255.255.255/unknown"
21 | Last reload reason: Unknown reason
22 |
23 |
24 |
25 | This product contains cryptographic features and is subject to United
26 | States and local country laws governing import, export, transfer and
27 | use. Delivery of Cisco cryptographic products does not imply
28 | third-party authority to import, export, distribute or use encryption.
29 | Importers, exporters, distributors and users are responsible for
30 | compliance with U.S. and local country laws. By using this product you
31 | agree to comply with applicable laws and regulations. If you are unable
32 | to comply with U.S. and local laws, return this product immediately.
33 |
34 | A summary of U.S. laws governing Cisco cryptographic products may be found at:
35 | http://www.cisco.com/wwl/export/crypto/tool/stqrg.html
36 |
37 | If you require further assistance please contact us by sending email to
38 | export@cisco.com.
39 |
40 | Cisco 7206VXR (NPE400) processor (revision A) with 491520K/32768K bytes of memory.
41 | Processor board ID 4279256517
42 | R7000 CPU at 150MHz, Implementation 39, Rev 2.1, 256KB L2 Cache
43 | 6 slot VXR midplane, Version 2.1
44 |
45 | Last reset from power-on
46 |
47 | PCI bus mb0_mb1 (Slots 0, 1, 3 and 5) has a capacity of 600 bandwidth points.
48 | Current configuration on bus mb0_mb1 has a total of 600 bandwidth points.
49 | This configuration is within the PCI bus capacity and is supported.
50 |
51 | PCI bus mb2 (Slots 2, 4, 6) has a capacity of 600 bandwidth points.
52 | Current configuration on bus mb2 has a total of 0 bandwidth points
53 | This configuration is within the PCI bus capacity and is supported.
54 |
55 | Please refer to the following document "Cisco 7200 Series Port Adaptor
56 | Hardware Configuration Guidelines" on Cisco.com
57 | for c7200 bandwidth points oversubscription and usage guidelines.
58 |
59 |
60 | 3 FastEthernet interfaces
61 | 4 Serial interfaces
62 | 509K bytes of NVRAM.
63 |
64 | 8192K bytes of Flash internal SIMM (Sector size 256K).
65 | Configuration register is 0x2102
66 |
67 | R2# show ip int brief
68 | Interface IP-Address OK? Method Status Protocol
69 | FastEthernet0/0 192.168.11.2 YES manual up up
70 | FastEthernet1/0 unassigned YES unset administratively down down
71 | FastEthernet1/1 unassigned YES unset administratively down down
72 | Serial2/0 unassigned YES unset administratively down down
73 | Serial2/1 unassigned YES unset administratively down down
74 | Serial2/2 unassigned YES unset administratively down down
75 | Serial2/3 unassigned YES unset administratively down down
76 | R2#exit
77 |
78 | root@debian:/home/todd/gns3#
79 |
--------------------------------------------------------------------------------
/telnetlib/telnet_py3.py:
--------------------------------------------------------------------------------
1 | #This is the telnet Library for Python3
2 | #Make sure transport input telnet is enabled on router validate
3 | #This scripts will run commands you choose on the remote devices using telnet as transport
4 | #The results will be print to screen and captured in files named ("router_" + HOST)
5 | #(c) 2017 Todd Riemenschneider
6 |
7 | from getpass import getpass
8 | import telnetlib
9 |
10 | host = input("Enter host IPs u want to connect to seperate using a space : ")
11 | cmd = input("Enter cmd seperate with a ',' : ")
12 | user = input("Username: ")
13 | password = getpass("Password: ")
14 |
15 | #create lists to iterate through
16 | hosts = host.split()
17 | cmds = cmd.split(",")
18 |
19 | for HOST in hosts:
20 | print("Connecting to host:", HOST)
21 | tn = telnetlib.Telnet(HOST)
22 | tn.read_until(b"Username: ")
23 | tn.write(user.encode('ascii') + b"\n")
24 | if password:
25 | tn.read_until(b"Password: ")
26 | tn.write(password.encode('ascii') + b"\n")
27 |
28 | tn.write(b"term length 0\n")
29 | #iterate through cmds using for loop
30 | for CMD in cmds:
31 | tn.write(CMD.encode('ascii') + b"\n")
32 | tn.write(b"exit\n")
33 | readoutput = tn.read_all().decode('ascii')
34 | saveoutput = open("router_" + HOST, "w")
35 | saveoutput.write(readoutput)
36 | saveoutput.write("\n")
37 | saveoutput.close
38 | #This command will print out the saved output on your screen
39 | print(readoutput)
40 |
--------------------------------------------------------------------------------
/telnetlib/telnet_script_enable_mode.py:
--------------------------------------------------------------------------------
1 | #This is the telnet Library for Python3
2 | #Make sure transport input telnet is enabled on router validate
3 | #This scripts will run commands you choose on the remote devices using telnet as transport
4 | #The results will be print to screen and captured in files named ("router_" + HOST)
5 | #(c) 2017 Todd Riemenschneider
6 |
7 | from getpass import getpass
8 | import telnetlib
9 |
10 | user = input("Username: ")
11 | password = getpass("Password: ")
12 | enpw = getpass("Enable: ")
13 |
14 | with open('host_file.txt') as f:
15 | hosts = f.read().splitlines()
16 |
17 | commands = '''
18 | show cdp neighbor
19 | show run
20 | show version
21 | show inventory
22 | '''
23 |
24 | cmds = commands.splitlines()
25 |
26 |
27 | for HOST in hosts:
28 | print("Connecting to host:", HOST)
29 | tn = telnetlib.Telnet(HOST)
30 | tn.read_until(b"Username: ")
31 | tn.write(user.encode('ascii') + b"\n")
32 | if password:
33 | tn.read_until(b"Password: ")
34 | tn.write(password.encode('ascii') + b"\n")
35 | tn.write(b"enable \n")
36 | tn.read_until(b"Password: ")
37 | tn.write(enpw.encode('ascii') + b"\n")
38 |
39 | tn.write(b"term length 0\n")
40 | #iterate through cmds using for loop
41 | for CMD in cmds:
42 | tn.write(CMD.encode('ascii') + b"\n")
43 | tn.write(b"exit\n")
44 | readoutput = tn.read_all().decode('ascii')
45 | saveoutput = open("router_" + HOST, "w")
46 | saveoutput.write(readoutput)
47 | saveoutput.write("\n")
48 | saveoutput.close
49 | #This command will print out the saved output on your screen
50 | print(readoutput)
51 |
52 |
--------------------------------------------------------------------------------