Exemple #1
0
    "host": "10.91.126.199",
    "username": "******",
    "password": "******",
    "device_type": "cisco_xr",
}

net_connect = Netmiko(**cisco1)
failure_command = ['int HundredGigE0/0/1/0', 'shut']
repair_command = ['int HundredGigE0/0/1/0', 'no shut']

print()
print(net_connect.find_prompt())
## this loop will run 2 times, means will fail the link 2 times and repair the link 2 times
no_of_failure_repair = 4
for x in range(int(no_of_failure_repair / 2)):
    output = net_connect.send_config_set(failure_command)
    net_connect.commit()
    print(output)
    time.sleep(10)
    output = net_connect.send_config_set(repair_command)
    net_connect.commit()
    print(output)
    time.sleep(10)

net_connect.exit_config_mode()
net_connect.disconnect()

print("***** log out of device")
time.sleep(90)
print("***** 90 seconds sleep done")
            # grab VLAN from dict
            vlan = i['vlan']

    # seperate the VLAN into digits
    splitvlan = list(str(vlan))
    # first digit of the vlan
    netvlan = splitvlan[0]
    # second digit of the vlan, change to an int so we can add to it
    intvlan = int(splitvlan[1])

    # reset number back to 0
    if intvlan == 9:
        intvlan = 0
    # skip 7
    elif intvlan == 6:
        intvlan += 2
    # increment VLAN
    else:
        intvlan += 1

    # combine both integers, change intvlan back to str
    newvlan = netvlan + str(intvlan)

    # send commands
    config_commands = [
    'int '+intf,
    'swi acc vlan '+newvlan
    ]

    net_connect.send_config_set(config_commands)
Exemple #3
0
from netmiko import Netmiko
from getpass import getpass
from pprint import pprint
from datetime import datetime

#password = getpass()
devices = {'host': 'cisco3.lasthop.io', 'username': '******', 'password': '******', 'device_type': 'cisco_xe', 'session_log': 'logging.txt', 'fast_cli:True'}

ssh_conn = Netmiko(**devices)
print(ssh_conn.find_prompt())

commands = ['ip name-server 1.1.1.1', 'ip name-server 1.0.0.1', 'ip domain-lookup']
verify_command = "ping google.com"

start_time = datetime.now()
push1 = ssh_conn.send_config_set(commands)
print(push1)
push2 = ssh_conn.send_command(verify_command)

if "!!" in push2:
    print("Ping Successful:")
    print(f"Result :{push2}")
else:
    print("Not Working FIX IT")
    
end_time = datetime.now()
print(f"Execution Time for delay of 2 :{end_time} : {start_time}")



# set list of commands to pass to net_command.send_config_set
commands_Router1 = [
    "interface g0/0",
    "desc This has changed",
]

commands_Router2 = [
    "interface g0/1",
    "desc This has changed too",
]

#  ssh to device, pass in dictionary to net_connect
net_connect = Netmiko(**Router1)

print("\nRunning commands to S1...\n\n" + net_connect.find_prompt())
output = net_connect.send_config_set(commands_Router1)
output = net_connect.save_config
print(output)
print("\n\n")
output = net_connect.send_command("show int des")
print(output)
print("\n\nCommands to Router1 complete")
net_connect.disconnect()

net_connect = Netmiko(**Router2)

print("\nRunning commands to R1...\n\n" + net_connect.find_prompt())
output = net_connect.send_config_set(commands_Router2)
output = net_connect.save_config()
print(output)
output = net_connect.send_command("show int des")
    # "username": "******",
    # "password": getpass(),
	"global_delay_factor":4,
	#"blocking_timeout": 8,
    # "default_enter":'\r\n',
	# "default_enter":'\r',
    "device_type": "cisco_ios_telnet"  
}
print("Initalizing Router 1...")
hostname = "bxcs-r-btbbmr491045"
loopback10 = "172.108.23.5 255.255.255.255"
vlan1_ip = "10.10.160.4 255.255.255.0"

net_connect = Netmiko(**XIAN_1)
print(net_connect.enable())
print(net_connect.send_config_set("hostname "+hostname))
print(net_connect.send_config_set("int lo10 \r no sh \r ip addr "+loopback10))
print(net_connect.send_config_set("int vlan 1 \r no sh \r ip addr "+vlan1_ip))
print(net_connect.send_command("show ip int brief"))
net_connect.disconnect()

XIAN_2 = {
    "host": "10.31.3.1",
	"port":17004,
    # "username": "******",
    # "password": getpass(),
	"global_delay_factor":4,
	#"blocking_timeout": 8,
    # "default_enter":'\r\n',
	# "default_enter":'\r',
    "device_type": "cisco_ios_telnet"  
Exemple #6
0
Use send_config_set() and send_config_from_file() to make configuration changes.
The configuration changes should be benign. For example, on Cisco IOS I typically change the
logging buffer size.
As part of your program verify that the configuration change occurred properly. For example, use
send_command() to execute 'show run' and verify the new configuration.
"""

from netmiko import Netmiko
from getpass import getpass

my_device = {
    "host": "10.10.10.10",
    "username": "******",
    "password": getpass(),
    "device_type": "cisco_ios"
}

net_conn = Netmiko(**my_device)
command_logging = "show conf | inc logging"

show_log = net_conn.send_command(command_logging)
print(show_log)

config_update = net_conn.send_config_set("logging buffered 10000")
print(config_update)

config_from_file = net_conn.send_config_from_file("config.txt")
print(config_from_file)

print(show_log)
from netmiko import Netmiko
from yaml import safe_load
from jinja2 import Environment, FileSystemLoader

router = {
    'ip': '10.10.20.30',
    'port': '22',
    'username': '******',
    'password': '******',
    'device_type': 'cisco_xe'
}

with open("vars/variables.yml", "r") as handle:
    data = safe_load(handle)

my_template = Environment(loader=FileSystemLoader('templates'))
template = my_template.get_template("netmiko.j2")
netmiko_payload = template.render(data=data)

net_connect = Netmiko(**router)
output = net_connect.send_config_set(netmiko_payload.split('\n'))
print(f"Added subscriptions successfully. Here are the commands we used:")
print(output)
net_connect.disconnect()
Exemple #8
0
    'host': '10.1.1.253',
    'username': '******',
    'password': '******',
    'device_type': 'cisco_ios_telnet',  # Telnet
    # 'device_type': 'cisco_ios',  # SSH
    'secret': 'Cisc0123',
}

# 支持的device_types
# https://github.com/ktbyers/netmiko/blob/master/netmiko/ssh_dispatcher.py
# 主要是CLASS_MAPPER_BASE部分

# ">" 下的exec命令
net_connect = Netmiko(**CSR1)  # ** 表示使用字典映射的方式来传参数
# Netmiko(host='10.1.1.253', username='******', password='******', device_type='cisco_ios_telnet', secret='Cisc0123')
print(net_connect.send_command("show ip interface brief"))

# "#" 下的exec命令
net_connect.enable()  # 如果需要, 使用enable进入特权模式
print(net_connect.send_command("show run"))

# 全局配置模式下的配置命令
config_commands = [
    'router ospf 1', 'router-id 1.1.1.1', 'network 1.1.1.1 0.0.0.0 a 0'
]

output = net_connect.send_config_set(config_commands)
print(output)

net_connect.disconnect()
from netmiko import Netmiko
from Netmiko_project.credentails import password1, username1
cisco1 = {
    "host": "10.223.44.102",
    "username": username1,
    "password": password1,
    "device_type": "cisco_ios",
}

# I was forced to use my own TACACS credentials to make this work

commands = ["logging history size 500"]

net_connect = Netmiko(**cisco1)

print(net_connect.find_prompt())
net_connect.send_config_set("conf t")
net_connect.send_config_set(commands)
output = net_connect.send_command("sh run | i logging ")
net_connect.disconnect()

print(output)


 neighbor {{ bgp.neighbor_address }} remote-as {{ bgp.peer_asn }}
 neighbor {{ bgp.neighbor_address }} description ebgp-to-{{ bgp.remote_router_name }}
 neighbor {{ bgp.neighbor_address }} password {{ bgp.password }}
 neighbor {{ bgp.neighbor_address }} timers 1 3
 neighbor {{ bgp.neighbor_address }} advertisement-interval 1

'''

print(r4_bgp_nei_dict)

output = template.render(bgp=r4_bgp_nei_dict)

print(output)
print(type(output))

pprint(net_conn_r4.send_config_set(output))

print("****" * 25)

ENV = Environment(loader=FileSystemLoader('.'))
template = ENV.get_template("ebgp_neighbor_template.j2")

my_device = {
    "host": "r5",
    "username": "******",
    "password": "******",
    "device_type": "cisco_ios"
}

net_conn_r5 = Netmiko(**my_device)
Exemple #11
0
new.remove('nxos2')
# Get rid of null strings in the list
new = list(filter(None, new))
# Strip white space from strings in the list using list comprehension
new = [line.strip() for line in new]

# Create list slices from original list with each devices corresponding config
nxos1_config = new[:5]  # Index 0  to Index 4 list slice
nxos2_config = new[5:]  # Index 5 to 9 list slice.

x = 0
# Connect to each device one by one
for device in (nxos1, nxos2):
    net_connection = Netmiko(**device)
    if x == 0:  # Send config to first device
        output = net_connection.send_config_set(nxos1_config)
        print(output)
    if x == 1:  # Send config to 2nd device
        output = net_connection.send_config_set(nxos2_config)
        print(output)
        # Sleep for 20s allowing time for BGP connection to establish
        time.sleep(20)
        # Verify that the BGP neighbourship has formed
        output += net_connection.send_command('show ip bgp neighbors')
        # Check that neighbour is in Established state and print confirmation
        if 'BGP state = Established' in output:
            print('-' * 80)
            print('BGP neighbourship has been established')

    # Gracefully disconnect from SSH session
    net_connection.disconnect()
    # "password": getpass(),
    "global_delay_factor": 4,
    "blocking_timeout": 8,
    # "default_enter":'\r\n',
    # "default_enter":'\r',
    "device_type": "cisco_ios_telnet"
}
print('Script Started!')

cfg_commands = ["logging buffered 10000", "no logging console"]
net_connect = Netmiko(**cisco1)

# print(net_connect.send_config_set("en"))
print(net_connect.enable())
print(net_connect.send_command("show ip int brief"))

print(net_connect.send_command("show int | i rate"))
# print(net_connect.send_command("show int summary"))
#output = net_connect.send_config_set("en")
# print(output)
#output = net_connect.send_config_set(cfg_commands)
# print(output)
# print(net_connect.send_config_set("int gi0/1"))
print(
    net_connect.send_config_set(
        "int gi0/1 \r ip address 172.10.10.2 255.255.255.0 \r no sh"))
# print(net_connect.send_config_set("ip address 172.10.10.1 255.255.255.255"))

print(net_connect.send_command("show ip int brief"))
net_connect.disconnect()
Exemple #13
0
#! /usr/local/Python_envs/Python3/bin/python3
from netmiko import Netmiko

fw_01 = {
    'host': '192.168.0.21',
    'username': '******',
    'password': '******',
    'device_type': 'fortinet'
}
print(f"{'#'*20} Connecting to the Device {'#'*20}")
net_connect = Netmiko(**fw_01)
print(f"{'#'*20} Connected {'#'*20}")
# print(net_connect.find_prompt())

# command = 'show full-configuration'
# full_config = net_connect.send_command(command)
# print(full_config)

config = [
    'config firewall address', 'edit IP_101', 'set type ipmask',
    'set subnet 192.168.0.101/32', 'end'
]
send_config = net_connect.send_config_set(config)

print(send_config)
Exemple #14
0
#!/usr/bin/env python

from netmiko import Netmiko
from credentials import password1, username1
cisco1 = {
    "host": "10.223.44.102",
    "username": username1,
    "password": password1,
    "device_type": "cisco_ios",
}

commands = ["logging history size 500"]

net_connect = Netmiko(**cisco1)

print()
print(net_connect.find_prompt())
net_connect.send_config_set("conf t")
output = net_connect.send_config_set(commands, exit_config_mode=False)
print(output)
# I was no able to use "and_quite"
output = net_connect.commit(and_quit=True)
print(output)
output = net_connect.send_command("sh run | i logging ")
print(output)

net_connect.disconnect()
Exemple #15
0
def main():

    # Get device(s) to connect to
    while True:
        try:
            devs = input(
                "Enter a space delimited list of device IPs: ").split()
            for i in range(0, len(devs)):
                devs[i] = ipaddress.IPv4Address(devs[i])
        except:
            if input(
                    "Invalid data entered. Press any key to continue or 'q' to quit. "
            ) == 'q':
                exit()
        else:
            break

    if len(devs) > 0:

        # gather username and password
        cisco_user = input("Device Username: "******"Device Password: "******"host": str(dev),
                "username": cisco_user,
                "password": cisco_pass,
                "device_type": "cisco_ios",
            }

            # Attempt connection
            try:
                net_connect = Netmiko(**conn)
                vers = net_connect.send_command('show version')
            except:
                pass
            else:
                # Special handling for Nexus
                if "Nexus" in vers:
                    command = 'show int brief | inc down'

                # Normal handling for IOS
                else:
                    command = 'show ip int brief | inc down'

                # Get list of down ports and configure as client access ports
                ports = net_connect.send_command(command).split()
                for port in ports:
                    int_commands = [
                        f'interface {port}', 'switchport mode access',
                        'switchport access vlan 2', 'switchport voice vlan 10',
                        'spanning portfast', 'spanning link point',
                        'no logging event link', 'no snmp trap link'
                    ]
                    if port.startswith(
                        ('Eth', 'eth', 'Gig', 'gig', 'Fa', 'fa')):
                        output = net_connect.send_config_set(int_commands)
                        print(output)
Exemple #16
0
def main():
    """
    Execution starts here.
    """

    # Read host file into structured data, may raise YAMLerror.
    #
    #
    with open("host.yml", "r") as handle:
        host_root = safe_load(handle)

    # Netmiko uses "cisco_ios" instead of "ios"  AND
    # "cisco_xr" instead of "iosxr", so use a mapping dict to convert
    # "cisco_nxos" instead of "nxos"
    platform_map = {"ios": "cisco_ios", "nxos": "cisco_nxos"}

    # Iterate over the list of hosts (list of dictionaries)
    for host in host_root["host_list"]:

        # uset the map to get the poper netmiko paltform
        platform = platform_map[host["platform"]]

        # Load the host-specific VLAN state:
        with open(f"vars/{host['name']}_vlans.yml", "r") as handle:
            vlans = safe_load(handle)

        # Setup the jinja2 templating environment and render the tempate
        j2_env = Environment(loader=FileSystemLoader("."),
                             trim_blocks=True,
                             autoescape=True)
        template = j2_env.get_template(
            f"templates/netmiko/{host['platform']}_vlans.j2")
        new_vlan_config = template.render(data=vlans)

        # Parmiko can be ssh client or server..
        # conn_params = paramiko.SSHClient()
        # We dont need paramiko to refuse connections due to missing keys.
        # conn_params.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # conn_params.connect(
        #    hostname=host["name"],
        #    port=22,
        #    username="******",
        #    password="******",
        #    look_for_keys=False,
        #    allow_agent=False,

        # Create a netmiko SSH connection handler to access the device:
        conn = Netmiko(
            host=host["name"],
            username="******",
            password="******",
            device_type=platform,
        )

        # Get interactive shell and wait a bit for the prompt to appear.
        # conn = conn_params.invoke_shell()
        # time.sleep(1.0)
        print(f"Logged into {conn.find_prompt()} successfully")

        # Send configuration string to the device. Netmiko
        # takes a list of strings, not a giant \n-delimted string,
        # so use the .split() function
        result = conn.send_config_set(new_vlan_config.split("\n"))

        # Netmiko automatically collect the results,  you can ignore them
        # or process them further.
        print(result)

        # close session when we are done..
        conn.disconnect()
Exemple #17
0
from netmiko import Netmiko
import logging

logging.basicConfig(
    filename="test.log",
    level=logging.DEBUG)  # It will log all reads and writes on the SSH channel
logger = logging.getLogger("netmiko")

host1 = {  # Enter Device information
    "host": "129.9.0.101",
    "username": "******",
    "password": "******",
    "device_type": "huawei",
    "global_delay_factor": 0.1,  # Increase all sleeps by a factor of 1
}

net_connect = Netmiko(**host1)
command1 = ["interface eth-trunk 1",
            "description TEST123456"]  # Enter set of commands

print("Connected to:", net_connect.find_prompt())  # Display hostname
output = net_connect.send_config_set(
    command1, delay_factor=.5)  # Run set of commands in order
# Increase the sleeps for just send_command by a factor of 2

net_connect.disconnect()  # Disconnect from Session
print(output)
Exemple #18
0
def main():
    while True:
        try:
            dev_ips = input(
                "Destination IP or IPs (space delimited): ").split()
            for i in range(0, len(dev_ips)):
                dev_ips[i] = ipaddress.IPv4Address(dev_ips[i])
            add_ips = input(
                "DHCP relay IP(s) to add (space delimited): ").split()
            for i in range(0, len(add_ips)):
                add_ips[i] = ipaddress.IPv4Address(add_ips[i])
            rem_ips = input(
                "DHCP relay IP(s) to remove (space delimited): ").split()
            for i in range(0, len(rem_ips)):
                rem_ips[i] = ipaddress.IPv4Address(rem_ips[i])
            vlans = input(
                "VLAN ID(s) to update (number only, space delimited): ").split(
                )
            for i in range(0, len(vlans)):
                if not vlans[i].isnumeric() or int(vlans[i]) < 0 or int(
                        vlans[i]) > 4094:
                    vlans.pop(i)
        except:
            if input(
                    "Invalid data entered. Press any key to continue or 'q' to quit. "
            ) == 'q':
                exit()
        else:
            break

    if len(add_ips) > 0 or len(rem_ips) > 0:
        # gather username and password
        cisco_user = input("username: "******"ip helper-address "
        rem_comm = "no ip helper-address "
        print("Please wait while the update is being performed")

        for ip in dev_ips:
            conn = {
                "host": str(ip).rstrip("\n"),
                "username": cisco_user,
                "password": cisco_pass,
                "device_type": "cisco_ios",
            }

            try:
                net_connect = Netmiko(**conn)
                vers = net_connect.send_command('show version')
            except:
                print(f"Connection to {ip} failed")
            else:
                hostname = net_connect.find_prompt().split('#')[0]
                # Special handling for Nexus
                if "Nexus" in vers:
                    add_comm = "ip dhcp relay address "
                    rem_comm = "no ip dhcp relay address "
                for vlan in vlans:
                    for i in rem_ips:
                        net_connect.send_config_set(
                            ['interface vlan ' + vlan, rem_comm + str(i)])
                    for i in add_ips:
                        net_connect.send_config_set(
                            ['interface vlan ' + vlan, add_comm + str(i)])
                    print(f"Updated DHCP relays for VLAN {vlan}")
                net_connect.disconnect()
                print(f"Successfully updated DHCP relays on {hostname}")
Exemple #19
0
ip_list = [
    "192.168.100.1", "192.168.100.2", "192.168.100.3", "192.168.100.254"
]

# Entrar en los dispositivos a traves de SSH con la libreria Netmiko
for ip in ip_list:
    dispositivo = {
        "username": username,
        "ip": ip,
        "password": password,
        "device_type": "cisco_ios",
        "secret": secret,
    }

    net_connect = Netmiko(**dispositivo)
    net_connect.enable()

    output = net_connect.send_command("show cdp")

    if "% CDP is not enabled" in output:
        print("CDP no esta habilitado en {}".format(ip))

        # command = ["no cdp run"]
        # net_connect.send_config_set("no cdp run")
    else:
        print("CDP esta habilitado en {}.".format(ip))
        command = ["no cdp run"]
        net_connect.send_config_set("no cdp run")

    net_connect.save()
Exemple #20
0
class Client:
    def __init__(self, platform, hostname, username, password, port, keys):
        self.platform = platform
        self.hostname = hostname
        self.username = username
        self.password = password
        self.port = port
        self.keys = keys
        self.net_connect = None

    def connect(self):
        if self.keys:
            try:
                self.net_connect = Netmiko(device_type=self.platform,
                                           host=self.hostname,
                                           port=self.port,
                                           pkey=self.keys,
                                           use_keys=True,
                                           username=self.username,
                                           passphrase=self.password)
            except Exception as err:
                return_error(err)
        else:
            try:
                self.net_connect = Netmiko(device_type=self.platform,
                                           host=self.hostname,
                                           port=self.port,
                                           use_keys=True,
                                           username=self.username,
                                           password=self.password)
            except Exception as err:
                return_error(err)

    def disconnect(self):
        try:
            if self.net_connect:
                self.net_connect.disconnect()
        except Exception as err:
            return_error(err)

    def cmds(self, require_exit, exit_argument, commands, enable, isConfig):
        try:
            output = {
                "Hostname": self.hostname,
                "Platform": self.platform,
                "Commands": []
            }
            self.connect()
            if enable:
                self.net_connect.enable()  # type: ignore
            if isConfig:
                output['Commands'].append({
                    "Hostname":
                    self.hostname,
                    "DateTimeUTC":
                    datetime.utcnow().isoformat(),
                    "Config":
                    self.net_connect.send_config_set(commands)
                })  # type: ignore
            if not isConfig:
                for cmd in commands:
                    prompt = self.net_connect.find_prompt()  # type: ignore
                    c = {
                        "Hostname":
                        self.hostname,
                        "DateTimeUTC":
                        datetime.utcnow().isoformat(),
                        "Command":
                        cmd,
                        "Output":
                        f"{prompt} {self.net_connect.send_command_timing(cmd)}"
                    }  # type: ignore
                    output['Commands'].append(c)

        except Exception as err:
            return_error(err)
        finally:
            self.disconnect()
        return output
Exemple #21
0
class CiscoExample5:
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

        self.env_creds = env_file.get(path="env\ssh")

        self.ssh_details = {
            "device_type": "cisco_ios",
            "ip": self.ip,
            "port": self.port,
            "username": self.env_creds["SSH_USERNAME"],
            "password": self.env_creds["SSH_PASSWORD"],
            "secret": self.env_creds["SSH_SECRET"]
        }

        self.ssh_session = Netmiko(**self.ssh_details)
        self.ssh_session.enable()

    def create_vlan(self, vlan_id, vlan_name=""):
        if not self.validate_vlan(vlan_id):
            return {
                "error":
                True,
                "details":
                "Not a valid VLAN. Ensure this is passed as an integer to the function and is within the valid VLAN range"
            }

        if self.check_vlan_exist(vlan_id):
            return {"error": True, "details": "VLAN already exist on device"}

        cmds = ["vlan {}".format(vlan_id)]
        if vlan_name:
            cmds.append("name {}".format(vlan_name))

        self.ssh_session.send_config_set(cmds)

        #Perform verification check
        if self.check_vlan_exist(vlan_id):
            return {
                "error": False,
                "details":
                "VLAN {} has been successfully created".format(vlan_id)
            }
        else:
            return {
                "error":
                True,
                "details":
                "VLAN {} has not been successfully created".format(vlan_id)
            }

    def get_vlans(self):
        output = self.ssh_session.send_command("show vlan brief | begin 1")
        split_output = output.split(
            "\n"
        )  #Assuming the above command pulls the right info, we can just split into lines, and then hard code the index splicing

        vlans = []
        for line in split_output:
            vlan = line.split()
            vlans.append({
                "vlan_id":
                int(vlan[0]),  #0 will always be VLAN ID in Cisco IOS
                "vlan_name": vlan[1]  #1 will always be VLAN Name in Cisco IOS
            })

        #Try to avoid when possible, hardcoding values like the above example...
        return vlans

    def check_vlan_exist(self, vlan_id):
        if not self.validate_vlan(vlan_id):
            return {
                "error":
                True,
                "details":
                "Not a valid VLAN. Ensure this is passed as an integer to the function and is within the valid VLAN range"
            }

        found_vlan = False
        vlans = self.get_vlans(
        )  # A function we implemented above to get the vlans in a python dictionary format to make it easier to loop through the vlans on the device

        for vlan in vlans:
            if vlan["vlan_id"] == vlan_id:
                found_vlan = True

        return found_vlan

    def validate_vlan(self, vlan_id):  # Taken from example-2
        if isinstance(vlan_id, int):
            if vlan_id in range(1, 4095):
                return True
        return False
Exemple #22
0
    'username': '******',
    'password': '******',
    'device_type': 'cisco_ios',
    'session_log': 'l2ex4.txt',
    'fast_cli': True
}

net_connection = Netmiko(**device)
print(net_connection.find_prompt())

command = ('sh ip name-server')
output = net_connection.send_command(command, expect_string="#")
command = ('ping google.com')
output += net_connection.send_command(command)
print(output)

config = [
    'ip name-server 1.1.1.1', 'ip name-server 1.0.0.1', 'ip domain-lookup'
]

output = net_connection.send_config_set(config,
                                        strip_command=False,
                                        strip_prompt=False)
print(output)

command = ('sh ip name-server')
output = net_connection.send_command(command, expect_string="#")
command = ('ping google.com')
output += net_connection.send_command(command)
print(output)
Exemple #23
0
from netmiko import Netmiko
print('Before Connection')
host = input("Enter Firewall IP/Hostname:")
connection = Netmiko(host=(host), port ='22', username='******', password='******', device_type='fortinet')
enter_vdom_config_mode = connection.send_config_set('config global')
edit_vdom = connection.send_config_set('get system vdom-property | grep name:')
print(edit_vdom)
Exemple #24
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

device = {
    'host': 'srx1.twb-tech.com', 
    'username': '******', 
    'password': getpass(), 
    'device_type': 'juniper_junos',
}

commands = [
    'set system syslog archive size 240k files 3 '
]

net_connect = Netmiko(**device)

print()
print(net_connect.find_prompt())
output = net_connect.send_config_set(commands, exit_config_mode=False)
output += net_connect.commit(and_quit=True)
print(output)
print()

net_connect.disconnect()
Exemple #25
0
        inventory['device_type'] = vals['Device type']

        inv_list.append(inventory.copy())

for items in inv_list:
    print('\nCurrent device: ' + items['device'])

    with open(jinja_template) as f:
        tfile = f.read()
    template = jinja2.Template(tfile)
    cfg_list = template.render(items).split('\n')

    conn = Netmiko(host=items['ip'],
                   device_type=items['device_type'],
                   username=items['username'],
                   password=items['password'],
                   port=items['port'])

    conn.write_channel("\n")
    time.sleep(1)
    output = conn.read_channel()
    if 'initial configuration dialog' in output:
        conn.write_channel('no\n')
        time.sleep(1)

    output = conn.enable()
    output = conn.send_config_set(cfg_list)

    print(output)

    conn.disconnect()
Exemple #26
0
from netmiko import Netmiko

devices = [{
    "device_type": "cisco_xe",
    "ip": "ios-xe-mgmt-latest.cisco.com",
    "username": "******",
    "password": "******",
    "port": "8181",
}]

description = 'Description set with Netmiko'

description_config = [
    "interface GigabitEthernet3",
    f"description {description}",
]

for device in devices:
    net_connect = Netmiko(**device)
    output = net_connect.send_config_set(description_config)
    print(output)
    net_connect.disconnect()
Exemple #27
0
from netmiko import Netmiko
from getpass import getpass

ip_addr = sys.argv[1]
username = sys.argv[2]

my_device = {
    'host': ip_addr,
    'username': username,
    'password': getpass(),
    'device_type': 'cisco_ios'
}

cfg_commands = ['logging buffered 10000', 'no logging console']

net_conn = Netmiko(**my_device)

cfg_cmds_output = net_conn.send_config_set(cfg_commands)

cfg_file_output = net_conn.send_config_from_file('config.txt')
print(cfg_file_output)

sh_run_output = net_conn.send_command('show running-config all | i logging')

if cfg_commands[0] in sh_run_output and cfg_commands[1] in sh_run_output:
    print("Commands committed successfully!")
else:
    print("Commands not committed.")

net_conn.disconnect()
Exemple #28
0
output_r4 = template.render(bgp=r4_bgp)
output_r5 = template.render(bgp=r5_bgp)


my_device_r4 = {
    "host": "r4",
    "username": "******",
    "password": "******",
    "device_type": "cisco_ios"
}

my_device_r5 = {
    "host": "r5",
    "username": "******",
    "password": "******",
    "device_type": "cisco_ios"
}

net_conn_r4 = Netmiko(**my_device_r4)

print(net_conn_r4.find_prompt())

pp(net_conn_r4.send_config_set(output_r4))

net_conn_r5 = Netmiko(**my_device_r5)

print(net_conn_r5.find_prompt())

pp(net_conn_r5.send_config_set(output_r5))

Exemple #29
0
for host in device["lista_host"]:
    plataform = maps_so[host["plataforma"]]

    # Abrimos nuestro archivo con las variables para cargar la configuracion
    with open(f"hosts_vars/{plataform}_conf.yml", "r") as handle:
        ntps = safe_load(handle)

    # Creamos el entorno para jinja2
    jinja_env = Environment(loader=FileSystemLoader("."),
                            trim_blocks=True,
                            autoescape=True)
    template = jinja_env.get_template(f"templates/{plataform}_ntp.j2")
    nueva_config = template.render(data=ntps)
    pdb.set_trace()

    # realizamos la conexión con Netmiko
    conexion = Netmiko(
        host=host["name"],
        username="******",
        password="******",
        device_type=plataform,
    )

    print(f"Ingresando en el equipo {conexion.find_prompt()}, corectamente")
    resultado = conexion.send_config_set(nueva_config.split("\n"))

    print(resultado)

    conexion.close()
Exemple #30
0
    host = raw_input("Enter host to connect to: ")
except NameError:
    host = input("Enter host to connect to: ")

password = getpass()
device = {
    'host': host,
    'username': '******',
    'password': password,
    'device_type': 'cisco_ios',
}

net_connect = Netmiko(**device)

# Use send_config_set() to make config change
config = ['logging console', 'logging buffer 15000']
output = net_connect.send_config_set(config)
output_printer(output)

# Use send_config_from_file() to make config change
output = net_connect.send_config_from_file('config.txt')
output_printer(output)

message = "Verifying config change\n"
output = net_connect.send_command("show run | inc logging")
if '8000' in output:
    message += "Logging buffer is size 8000"
else:
    message += "Logging buffer size is not correct!"
output_printer(message)
#!/usr/bin/env python
from netmiko import Netmiko

# SSH Connection Details
ios1 = {
    'device_type': 'cisco_ios',
    'ip': '198.18.1.55',
    'username': '******',
    'password': '******',
}

# Establish SSH to device and run config command
net_connect = Netmiko(**ios1)
output = net_connect.send_config_set('logging host 10.1.1.1')
print(output)
Exemple #32
0
#!/usr/bin/env python
from __future__ import print_function, unicode_literals

# Netmiko is the same as ConnectHandler
from netmiko import Netmiko
from getpass import getpass

my_device = {
    'host': "host.domain.com",
    'username': '******',
    'password': getpass(),
    'device_type': 'cisco_ios',
}

net_connect = Netmiko(**my_device)
cfg_commands = ['logging buffered 10000', 'no logging console']

# send_config_set() will automatically enter/exit config mode
output = net_connect.send_config_set(cfg_commands)
print(output)

net_connect.disconnect()
Exemple #33
0
except NameError:
    host = input("Enter host to connect to: ")

password = getpass()
device = {
    'host': host,
    'username': '******',
    'password': password,
    'device_type': 'cisco_ios',
}

net_connect = Netmiko(**device)

# Use send_config_set() to make config change
config = ['logging console', 'logging buffer 15000']
output = net_connect.send_config_set(config)
output_printer(output)

# Use send_config_from_file() to make config change
output = net_connect.send_config_from_file('config.txt')
output_printer(output)


message = "Verifying config change\n"
output = net_connect.send_command("show run | inc logging")
if '8000' in output:
    message += "Logging buffer is size 8000"
else:
    message += "Logging buffer size is not correct!"
output_printer(message)