Example #1
0
 def test_device_open_normalize(self, mock_connect, mock_execute):
     mock_connect.side_effect = self._mock_manager
     self.dev2 = Device(host='2.2.2.2', user='******', password='******')
     self.dev2.open(gather_facts=False, normalize=True)
     self.assertEqual(self.dev2.transform, self.dev2._norm_transform)
Example #2
0
jinja2_file = '../jinja2files/OSPF_iBGP_config.j2'
#jinja2_file = '../jinja2files/firewall_filter.j2'

for ip in junos_hosts:
    try:
        # Open and read the YAML file.
        with open(yaml_file, 'r') as fh:
            data = yaml.load(fh.read())

        # print the rended file
        #print ("\nResults for device " + host)
        #print ("------------------------" )
        #print (myConfig)

        #write to the Juniper Box
        dev = Device(host=ip, user='******', password='******')
        dev.open()
        config = Config(dev)
        config.lock()
        config.load(template_path=jinja2_file,
                    template_vars=data,
                    merge=True,
                    format="text")
        config.pdiff()
        config.commit()
        config.unlock()
        dev.close()
    except LockError as e:
        print("The config database was locked!")
    except ConnectTimeoutError as e:
        print("Connection timed out!")
Example #3
0
from pprint import pprint
from jnpr.junos import Device
from jnpr.junos.op.lldp import LLDPNeighborTable

# Need to check vagrant ssh-config to ensure correct port
dev = Device(host='127.0.0.1', user='******', password='******', port=<port>)
dev.open()

pprint(dev.facts)
Example #4
0
from jnpr.junos.op.fpc import FpcInfoTable
import warnings
warnings.filterwarnings('ignore', category=RuntimeWarning)


def get_vmhost_shell(dev):
    '''Login to shell mode'''
    ss = StartShell(dev)
    ss.open()
    '''Different ways to collect host output'''
    #vmhost_shell = ss.run('cli -c \'request vmhost exec "df -i"\'')
    ###Use ">show interfaces terse routing-instance all" to find out virtual instance and IP to connect to Host OS
    #vmhost_shell = ss.run('rsh -JU __juniper_private4__ 192.168.1.1 "df -i"')
    #vmhost_shell = ss.run('rsh -JU __juniper_private5__ 192.168.1.2 "df -i"')
    vmhost_shell = ss.run('vhclient "df -i"')
    #print(vmhost_shell)
    '''Print output'''
    for line in vmhost_shell[1].strip().split('\n')[1:]:
        print(line)
    '''Logout from shell mode'''
    ss.close()


if __name__ == '__main__':
    '''Login to device'''
    #with Device(host='h16-37.ultralab.juniper.net',user='******',password='******') as dev: ###Testsing MX204 device
    with Device(host='10.228.30.11', user='******',
                password='******') as dev:  ###Testing ACX6360 device
        print('{:*^50}'.format(' Get vmhost shell info -- shell '))
        get_vmhost_shell(dev)
Example #5
0
 def setUp(self, mock_connect):
     self.dev = Device(host='1.1.1.1')
     self.shell = StartShell(self.dev)
sys.excepthook = onError

cmdline = argparse.ArgumentParser(description="Python JUNOS PyEZ Client")
cmdline.add_argument("target", help="Target router to query")
cmdline.add_argument("-p", metavar="port", help="TCP port", default=8443)
cmdline.add_argument("-u",
                     metavar="username",
                     help="Remote username",
                     default=getpass.getuser())
args = cmdline.parse_args()

password = getPass(args.u + "@" +
                   args.target) if 'getPass' in globals() else ""

dev = Device(host=args.target, user=args.u, port=args.p, password=password)
dev.open()
dev.timeout = 60

config = dev.rpc.get_configuration(normalize=True)
ifd = config.xpath("interfaces/interface")
ifl = config.xpath("interfaces/interface/unit")
iflacli = config.xpath("interfaces/interface/unit/family/inet/filter/input")
iflaclo = config.xpath("interfaces/interface/unit/family/inet/filter/output")
vrrp = config.xpath("interfaces/interface/unit/family/inet/address/vrrp-group")
vrrpauth = config.xpath(
    "interfaces/interface/unit/family/inet/address/vrrp-group/authentication-key"
)
vrf = config.xpath("routing-instances/instance[instance-type='vrf']")
ibgp = config.xpath(
    "protocols/bgp//neighbor[type='internal' or ../type='internal']")
Example #7
0
    mythirdddefs = loadyaml('ifDescription.yml')
    globals().update(mythirdddefs)

    #We take the first argument of the prompt data. Put the Prefix Here
    URL = (sys.argv)
    #  print str(URL[1])

    # Use .ssh/config file
    config_file = os.path.join(os.getenv('HOME'), '.ssh/config')
    ssh_config = paramiko.SSHConfig()
    ssh_config.parse(open(config_file, 'r'))
    got_lkup = ssh_config.lookup("Your Device")

    # Connect to the device
    dev = Device(host=got_lkup['hostname'],
                 user="******",
                 password="******",
                 gather_facts=False)
    dev.open()

    # Obtain bgpView for the prefix x.x.x.x/x

    routeBgpTable = bgpRoutes(dev).get("%s" % str(URL[1]))

    #Save the prefix for futur usage
    prefix = str(URL[1])
    # Print Information on the p)refix
    for item in routeBgpTable:
        # Print the Route To :
        print(
            colored("Route To : " + item.rt_destination + "/" +
                    item.rt_prefix_length,
Example #8
0
from jnpr.junos import Device
from jnpr.junos.utils.start_shell import StartShell

dev = Device(host='172.27.14.72', user='******', passwd='jun2per')

ss = StartShell(dev)
ss.open()
version = ss.run('cli -c "show version"')
for item in version:
    print(item)
ss.close()
Example #9
0
import sys
import json
import yaml
from pprint import pprint
from jnpr.junos import Device
from jnpr.junos.exception import ConnectError

dev = Device(host='192.168.99.111', user='******', passwd='ansible123')
try:
    dev.open()
except ConnectError as err:
    print("Cannot connect to device: {0}".format(err))
    sys.exit(1)

print("#print everything\n")
pprint(dev.facts)

#print("\n#print only the version")
#pprint (dev.facts['version'])

#print (yaml.dump(dev.facts))

#print (json.dumps(dev.facts))

dev.close()
from jnpr.junos import Device
from lxml import etree

address = str(input("Hostname or IP: "))
username = str(input("Username: "******"Password: "******"File Name: "))

if ".txt" not in fileName:
    fileName += ".txt"

with Device(host=address, user=username, passwd=password) as dev:
    data = dev.rpc.get_config()
    f = open(fileName, "w")
    f.write(etree.tostring(data, encoding='unicode', pretty_print=True))
    f.close()
    print(etree.tostring(data, encoding='unicode', pretty_print=True))
Example #11
0
def xml_conf(hostname, oob):
    with Device(host=oob, user=username, gather_facts="false") as dev:
        config = dev.rpc.get_config()
        return config
Example #12
0
#!/usr/bin/env python
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from getpass import getpass

juniper_mx = {
    "host": "juniper1.twb-tech.com",
    "user": "******",
    "password": getpass(),
}

a_device = Device(**juniper_mx)
a_device.open()
a_device.timeout = 90
cfg = Config(a_device)

print "\nConfiguring IP using {} notation (external file)"
cfg.load(path="configure_ip.conf", format="text", merge=False)

print "Current config differences: "
print cfg.diff()

print "Performing commit"
cfg.commit()
Example #13
0
login = sys.argv[1]
passwd = sys.argv[2]

# Parse Topology file to connect to each device
with open("Topology.yaml", 'r') as yamlfile:
    Devices = yaml.load(yamlfile, Loader=yaml.FullLoader)

# Parse device dictionnary ie Topology file to map each device with JCL IP and Netconf port
for Key, Router in Devices.items():
    print('Je vais prendre la conf du routeur' + str(Key))
    print("Quelle IP pour le " + (Router['HostName']) + "?")
    IP = input()
    Port = input("Type enter to leave default port or enter Netconf port:")
    if not (Port):
        Port = '830'
    dev = Device(host=IP, user=login, passwd=passwd, port=Port)

    # Then connect to each IP mapped to the device to load relevant config file which is in /Config folder
    try:
        dev.open()
    except ConnectError as err:
        print("Cannot connect to device: {0}".format(err))
        sys.exit(1)
    else:
        cu = Config(dev)
        print("Loading configuration changes for %s" % str(Key))
        try:
            cu.load(path="configs/" + str(Key) + ".txt", merge=True)
            cu.pdiff()
        except:
            print("Unable to load configuration changes: {0}".format(err))
Example #14
0
 def setUp(self, mock_connect):
     mock_connect.side_effect = self._mock_manager
     self.dev = Device(host='1.1.1.1', user='******', password='******',
                       gather_facts=False)
     self.dev.open()
     self.ppt = PhyPortStatsTable(self.dev)
Example #15
0
#!/usr/bin/env python
from jnpr.junos import Device
from lxml import etree
from getpass import getpass

password = getpass()
device = {"host": "vmx1.lasthop.io", "user": "******", "password": password}

a_device = Device(**device)
a_device.open()

import ipdb  # noqa

ipdb.set_trace()
# show version | display xml rpc
# <get-software-information>
xml_out = a_device.rpc.get_software_information()
print(etree.tostring(xml_out, encoding="unicode", pretty_print=True))

# get_lldp_neighbors_information()
xml_out = a_device.rpc.get_lldp_neighbors_information()
print(etree.tostring(xml_out, encoding="unicode", pretty_print=True))
Example #16
0
from ncclient import manager

host = '127.0.0.1'
user = '******'
password = '******'
port = 2200

with manager.connect(host=host,
                     port=port,
                     username=user,
                     hostkey_verify=False,
                     password=password,
                     device_params={'name': 'junos'}) as m:
    print m.dispatch('get-lldp-neighbors-information')
    # Dispatch an RPC command yourself (obviously vendor-specific)

from pprint import pprint
from jnpr.junos import Device

dev = Device(host='10.12.0.77', user='******', password='******')
dev.open()

pprint(dev.facts)

dev.close()
Example #17
0
from pprint import pprint
from jnpr.junos import Device
import getpass

host = None
uname = None
pw = None

if host == None:
    host = input("Hostname or IP: ")
if uname == None:
    uname = input("Username:")
if pw == None:
    pw = getpass.getpass()

dev = Device(host=host, user=uname, password=pw)
dev.open()
pprint(dev.facts)
dev.close()
Example #18
0
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from jnpr.junos.utils.sw import SW
import sys

dev = Device('host', user='******', password='******')

dev.open()

print "===========Setting the configuration==========="

cu = Config(dev)

#rsp = cu.load( path="config-example.conf" )
config_set = """set system extensions providers juniper license-type juniper deployment-scope commercial"""

cu.load(config_set, format="set", merge=True)

cu.commit(comment="===========Set the configuration successfully===========")
print dev.cli("show configuration system extensions providers", warning=False)

cu.rollback(rb_id=1)
cu.commit(detail=True)

print dev.cli("show configuration system extensions providers", warning=False)
Example #19
0
 def setUp(self, mock_connect):
     mock_connect.side_effect = self._mock_manager_setup
     self.dev = Device(host='1.1.1.1', user='******', password='******')
     self.dev.open()
Example #20
0
addr_cmd = ''

# iterate through address arguments and build set commands
for addr_prefix in sys.argv[+2:]:
    #print addr_prefix
    addr_cmd = addr_cmd + 'set security address-book global address ' + 'NET_' + addr_prefix + ' ' + addr_prefix + "\n"
    set_cmd = set_cmd + 'set security address-book global address-set ' + set_name + ' address NET_' + addr_prefix + '\n'
all_set_cmds = addr_cmd + set_cmd
print "\nSET commands to be added:\n", all_set_cmds

# connect to junos device
print "Connecting to Junos device -", junos_host, ":", host_netconf_port
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
junos_device = Device(host=junos_host,
                      port=host_netconf_port,
                      user=host_user,
                      password=host_pwd)
junos_device.open()

# load config module and execute set commands
cfg = Config(junos_device)
cfg.load(all_set_cmds, format="set")

# output 'show |compare'
print "Changes to commit:\n", cfg.diff()

# commit with comment
commit_comment = script_name + ' added address-set: ' + set_name
if cfg.diff():
    cfg.commit(comment=commit_comment)
Example #21
0
from jnpr.junos import Device
from jnpr.junos.op.routes import RouteTable

dev = Device(host='172.16.0.2',
             user='******',
             password='******',
             gather_facts=False)
dev.open()

tbl = RouteTable(dev)
tbl.get()
#tbl.get('10.13.10.0/23', protocol='static')
print tbl
for item in tbl:
    print 'protocol:', item.protocol
    print 'age:', item.age
    print 'via:', item.via
    print

dev.close()
Example #22
0
from jnpr.junos import Device
from lxml import etree

dev = Device(host='xxxx', user='******', password='******', gather_facts=False)
dev.open()

cnf = dev.rpc.get_config()
#cnf = dev.rpc.get_config(filter_xml=etree.XML('<configuration><interfaces/></configuration>'))
print etree.tostring(cnf)
Example #23
0
juniper_srx = {
    "host": "184.105.247.76",
    "user": "******",
    "password": getpass(),
}


def juniper_print(k, v):
    print
    print k
    print '-' * 20
    pprint(v)
    print '-' * 20


a_device = Device(**juniper_srx)
a_device.open()

eth_ports = EthPortTable(a_device)
eth_ports.get()
print '-' * 80
print "Ethernet Ports"
for k, v in eth_ports.items():
    juniper_print(k, v)
import sys
sys.exit()
print '-' * 80
raw_input("Hit enter to continue: ")

arp = ArpTable(a_device)
arp.get()
Example #24
0
 def test_device_repr(self):
     localdev = Device(host='1.1.1.1',
                       user='******',
                       password='******',
                       gather_facts=False)
     self.assertEqual(repr(localdev), 'Device(1.1.1.1)')
Example #25
0
import sys
from jnpr.junos import Device
from jnpr.junos.op.fpc import FpcHwTable
from jnpr.junos.op.fpc import FpcInfoTable
from getpass import getpass
from pprint import pprint as pp
from sys import exit
from lxml import etree


user = "******"

Host = raw_input('Enter Hostname or IP address of Device: ')
dev = Device(host=Host,user='******',password='******').open()


class style:
   BOLD = '\033[1m'
   END = '\033[0m'



#print FPC hardware Table
#get-chassis-inventory
print "\n*************************************************************************************"
print style.BOLD + "Chassis Installed FPC Details " + style.END
fpcs = FpcHwTable(dev)
fpcs.get()
print fpcs

for fpc in fpcs:
Example #26
0
 def test_device_local(self):
     Device.ON_JUNOS = True
     localdev = Device()
     self.assertEqual(localdev._hostname, 'localhost')
import re

today = datetime.now().strftime("%d-%h-%Y")
username = "******"

Leafs = {
    "Leaf1": "192.0.0.61",
    "Leaf2": "192.0.0.62",
    "Leaf3": "192.0.0.63",
    "Leaf4": "192.0.0.64",
    "Leaf5": "192.0.0.65",
    "Leaf6": "192.0.0.66",
}

for leaf, oob in Leafs.items():
    dev = Device(host=oob, user=username, gather_facts="false")
    dev.open()
    config = dev.rpc.get_config()
    dev.close()
    #etree.dump(config)
    vlans = config.findall('vlans/vlan')

    vlan_list = list()
    for vlan in vlans:
        vlan_name = vlan.find('name').text
        vlan_list.append(vlan_name)
    vlan_list.sort()

    file_name = "/var/tmp/{}_sp-to-ent-migration_{}.txt".format(leaf, today)
    open_file = open(file_name, "w")
Example #28
0
    def connect(self,
                hostname,
                username,
                password,
                output_file,
                config_data=None,
                action=None,
                post_snap=None,
                **kwargs):
        """
        connect to device and calls the function either to generate snapshots
        or compare them based on option given (--snap, --check, --snapcheck, --diff)
        :param hostname: ip/ hostname of device
        :param username: username of device
        :param password: password to connect to device
        :param snap_files: file name to store snapshot
        :return: if snap operation is performed then return true on success
                 if snapcheck or check operation is performed then return test details
        """
        res = None
        if config_data is None:
            config_data = self.main_file

        if 'local' in config_data:
            self.args.local = True

        if (self.args.snap is True or action is "snap") or (
            (self.args.snapcheck is True or action is "snapcheck")
                and self.args.local is not True):
            self.logger.info(colorama.Fore.BLUE +
                             "Connecting to device %s ................",
                             hostname,
                             extra=self.log_detail)
            if username is None:
                username = raw_input("\nEnter User name: ")
            dev = Device(host=hostname,
                         user=username,
                         passwd=password,
                         gather_facts=False,
                         **kwargs)
            try:
                dev.open()
            except ConnectAuthError as ex:
                if password is None and action is None:
                    password = getpass.getpass(
                        "\nEnter Password for username <%s> : " % username)
                    self.connect(hostname, username, password, output_file,
                                 config_data, action, post_snap, **kwargs)
                else:
                    self.logger.error(colorama.Fore.RED +
                                      "\nERROR occurred %s" % str(ex),
                                      extra=self.log_detail)
                    raise Exception(ex)
            except Exception as ex:
                self.logger.error(colorama.Fore.RED +
                                  "\nERROR occurred %s" % str(ex),
                                  extra=self.log_detail)
                raise Exception(ex)
            else:
                res = self.generate_rpc_reply(dev, output_file, hostname,
                                              config_data)
                self.snap_q.put(res)
                dev.close()
        if self.args.check is True or self.args.snapcheck is True or self.args.diff is True or action in [
                "check", "snapcheck"
        ]:

            if self.args.local is True and 'local' in config_data:
                output_file = config_data['local']
                res = {}
                for local_snap in output_file:
                    ret_obj = self.get_test(config_data, hostname, local_snap,
                                            post_snap, action)
                    res[local_snap] = ret_obj
            else:
                res = self.get_test(config_data, hostname, output_file,
                                    post_snap, action)

        return res