Пример #1
0
def getdevice(ip_address, username, password):
    """
    Retrieve and return device class.
    """
    device = Device(host=ip_address, user=username, password=password)
    device.open()
    return device
Пример #2
0
def ConnectJuniper():
    

    global dev
    print '\n\n' + "Establish connection to Juniper System..." + '\t\t\n',
    dev=Device(host='Insert_Device', user="******", password="******")
    dev.open()
Пример #3
0
def mocked_device(rpc_reply_dict, mock_connect):
    """Juniper PyEZ Device Fixture"""
    def mock_manager(*args, **kwargs):
        if 'device_params' in kwargs:
            # open connection
            device_params = kwargs['device_params']
            device_handler = make_device_handler(device_params)
            session = SSHSession(device_handler)
            return Manager(session, device_handler)
        elif args:
            # rpc request
            rpc_request = args[0].tag
            rpc_command = str(args[0].text)
            rpc_command = rpc_command.strip()
            rpc_command = rpc_command.replace(" ", "_")
            if rpc_request in rpc_reply_dict:
                xml = rpc_reply_dict[rpc_request]
            elif 'dir' in rpc_reply_dict:
                fname = os.path.join(rpc_reply_dict['dir'], 'rpc-reply', rpc_command, rpc_request + '.xml')
                with open(fname, 'r') as f:
                    xml = f.read()
            else:
                _rpc_reply_dict['dir']
                fname = os.path.join(os.path.dirname(__file__), 'rpc-reply', rpc_command, rpc_request + '.xml')
                with open(fname, 'r') as f:
                    xml = f.read()
            rpc_reply = NCElement(xml, dev._conn._device_handler.transform_reply())
            return rpc_reply
    mock_connect.side_effect = mock_manager
    dev = Device(host='1.1.1.1', user='******', gather_facts=False)
    dev.open()
    dev._conn.rpc = MagicMock(side_effect=mock_manager)
    dev.close = MagicMock()
    return dev
Пример #4
0
def connect(module):
    host = get_param(module, 'host')

    kwargs = {
        'port': get_param(module, 'port') or 830,
        'user': get_param(module, 'username')
    }

    if get_param(module, 'password'):
        kwargs['passwd'] = get_param(module, 'password')

    if get_param(module, 'ssh_keyfile'):
        kwargs['ssh_private_key_file'] = get_param(module, 'ssh_keyfile')

    kwargs['gather_facts'] = False

    try:
        device = Device(host, **kwargs)
        device.open()
        device.timeout = get_param(module, 'timeout') or 10
    except ConnectError:
        exc = get_exception()
        module.fail_json('unable to connect to %s: %s' % (host, str(exc)))

    return device
Пример #5
0
 def connectToDevice(self):
     '''
     :param dict deviceInfo:
         ip: ip address of the device
         username: device credential username
     :returns Device: Device, handle to device connection.
     '''
     if self.device.managementIp == None or self.device.username == None:
         raise DeviceConnectFailed('Device: %s, ip: %s, username: %s' % (self.device.id, self.device.managementIp, self.device.username))
     if self.device.encryptedPassword == None:
         raise DeviceConnectFailed('Device: %s, , ip: %s, password is None' % (self.device.id, self.device.managementIp))
     
     try:
         deviceIp = self.device.managementIp.split('/')[0]
         devicePassword = self.device.getCleartextPassword()
         deviceConnection = DeviceConnection(host=deviceIp, user=self.device.username, password=devicePassword, port=22)
         deviceConnection.open()
         logger.debug('Connected to device: %s' % (self.device.managementIp))
         self.deviceConnectionHandle = deviceConnection
         return deviceConnection
     except ConnectError as exc:
         logger.error('Device connection failure, %s' % (exc))
         self.deviceConnectionHandle = None
         raise DeviceConnectFailed(self.device.managementIp, exc)
     except Exception as exc:
         logger.error('Unknown error, %s' % (exc))
         logger.debug('StackTrace: %s' % (traceback.format_exc()))
         self.deviceConnectionHandle = None
         raise DeviceConnectFailed(self.device.managementIp, exc)
Пример #6
0
def device(connect_string):
    """Return a connected device.

    This should be run as a context. Devices will be kept open and
    reused. If a device is already in use, entering the context will
    block until the device is ready.

    """
    with device_lock:
        device, lock = device_list.get(connect_string, (None, None))
        if device is None:
            # Parse the connect string
            mo = connect_re.match(connect_string)
            if not mo:
                raise ValueError("unparsable host string")
            args = {k: v for k, v in mo.groupdict().items()
                    if v is not None}
            device = Device(**args)
            lock = threading.Lock()
            device_list[connect_string] = device, lock
    with lock:
        if not device.connected:
            device.open(gather_facts=False, attempts=3)
            device.timeout = 60
        yield device
def main():
    """Simple main method to enter log entries."""
    routers = ['10.11.12.1', '10.11.12.2']
    pyez_user = '******'
    pyez_pass = '******'
    netdata_db = 'network_data.db'
    link_down = re.compile('(\w{1,3}\s{1,3}\d{1,2}\s{1,3}\d{1,2}:\d{1,2}:\d{1,2}).*SNMP_TRAP_LINK_DOWN.*ifName ([gax]e-\d{1,2}\/\d{1,2}\/\d{1,2})\n', flags=0)
    for router in routers:
        try:
            device = Device(host=router, user=pyez_user, password=pyez_pass)
            device.open()
            logs = device.rpc.get_log(filename='messages')
            for log_content in logs.iter("file-content"):
                # print(log_content.text)
                messages = link_down.finditer(log_content.text)
                if messages:
                    # print(messages.group(0))
                    for log in messages:
                        entry = []
                        # Step 1.1
                        print(log.group(1))
                        print(log.group(2))
                        print(log.group(0))
                        # Step 1.3
                        print(log.group(1).replace(' ', '_') + '_' + device.facts['fqdn'])
                        entry.append(log.group(1).replace(' ', '_') + '_' + device.facts['fqdn'])
                        entry.append(device.facts['fqdn'])
                        entry.append(log.group(2))
                        entry.append(log.group(0))
                        write_log_to_database(netdata_db, entry)
            device.close()
        except Exception as e:
            print("Uh oh! We had a problem retrieving the messages log file.")
            print('Here is the error {error}'.format(error=e))
Пример #8
0
def login():
    error = None
    if request.method == 'POST':
    	hostname = request.form['hostname'] 
        username = request.form['username'] 
        password = request.form['password']
        #
        # Retrieve device information
        #
        dev = Device(hostname,user=username,password=password)

        try:
            dev.open()

        except ConnectAuthError:
            error = 'Wrong Credentials. Please try again.'
            return render_template('login.html',error=error)

        except ConnectTimeoutError:
            error = 'Timeout. Host not reachable?'
            return render_template('login.html',error=error)

        except ConnectError:
            error = 'Huh... something wrong. Try again?'
            return render_template('login.html',error=error)

        print "Login success"
        #  Print device info
        global device
        device = dev.facts
        print "Device Name: ", device['hostname']
        print device
        dev.close()
        return redirect(url_for('get_device'))
    return render_template('login.html', error=error)
Пример #9
0
def main():

    pwd = getpass()

    juniper = {
        "host": "50.76.53.27",
        "user": "******",
        "password": pwd
    }

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

    table = RouteTable(a_device)
    table.get()

    print
    print "Juniper SRX Routing Table"
    print

    for route, rtable in table.items():
        rtable = dict(rtable)
        #print stats
        nexthop = rtable['nexthop']
        age = rtable['age']
        via = rtable['via']
        protocol = rtable['protocol']
        print route
        print " NextHop %s" % (nexthop)
        print " age %s" % (age)
        print " via %s" % (via)
        print " protocol %s" % (protocol)
        print
Пример #10
0
class TestTable(unittest.TestCase):

    @classmethod
    def setUpClass(self):
        from jnpr.junos import Device
        self.dev = Device(host='stag.englab.juniper.net',
                          user='******', password='******')
        self.dev.open()

    @classmethod
    def tearDownClass(self):
        self.dev.close()

    def test_table_union(self):
        lldp = LLDPNeighborTable(self.dev)
        lldp.get('et-0/1/1')
        self.assertEqual(lldp['et-0/1/1'].local_int, 'et-0/1/1')

    def test_table_json(self):
        lldp = LLDPNeighborTable(self.dev)
        lldp.get('et-0/1/1')
        json = '{"et-0/1/1": {"remote_port_desc": "et-1/1/1", '\
            '"local_int": "et-0/1/1", "remote_sysname": "highlife", '\
            '"local_parent": "-", "remote_chassis_id": "4c:96:14:f3:d5:20", '\
            '"remote_type": "Mac address"}}'
        self.assertEqual(lldp.to_json(), json)
 def get_connected_device(self, requester_name, device):
     LOGGER.debug('get_connected_device, request by [%s]', requester_name)
     time1 = time.time()
     dev_name = device.get('ip_address')
     password_encoded = self.config.get('password_encoded', False)
     if password_encoded:
         pwd = utils.decrypt_passwd(device.get('password'))
     else:
         pwd = device.get('password')
     try:
         dev = Device(host=dev_name, user=device.get('user'),
                  password=pwd, port=device.get('port', 22), gather_facts=False, auto_probe=5)
         rpc_timeout = self.config.get('rpc_timeout', 1) * 60
         dev.open()
         if dev.connected:
             dev.timeout = rpc_timeout
             return dev
     except Exception as e:
         LOGGER.error(
                 'connect, for device [%s, %s] failed',
                 dev_name,
                 e)
     finally:
         LOGGER.debug(
                 'connect, for device %s %d(s)',
                 dev_name,
                 (time.time() - time1))
     return None
Пример #12
0
def main():
    '''
    For each of the SRX's interfaces, display: the operational state,
    packets-in, and packets-out. You will probably want to use EthPortTable for
    this.
    '''
    pwd = getpass()
    try:
        a_device = Device(host='184.105.247.76', user='******', password=pwd)
        a_device.open()
        ports = EthPortTable(a_device)
        ports.get()
        print "\n"*2
        for port in ports.keys():
            print "#"*80
            print "Operational state, Packets-in and Packets-out for Port {0} are :".format(port)
            print "#"*80
            print "Operational state is : {0}".format(ports[port]['oper'])
            print "Packets-in are : {0}".format(ports[port]['rx_packets'])
            print " Packets-out are : {0}".format(ports[port]['tx_packets'])
            print "*"*80
            print "\n"*2
        print
    except:
        print
        print "Authentication Error"
        print
Пример #13
0
    def snap(self):
        dev = Device(host=self.hostname, user=user, password=password)
        dev.open()

        # get basic Node facts
        node = Node(self.snapshot, self.hostname)
        node.fqdn = dev.facts['fqdn']
        node.hostname = dev.facts['hostname']
        node.model = dev.facts['model']
        node.personality = dev.facts['personality']
        node.serialnumber = dev.facts['serialnumber']
        node.switch_style = dev.facts['switch_style']
        node.version = dev.facts['version']
        node.uptime = dev.facts['RE0']['up_time']
        node.reboot_reason = dev.facts['RE0']['last_reboot_reason']
        roumiga.session.add(node)
        roumiga.session.flush()

        # do the ARP dance
        import jnpr.junos.op.arp
        raw_arp = jnpr.junos.op.arp.ArpTable(dev)
        for a in raw_arp.get():
            arp_entry = ArpEntry.from_dict(snapshot, node, a)
            roumiga.session.add(arp_entry)
            self.arp.append(arp_entry)

        # do the BGP dance
        import jnpr.junos.op.bgppeer
        raw_bgp = jnpr.junos.op.bgppeer.BgpPeerTable(dev)
        for b in raw_bgp.get():
            bgp_peer = BgpPeer.from_dict(snapshot, node, b)
            roumiga.session.add(bgp_peer)
            self.bgp.append(bgp_peer)

        dev.close()
Пример #14
0
 def test_ftp_open_erors(self, mock_connect, mock_ftpconnect):
     dev2 = Device(host='1.1.1.1', user="******",
                   passwd="testpasswd",
                   gather_facts=False)
     dev2.open()
     dev_ftp = jnpr.junos.utils.ftp.FTP(dev2)
     self.assertRaises(Exception, dev_ftp.open)
Пример #15
0
class interfaceThread(threading.Thread):
    def __init__(self, rtr, r):
        threading.Thread.__init__(self)
        self.rtr = rtr
        self.dev = ''
        self.redis = r
        
    def run(self):
        self.dev = Device(host=self.rtr['ip'], user='******', password='******')
        self.dev.open()
        while True:
            #t0 = time.clock()
            #t1 = time.time()
            if self.rtr['name'] == 'houston':
                continue
            for intf in self.rtr['interfaces']:
                try:
                    result = self.dev.rpc.ping({'format': 'json'},host=intf['address'], count='1')
                    latency = { 'timestamp': datetime.datetime.fromtimestamp(time.time()).strftime('%a:%H:%M:%S'), 
                                             'from-router': self.rtr['name'], 'to-router': intf['to'],
                                             'rtt-average(ms)':  float(result['ping-results'][0]['probe-results-summary'][0]['rtt-average'][0]['data'])/1000.0 }
                    jd = json.dumps(latency)
                    dataset = self.rtr['name'] + ':' + intf['to'] + ':latency'
                    self.redis.lpush(dataset,jd)
                    self.redis.ltrim(dataset, 0, window)
                except:
                    print self.rtr['name'], intf['address'], ' latency polling failed'
                    continue
                
            print self.rtr['name'], ' latency thread exist'
            time.sleep(self.rtr['nap_time'])   
        self.dev.close()
Пример #16
0
class TestCore(unittest.TestCase):

    @classmethod
    def setUpClass(self):
        from jnpr.junos import Device
        self.dev = Device(host='snuggums.englab.juniper.net',
                          user='******', password='******')
        self.dev.open()

    @classmethod
    def tearDownClass(self):
        self.dev.close()

    def test_device_open(self):
        self.assertEqual(self.dev.connected, True)

    def test_device_facts(self):
        assert self.dev.facts['hostname'] == 'snuggums'

    def test_device_get_timeout(self):
        assert self.dev.timeout == 30

    def test_device_set_timeout(self):
        self.dev.timeout = 35
        assert self.dev.timeout == 35

    def test_device_cli(self):
        self.assertIn('qfx5100', self.dev.cli('show version'))

    def test_device_rpc(self):
        sw = self.dev.rpc.get_software_information()
        hostname = sw.findtext('.//host-name')
        self.assertEqual(hostname, 'snuggums')
Пример #17
0
def ConnectJuniper(jhost, juser, jpassword):


    global dev
    dev=Device(host=jhost, user=juser, password=jpassword)
    dev.open()
    print "Established connection to Juniper System..."
Пример #18
0
class TestSrxCluster(unittest.TestCase):

    @patch('ncclient.manager.connect')
    @patch('jnpr.junos.device.warnings')
    def setUp(self, mock_warnings, mock_connect):
        mock_connect.side_effect = self._mock_manager
        self.dev = Device(host='1.1.1.1', user='******', password='******',
                          gather_facts=False, fact_style='old')
        self.dev.open()
        self.facts = {}

    @patch('jnpr.junos.Device.execute')
    def test_srx_cluster(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.facts['personality'] = 'SRX'
        self.facts['master'] = ['RE0']
        srx_cluster(self.dev, self.facts)
        self.assertTrue(self.facts['srx_cluster'])

    @patch('jnpr.junos.device.warnings')
    def test_srx_cluster_none(self, mock_warnings):
        self.facts['personality'] = 'MX'
        self.assertEqual(srx_cluster(self.dev, self.facts), None)

    @patch('jnpr.junos.Device.execute')
    def test_srx_cluster_no_node(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.facts['personality'] = 'SRX'
        srx_cluster(self.dev, self.facts)
        self.assertTrue(self.facts['srx_cluster'])

    @patch('jnpr.junos.Device.execute')
    def test_srx_cluster_node(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.facts['personality'] = 'SRX'
        self.facts['master'] = ['RE1']
        srx_cluster(self.dev, self.facts)
        self.assertTrue(self.facts['srx_cluster'])

    def _read_file(self, fname):
        from ncclient.xml_ import NCElement

        fpath = os.path.join(os.path.dirname(__file__),
                             'rpc-reply', fname)
        foo = open(fpath).read()

        rpc_reply = NCElement(foo, self.dev._conn.
                              _device_handler.transform_reply()).\
            _NCElement__doc[0]
        return rpc_reply

    def _mock_manager(self, *args, **kwargs):
        if kwargs:
            device_params = kwargs['device_params']
            device_handler = make_device_handler(device_params)
            session = SSHSession(device_handler)
            return Manager(session, device_handler)

        if args:
            return self._read_file(args[0].tag + '.xml')
Пример #19
0
def print_interface_table(hostname):
    dev = Device(user=username, host=hostname, password=password, gather_facts=False, normalize=True)
    dev.open()
    port_table = PhyPortTable(dev).get()
    for port in port_table:
        print hostname, port.name, port.macaddr, port.flapped
    dev.close()
Пример #20
0
def main():
    '''
    Connect to Juniper device using PyEZ. Display the routing table.
    '''
    pwd = getpass()
    ip_addr = raw_input("Enter Juniper SRX IP: ")
    ip_addr = ip_addr.strip()

    juniper_srx = {
        "host": ip_addr,
        "user": "******",
        "password": pwd
    }

    print "\n\nConnecting to Juniper SRX...\n"
    a_device = Device(**juniper_srx)
    a_device.open()

    routes = RouteTable(a_device)
    routes.get()

    print "\nJuniper SRX Routing Table: "
    for a_route, route_attr in routes.items():
        print "\n" + a_route
        for attr_desc, attr_value in route_attr:
            print "  {} {}".format(attr_desc, attr_value)

    print "\n"
Пример #21
0
def main():
    '''
    Connect to Juniper device using PyEZ. Display operational state and pkts_in, pkts_out for all
    of the interfaces.
    '''
    #pwd = getpass()
    pwd = '88newclass'
    #ip_addr = raw_input("Enter Juniper SRX IP: ")
    ip_addr = '50.76.53.27'
    ip_addr = ip_addr.strip()

    juniper_srx = {
        "host": ip_addr,
        "user": "******",
        "password": pwd
    }

    print "\n\nConnecting to Juniper SRX...\n"
    a_device = Device(**juniper_srx)
    a_device.open()

    eth_ports = EthPortTable(a_device)
    eth_ports.get()

    print "{:>15} {:>12} {:>12} {:>12}".format("INTF", "OPER STATE", "IN PACKETS", "OUT PACKETS")
    for intf, eth_stats in eth_ports.items():
        eth_stats = dict(eth_stats)
        oper_state = eth_stats['oper']
        pkts_in = eth_stats['rx_packets']
        pkts_out = eth_stats['tx_packets']
        print "{:>15} {:>12} {:>12} {:>12}".format(intf, oper_state, pkts_in, pkts_out)
    print
Пример #22
0
def main():
    globals().update(loadyaml(yamlfile))
    hosts = config.get('hosts')

    for host in hosts:
        dev = Device(host=host, user=user, password=password)
        try:
            dev.open()
        except Exception as err:
            print("Cannot connect to device: {}".format(err))
            return

        peerTable = BgpNeighborTable(dev)
        peerTable.get()
        for entry in peerTable:
            peer = dict(entry)
            print("Neighbor: {}:{}".format(peer["peer-address"],
                  peer["peer-as"]))
            print("    Description: {}".format(peer["description"]))
            print("    State: {}".format(peer["peer-state"]))
            print("    RIB: {}".format(peer["rib-name"]))
            print("    Stats:")
            print("        Accepted Prefixes: {}"
                  .format(peer["accepted-prefix"]))
            print("        Suppressed Prefixes: ",
                  "{}".format(peer["suppressed-prefix"]))
            print("        Active Prefixes: {}".format(peer["active-prefix"]))
            print("        Received Prefixes: {}"
                  .format(peer["received-prefix"]))
            print()

        dev.close()
def main():
    """Simple main method to view custom BGP table."""
    routers = ['10.11.12.1', '10.11.12.2']
    username = '******'
    password = '******'
    for router in routers:
        dev = Device(host=router, user=username, password=password)
        dev.open()
        dev_info = BGPNeighborTable(dev)
        dev_info.get()
        for key in dev_info.keys():
            bgp_info = dev_info[key]
            print('#' * 60)
            print('This host         : {host}'.format(host=bgp_info.local_address))
            print('Belongs to ASN    : {ver}'.format(ver=bgp_info.local_as))
            print('And peers with    : {host}'.format(host=bgp_info.peer_address))
            print('In ASN            : {ver}'.format(ver=bgp_info.peer_as))
            print('The peer type is  : {ver}'.format(ver=bgp_info.peer_type))
            print('The peer state is : {flap}'.format(flap=bgp_info.peer_state))
            print('The peer is advertising   : {sent}'.format(sent=bgp_info.nlri_type_peer))
            print('We peer are advertising   : {recv}'.format(recv=bgp_info.nlri_type_session))
            print('We are applying policy    : {act}'.format(act=bgp_info.export_policy))
            print('With route preference     : {recv}'.format(recv=bgp_info.preference))
            print('Using holdtime            : {acc}'.format(acc=bgp_info.holdtime))
            print('#' * 60)
        dev.close()
Пример #24
0
class TestScp(unittest.TestCase):
    def setUp(self):
        self.dev = Device(host='1.1.1.1')

    @patch('paramiko.SSHClient')
    def test_scp_open(self, mock_connect):
        from scp import SCPClient
        self.dev.bind(scp=SCP)
        assert isinstance(self.dev.scp.open(), SCPClient)

    @patch('paramiko.SSHClient')
    def test_scp_close(self, mock_connect):
        self.dev.bind(scp=SCP)
        self.dev.scp.open()
        self.assertEqual(self.dev.scp.close(), None)

    @patch('paramiko.SSHClient')
    def test_scp_context(self, mock_connect):
        with SCP(self.dev) as scp:
            scp.get('addrbook.conf')

    @patch('jnpr.junos.device.os')
    @patch('__builtin__.open')
    @patch('paramiko.config.SSHConfig.lookup')
    @patch('paramiko.SSHClient')
    @patch('paramiko.proxy.ProxyCommand')
    def test_scp_proxycommand(self, os_mock, open_mock, mock_paramiko, mock_connect, mock_proxy):
        os_mock.path.exists.return_value = True
        self.dev._sshconf_path = '/home/rsherman/.ssh/config'
        with SCP(self.dev) as scp:
            scp.get('addrbook.conf')
        mock_proxy.assert_called_any()
class TestGetChassisClusterStatus(unittest.TestCase):

    @patch('ncclient.manager.connect')
    def setUp(self, mock_connect):
        mock_connect.side_effect = self._mock_manager_setup
        self.dev = Device(host='1.1.1.1', user='******', password='******',
                          gather_facts=False)
        self.dev.open()

    @patch('jnpr.junos.Device.execute')
    def test_srx_cluster_fact_none(self, mock_execute):
        mock_execute.side_effect = self._mock_manager_rpc_error
        self.assertEqual(self.dev.facts['srx_cluster'], None)

    @patch('jnpr.junos.Device.execute')
    def test_srx_cluster_fact_false(self, mock_execute):
        mock_execute.side_effect = self._mock_manager_false
        self.assertEqual(self.dev.facts['srx_cluster'], False)

    @patch('jnpr.junos.Device.execute')
    def test_srx_cluster_fact_true(self, mock_execute):
        mock_execute.side_effect = self._mock_manager_true
        self.assertEqual(self.dev.facts['srx_cluster'], True)

    @patch('jnpr.junos.Device.execute')
    def test_srx_cluster_id_fact(self, mock_execute):
        mock_execute.side_effect = self._mock_manager_true
        self.assertEqual(self.dev.facts['srx_cluster_id'], '1')

    def _read_file(self, fname):
        from ncclient.xml_ import NCElement

        fpath = os.path.join(os.path.dirname(__file__),
                             'rpc-reply', fname)
        foo = open(fpath).read()

        rpc_reply = NCElement(foo,
                              self.dev._conn._device_handler
                              .transform_reply())._NCElement__doc[0]
        return rpc_reply

    def _mock_manager_setup(self, *args, **kwargs):
        if kwargs:
            device_params = kwargs['device_params']
            device_handler = make_device_handler(device_params)
            session = SSHSession(device_handler)
            return Manager(session, device_handler)

    def _mock_manager_rpc_error(self, *args, **kwargs):
        if args:
            raise RpcError()

    def _mock_manager_false(self, *args, **kwargs):
        if args:
            return self._read_file('cluster_false_' + args[0].tag + '.xml')

    def _mock_manager_true(self, *args, **kwargs):
        if args:
            return self._read_file('cluster_true_' + args[0].tag + '.xml')
Пример #26
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(required=True),
            targets=dict(required=False, default=None),
            checktype=dict(required=False, default='pre'),
            user=dict(required=False, default=os.getenv('USER')),
            passwd=dict(required=False, default=None)),
        supports_check_mode=False)

    m_args = module.params
    m_results = dict(changed=False)
    dev = Device(m_args['host'], user=m_args['user'], passwd=m_args['passwd'])
    try:
        dev.open()
        results = {}
        ping_results = []
        if m_args['checktype'] == 'pre':
            try:
                arp = ArpTable(dev)
                arp.get()
                arp_json = json.loads(json.dumps(arp, cls=TableJSONEncoder))
                for entry in arp_json:
                    ping_results.append(dev.rpc.ping
                                        (host=arp_json[entry]['ip_address'],
                                         count='3', rapid=True))
                for entry in ping_results:
                    ip = entry.findtext('target-ip').replace('\n', '')
                    results[ip] = {}
                    if entry.findtext('ping-success') is not None:
                        results[ip]['success'] = True
                    else:
                        results[ip]['success'] = False
            except Exception as err:
                module.fail_json(msg=err)
        elif m_args['targets'] is not None:
            import ast
            m_args['targets'] = ast.literal_eval(m_args['targets'])
            for entry in m_args['targets']:
                if m_args['targets'][entry]['success'] == True:
                    ping_results.append(dev.rpc.ping
                                        (host=entry, count='3', rapid=True))
            for entry in ping_results:
                ip = entry.findtext('target-ip').replace('\n', '')
                results[ip] = {}
                if entry.findtext('ping-success') is not None:
                    results[ip]['success'] = True
                else:
                    results[ip]['success'] = False
        else:
            module.fail_json(msg='You specified a post-check \
                             but did not specify targets.')
    except Exception as err:
        msg = 'unable to connect to {}: {}'.format(m_args['host'], str(err))
        module.fail_json(msg=msg)
        return
    else:
        dev.close()
        module.exit_json(results=results)
Пример #27
0
def pleaseConnect(devices):
    for k,v in devices.items():
        dev = Device(host = v[1][0],
                     user = v[1][1],
                     passwd = v[1][2])
        dev.open()
        devices[k]=(dev,v[1])
    return devices
Пример #28
0
 def test_ftp_open_erors(self, mock_connect, mock_ftpconnect,
                         mock_ftplogin):
     dev = Device(host='1.1.1.1', user="******",
                   passwd="testpasswd",
                   gather_facts=False)
     dev.open()
     dev_ftp = jnpr.junos.utils.ftp.FTP(dev)
     mock_ftplogin.assert_called_with('testuser', 'testpasswd', '')
def Connect_Router(device_fqdn, username, password, dpiloganalyzer_log):
	#Connect to the MX router using netconf. PyEZ netconf library is used here
	try:
		jdev = Device(host=device_fqdn, user=username, password=password)
		jdev.open()
	except ncclient.transport.AuthenticationError, err:
		dpiloganalyzer_log.error(err)
		return 1
Пример #30
0
 def test_can_login_parse_serial(self):
 	config = ConfigDictionary('./etc/example.ini')
 	jdev = Device(user=config.username(), host=config.get_router_ip('rtr1'), password=config.password())
 	jdev.open(gather_facts=False)
 	inv = jdev.rpc.get_chassis_inventory()
 	print "model: %s" % inv.findtext('.//chassis/description')
 	jdev.close()
 	assert inv.findtext('.//chassis/description') == 'VMX'
Пример #31
0
#!/usr/bin/python

import sys
from getpass import getpass
from jnpr.junos import Device
from jnpr.junos.op.ethport import EthPortTable
from pprint import pprint

devlist = ['192.168.2.254']
username = raw_input('username: '******'password: '******'hostname'] + " uptime " + dev.facts['RE0']['up_time'])
    dev.close()
Пример #32
0
#!/usr/bin/env python
from __future__ import print_function
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()
Пример #33
0
def connect_to_router(host, user, password):
    dev = Device(host=host, user=user, password=password, gather_facts=False)
    dev.open()
    return dev
Пример #34
0
#/usr/bin/python
#Author: Raj Bindra
import sys
from lxml import etree
from getpass import getpass
from jnpr.junos import Device
from jnpr.junos.utils.start_shell import StartShell
from pprint import pprint
import re
devices = open('device_list1')
devlist = devices.readlines()
user = raw_input('username: '******'password: '******'shell.txt', 'ab')
    print "Working on %s..." % host 
    dev = Device(host,user=user,password=passwd, port=22)
    ss = StartShell(dev)
    ss.open()
    output =  ss.run('cli -c "show chassis fpc | match Online"')    
#    file.write(output)   
#    file.write('\n              ')
    print output
    ss.close()
#file.close()
Пример #35
0
 def device_conn(self, host_ip):
     user = "******"
     password = "******"
     return Device(host=host_ip, user=user, password=password, port="22")
Пример #36
0
"""
5b. Using a direct RPC call, gather the output of "show interfaces terse". Print the output to standard out.
"""

from jnpr.junos import Device
from lxml import etree  # Etree class
from pprint import pprint
from jnpr_devices import srx2

# Create device object
device_conn = Device(**srx2)
# Establish connection to the device using NETCONF
device_conn.open()

# Invoke rpc call to the device to get the show interfaces terse output in normalised fashion for readability
xml_ouput = device_conn.rpc.get_interface_information(terse=True,
                                                      normalize=True)
# Use tostring method to change to unicdoe string and then print
print(etree.tostring(xml_ouput, encoding='unicode', pretty_print=True))
Пример #37
0
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
import yaml
#testing gitbranch
#dummy changes only in master branch

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

data = yaml.load(open('protocol_data.yml'))

cu = Config(dev)

cu.load(template_path='protocol_temp.j2', template_vars=data, format='text')
cu.pdiff()
if cu.commit_check():
    cu.commit()
else:
    cu.rollback()

dev.close()
Пример #38
0
from jnpr.junos import Device
# Do not worry if your IDE flags the next import up.
# It will work.
from jnpr.junos.op.ethport import EthPortTable

with Device(host='10.4.4.41', user='******',
            password='******') as dev:
    eths = EthPortTable(dev)
    eths.get()
    for port in eths:
        print("{}: {}".format(port.name, port.oper))
Пример #39
0
    def create_dev_conn(cls, sample_device=None, connect=True):
        """
        Creates a device connection object according to driver settings. If an OSSH session is used hand over sock_fd.
        :param sample_device. Create a connection object for sample_device.
        :return Device. Return Device object with with the according connection
        """

        if c.conf.DEVICEDRIVER.Driver == c.YAPT_DEVICE_DRIVER_PYEZ:

            # If we get an ossh connection hand over sock_fd
            if c.SERVICEPLUGIN_OSSH == sample_device.deviceServicePlugin:

                if c.conf.YAPT.DevicePwdIsRsa:

                    dev_conn = Device(host=None, sock_fd=sample_device.deviceConnection, user=c.conf.YAPT.DeviceUsr,
                                      password=Tools.get_password(c.YAPT_PASSWORD_TYPE_DEVICE_RSA),
                                      gather_facts=False)

                    if dev_conn is not None:

                        if connect:
                            try:
                                dev_conn.open()
                                sample_device.deviceConnection = dev_conn
                                return True, sample_device

                            except jnpr.junos.exception.ConnectError as err:
                                c.logger.info(Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP,
                                                                   logmsg.CONN_MGMT_OPEN_FAILED.format(err)))
                                return False, err
                        else:
                            sample_device.deviceConnection = dev_conn
                            return True, sample_device
                else:

                    dev_conn = Device(host=None, sock_fd=sample_device.deviceConnection, user=c.conf.YAPT.DeviceUsr,
                                      password=Tools.get_password(c.YAPT_PASSWORD_TYPE_DEVICE), gather_facts=False)

                    if dev_conn is not None:

                        if connect:

                            try:
                                dev_conn.open()
                                sample_device.deviceConnection = dev_conn
                                return True, sample_device

                            except jnpr.junos.exception.ConnectError as err:
                                c.logger.info(Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP,
                                                                   logmsg.CONN_MGMT_OPEN_FAILED.format(err)))
                                return False, err
                        else:
                            sample_device.deviceConnection = dev_conn
                            return True, sample_device
            else:

                if c.conf.YAPT.DevicePwdIsRsa:

                    dev_conn = Device(host=sample_device.deviceIP, user=c.conf.YAPT.DeviceUsr,
                                      ssh_private_key_file=Tools.get_password(c.YAPT_PASSWORD_TYPE_DEVICE_RSA))

                    if connect:
                        c.logger.info(Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP,
                                                           logmsg.CONN_MGMT_PROBING_DEV.format(sample_device.deviceIP,
                                                                                               c.conf.YAPT.ConnectionProbeTimeout)))
                        probe = dev_conn.probe(timeout=c.conf.YAPT.ConnectionProbeTimeout)

                        if probe:
                            c.logger.info(Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP,
                                                               logmsg.CONN_MGMT_PROBING_OK.format(
                                                                   sample_device.deviceIP,
                                                                   c.conf.YAPT.ConnectionProbeTimeout)))
                            try:
                                dev_conn.open()
                                sample_device.deviceConnection = dev_conn
                                return True, sample_device

                            except jnpr.junos.exception.ConnectError as err:
                                c.logger.info(Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP,
                                                                   logmsg.CONN_MGMT_OPEN_FAILED.format(err)))
                                return False, err

                        else:
                            c.logger.info(Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP,
                                                               logmsg.CONN_MGMT_PROBING_FAILED.format(
                                                                   sample_device.deviceIP)))
                            return False, Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP,
                                                               logmsg.CONN_MGMT_PROBING_FAILED.format(
                                                                   sample_device.deviceIP))

                    else:
                        sample_device.deviceConnection = dev_conn
                        return True, sample_device

                else:

                    dev_conn = Device(host=sample_device.deviceIP, user=c.conf.YAPT.DeviceUsr,
                                      password=Tools.get_password(c.YAPT_PASSWORD_TYPE_DEVICE), gather_facts=False)

                    if connect:
                        c.logger.info(Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceSerial,
                                                           logmsg.CONN_MGMT_PROBING_DEV.format(sample_device.deviceIP,
                                                                                               c.conf.YAPT.ConnectionProbeTimeout)))
                        probe = dev_conn.probe(timeout=c.conf.YAPT.ConnectionProbeTimeout)

                        if probe:
                            c.logger.info(Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceSerial,
                                                               logmsg.CONN_MGMT_PROBING_OK.format(
                                                                   sample_device.deviceIP,
                                                                   c.conf.YAPT.ConnectionProbeTimeout)))
                            try:
                                dev_conn.open()
                                sample_device.deviceConnection = dev_conn
                                return True, sample_device

                            except jnpr.junos.exception.ConnectError as err:
                                c.logger.info(Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP,
                                                                   logmsg.CONN_MGMT_OPEN_FAILED.format(err)))
                                return False, err

                        else:
                            c.logger.info(Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceSerial,
                                                               logmsg.CONN_MGMT_PROBING_FAILED.format(
                                                                   sample_device.deviceIP)))
                            return False, Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceSerial,
                                                               logmsg.CONN_MGMT_PROBING_FAILED.format(
                                                                   sample_device.deviceIP))
                    else:
                        sample_device.deviceConnection = dev_conn
                        return True, sample_device

        elif c.conf.DEVICEDRIVER.Driver == c.YAPT_DEVICE_DRIVER_NAPALM:

            # Use the appropriate network driver to connect to the device
            driver = napalm.base.get_network_driver(c.conf.DEVICEDRIVER.Napalm.Module)

            # Connect
            dev_conn = driver(hostname=sample_device.deviceIP, username=c.conf.YAPT.DeviceUsr,
                              password=Tools.get_password(c.YAPT_PASSWORD_TYPE_DEVICE),
                              optional_args={'port': c.conf.DEVICEDRIVER.Napalm.Port})

            try:

                sample_device.deviceConnection = dev_conn
                dev_conn.open()
                return True, sample_device

            except (napalm.base.exceptions.ConnectionException, napalm.base.exceptions.ConnectAuthError,
                    jnpr.junos.exception.ConnectError) as err:
                c.logger.info(Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP,
                                                   logmsg.CONN_MGMT_OPEN_FAILED.format(err)))
                return False, Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP,
                                                   logmsg.CONN_MGMT_OPEN_FAILED.format(err))

        else:
            c.logger.info(
                Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP, logmsg.CONN_MGMT_DEV_DRIVER_NOK))
            return False, Tools.create_log_msg(logmsg.CONN_MGMT, sample_device.deviceIP,
                                               logmsg.CONN_MGMT_DEV_DRIVER_NOK)
Пример #40
0
#-----------------------------------------------------------------------------------------------------------------------
# DESCRIPTION:
# Get the state of all interfaces with UPLINK in their description for a device.
#
# CONTACT:   [email protected]; [email protected]; [email protected]; [email protected]; [email protected]
#
# CREATED:  2015-11-11
#
# VERSION: 1
#
# USAGE: get_uplinks_state.py
# -----------------------------------------------------------------------------------------------------------------------

from jnpr.junos.op.phyport import *
from jnpr.junos import Device
ip = raw_input("ip address of the device:")
dev = Device(host=ip, user="******", password="******")
dev.open()
ports = PhyPortTable(dev).get()
for item in ports:
    if item.description and ("UPLINK" in item.description):
        print "Uplink " + item.key + " (" + item.description + ") is " + item.oper
Пример #41
0
import sys
import time
import datetime
from pprint import pprint
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from jnpr.junos import exception as EzErrors

#First, clean up log files

#MCR1.MIN
dev = Device(host='fuji.ultralab.juniper.net',
             user='******',
             password='******')
dev.open()
print 'Clearing MCR1.MIN logs'
dev.cli('clear log messages')
dev.cli('clear log MCR1.MIN.mpls.traceoptions.txt')
dev.close()

#MCR2.MIN
dev = Device(host='lisbon-re0.ultralab.juniper.net',
             user='******',
             password='******')
dev.open()
print 'Clearing MCR2.MIN logs'
dev.cli('clear log messages')
dev.cli('clear log MCR2.MIN.mpls.traceoptions.txt')
dev.close()

#Currently bypassing MCR1.ENG due to hardware.
Пример #42
0
from jnpr.junos.utils.config import Config
from jnpr.junos.exception import ConnectError, ConfigLoadError, LockError, UnlockError, ConnectClosedError, CommitError
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-device', help='Input host name', type=str)
parser.add_argument('-user', help='Input user name', type=str)
parser.add_argument('-password', help='Input password', type=str)
args, unknown = parser.parse_known_args()

device = args.device
user = args.user
password = args.password

print("Open connection ...")
dev = Device(host=device, user=user, password=password, gather_facts=False)
dev.open()

print("Load config  ...")
conf = Config(dev)

print("Locking config ...")
conf.lock()

print("Rollback config ...")
conf.rollback()

data = 'set interfaces gr-0/0/0 description "Some description sample standalone for gr-0/0/0"'
conf.load(data, format='set')  # syntax error raises exception

print("Check  ...")
Пример #43
0
def lict(lict_data):
    try:
        if isinstance(lict_data, list):
            return lict_data
        elif isinstance(lict_data, dict):
            return [lict_data]
    except (RuntimeError, TypeError, NameError):
        pass


host = 'localhost'
username = '******'
port = '2222'
password = '******'
dev = Device(host=host, user=username, passwd=password, port=port)

dev.open()
fp = dev.rpc.get_firewall_policies(detail=True)
dev.close()
x = xmltodict.parse(etree.tostring(fp))
for k in x["security-policies"]["security-context"]:
    for q in k["policies"].values():
        destZone = q["context-information"]["destination-zone-name"]
        srcZone = q["context-information"]["source-zone-name"]
        polName = q["policy-name"]
        polAction = q["policy-action"]["action-type"]
        src = q["source-addresses"]["source-address"]
        srcDetails = src if isinstance(src, list) else [src]
        for p in srcDetails:
            srcName = p["address-name"]
Пример #44
0
from pprint import pprint
from jnpr.junos import Device
dev = Device(host='172.25.11.1', user='******', password='******')
dev.open()
pprint(dev.facts)
dev.close()
Пример #45
0
def fnWriteToDevice(sConfig):
    logging.deug("fnWriteToDevice")
    hDev = Device()
    hDev.open()
    sCu = Config(hDev)

    # Lock the configuration, load configuration changes, and commit
    logging.info("Locking the configuration")
    try:
        sCu.lock()
        logging.debug("Configuration Locked")
    except LockError:
        logging.debug("Error: Unable to lock configuration")
        hDev.close()
        return

    logging.info("Loading configuration changes")
    try:
        if "delete" in sConfig:
            sCU.load(sConfig, format="set")
        else:
            sCu.load(sConfig, format="set", merge=True)
        logging.debug("Configuration Loaded")
    except ConfigLoadError as err:
        logging.debug(err)
        logging.debug("UNABLE TO LOAD CONFIGURATION CHANGES:")
        logging.debug("UNLOCKING THE CONFIGURATION")
    hDev = Device()
    hDev.open()
    sCu = Config(hDev)

    # Lock the configuration, load configuration changes, and commit
    logging.info("Locking the configuration")
    try:
        sCu.lock()
        logging.debug("Configuration Locked")
    except LockError:
        logging.debug("Error: Unable to lock configuration")
        hDev.close()
        return

    logging.info("Loading configuration changes")
    try:
        if "delete" in sConfig:
            sCU.load(sConfig, format="set")
        else:
            sCu.load(sConfig, format="set", merge=True)
        logging.debug("Configuration Loaded")
    except ConfigLoadError as err:
        logging.debug(err)
        logging.debug("UNABLE TO LOAD CONFIGURATION CHANGES:")
        logging.debug("UNLOCKING THE CONFIGURATION")
        try:
            sCu.unlock()
            logging.debug("Configuration Unlocked from Load Failure")
        except UnlockError:
            logging.debug(
                "Error: Unable to unlock configuration from Load Failure")
        sDev.close()
        return

    logging.info("Committing the configuration")
    try:
        dev.cu.commit()
        logging.debug("Commiting Configuration")
        logging.debug(sConfiguration)
    except CommitError:
        logging.debug("Error: Unable to commit configuration")
        logging.debug("Unlocking the configuration")
        try:
            sCu.unlock()
            logging.debug("Configuration Unlocked from Commit Failure")
        except UnlockError:
            logging.debug(
                "Error: Unable to unlock configuration from Commiti Failure")
        sDev.close()
        return

    logging.debug("Unlocking the configuration")
    try:
        dev.cu.unlock()
    except UnlockError:
        logging.debug("Error: Unable to unlock configuration")

    dev.close()
    return
Пример #46
0
  view: EtherSwView

EtherSwView:
  fields:
    vlan_name: mac-vlan
    mac: mac-address
    mac_type: mac-type
    mac_age: mac-age
    interface: mac-interfaces-list/mac-interfaces
'''
# Login to switch
host = raw_input('Enter Switch IP: ')
switch_user = raw_input('Enter switch username: '******'Enter switch password: '******'%s' % (host),
             user='******' % (switch_user),
             password='******' % (switch_password))
dev.open()

# Retrieve ArpTable info
globals().update(FactoryLoader().load(yaml.load(yaml_data)))
table = EtherSwTable(dev)
table.get()

# Organize Arp entries
mac_table = []
for i in table:
    print 'vlan_name:', i.vlan_name
    print 'mac:', i.mac
    print 'mac_type:', i.mac_type
    print 'mac_age:', i.mac_age
Пример #47
0
except ValueError:
    print(
        "\nErro:\n\tO endereço IP informado foi considerado inválido.\n\tPor favor verifique!!"
    )
    sys.exit(1)

#
# Informa que o IP foi aceito e que o script terá continuidade
#
print("\nIP Válido.\nIniciando tentativa de conexão.\nAguarde !!!")

#
# Inicia Variavel para conectar no Juniper
#
junosDev = Device(host=str(device_ip),
                  user=os.environ['PyEZ_User'],
                  password=os.environ['PyEZ_Pass'])

#
# Verifica se a conexão é estabelecida com sucesso
#
try:
    junosDev.open()
except ConnectError as err:
    print(f"Não foi possível conectar-se ao dispositivo: {str(device_ip)}.")
    print(f"Erro:\n\t{err}")
    sys.exit(1)

#
# Informa que a conexão ocorreu com sucesso
#
Пример #48
0
#!/usr/bin/env python

from jnpr.junos import Device
from getpass import getpass
from pprint import pprint

srx2 = {'host': 'srx2.lasthop.io', 'user': '******', 'password': getpass()}

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

pprint(device.facts.get('hostname'))
Пример #49
0
nonpreferredDeviceList = []
for mmpItem in mmpList:
    if mmpItem.keys()[0] == mmp:
        preferredDevice = mmpItem.values()[0]
    else:
        nonpreferredDeviceList.append(mmpItem.values()[0])
preferredSvcList = []
for svcItem in range(3, len(sys.argv)):
    preferredSvcList.append(sys.argv[svcItem])
print 'sas: %s, mmp: %s, svc: %s' % (sas, mmp, preferredSvcList)
print preferredDevice
print nonpreferredDeviceList
print creds['user']
dev = Device(host=preferredDevice,
             user=creds['user'],
             password=creds['password'])
dev.open()
for sasItem in sasList:
    if sasItem.keys()[0] == sas:
        sasPeer = sasItem.values()[0]
for prefSvc in preferredSvcList:
    print 'device %s' % preferredDevice
    varPolicy = "set policy-options policy-statement " + sas + "_" + prefSvc + "_to_var term " + prefSvc + " then metric 10"
    sasPolicy = "set policy-options policy-statement " + sas + "_" + prefSvc + "_to_sas term " + prefSvc + " then local-preference 110"
    print varPolicy
    print sasPolicy
    cfg = Config(dev)
    cfg.lock()
    cfg.load(varPolicy, format="set", merge=True)
    cfg.load(sasPolicy, format="set", merge=True)
Пример #50
0
class TestCurrentRe(unittest.TestCase):
    @patch('ncclient.manager.connect')
    def setUp(self, mock_connect):
        mock_connect.side_effect = self._mock_manager_setup
        self.dev = Device(host='1.1.1.1',
                          user='******',
                          password='******',
                          gather_facts=False)
        self.dev.open()

    @patch('jnpr.junos.Device.execute')
    def test_current_re_fact(self, mock_execute):
        mock_execute.side_effect = self._mock_manager_current_re
        self.assertEqual(self.dev.facts['current_re'],
                         ['re0', 'master', 'node', 'fwdd', 'member', 'pfem'])

    @patch('jnpr.junos.Device.execute')
    def test_current_re_fact_empty(self, mock_execute):
        mock_execute.side_effect = self._mock_manager_current_re_empty
        self.assertEqual(self.dev.facts['current_re'], None)

    @patch('jnpr.junos.Device.execute')
    def test_current_re_fact_srx_cluster_primary(self, mock_execute):
        mock_execute.side_effect = self._mock_manager_current_re_srx_primary
        self.dev.facts._cache['srx_cluster_id'] = '15'
        self.assertEqual(self.dev.facts['current_re'], ['node0', 'primary'])

    @patch('jnpr.junos.Device.execute')
    def test_current_re_fact_srx_cluster_secondary(self, mock_execute):
        mock_execute.side_effect = self._mock_manager_current_re_srx_secondary
        self.dev.facts._cache['srx_cluster_id'] = '15'
        self.assertEqual(self.dev.facts['current_re'], ['node1'])

    @patch('jnpr.junos.Device.execute')
    def test_current_re_fact_srx_cluster_index_error(self, mock_execute):
        mock_execute.side_effect = self._mock_manager_current_re_srx_index_err
        self.dev.facts._cache['srx_cluster_id'] = '15'
        self.assertEqual(self.dev.facts['current_re'], None)

    @patch('jnpr.junos.Device.execute')
    def test_current_re_fact_jdm(self, mock_execute):
        mock_execute.side_effect = self._mock_manager_current_re_jdm
        self.assertEqual(self.dev.facts['current_re'], ['server0'])

    @patch('jnpr.junos.Device.execute')
    def test_current_re_fact_rpc_error(self, mock_execute):
        mock_execute.side_effect = self._mock_manager_current_re_rpc_error
        self.assertEqual(self.dev.facts['current_re'], None)

    def _read_file(self, fname):
        from ncclient.xml_ import NCElement

        fpath = os.path.join(os.path.dirname(__file__), 'rpc-reply', fname)
        foo = open(fpath).read()

        rpc_reply = NCElement(foo,
                              self.dev._conn._device_handler.transform_reply()
                              )._NCElement__doc[0]
        return rpc_reply

    def _mock_manager_setup(self, *args, **kwargs):
        if kwargs:
            device_params = kwargs['device_params']
            device_handler = make_device_handler(device_params)
            session = SSHSession(device_handler)
            return Manager(session, device_handler)

    def _mock_manager_current_re(self, *args, **kwargs):
        if args:
            if args[0].tag == 'file-show' and args[0].xpath(
                    'filename')[0].text == '/usr/share/cevo/cevo_version':
                raise RpcError
            else:
                return self._read_file('current_re_' + args[0].tag + '.xml')

    def _mock_manager_current_re_empty(self, *args, **kwargs):
        if args:
            if args[0].tag == 'file-show' and args[0].xpath(
                    'filename')[0].text == '/usr/share/cevo/cevo_version':
                raise RpcError
            else:
                return self._read_file('current_re_empty_' + args[0].tag +
                                       '.xml')

    def _mock_manager_current_re_srx_primary(self, *args, **kwargs):
        if args:
            if args[0].tag == 'file-show' and args[0].xpath(
                    'filename')[0].text == '/usr/share/cevo/cevo_version':
                raise RpcError
            else:
                return self._read_file('current_re_srx_primary_' +
                                       args[0].tag + '.xml')

    def _mock_manager_current_re_srx_secondary(self, *args, **kwargs):
        if args:
            if args[0].tag == 'file-show' and args[0].xpath(
                    'filename')[0].text == '/usr/share/cevo/cevo_version':
                raise RpcError
            else:
                return self._read_file('current_re_srx_secondary_' +
                                       args[0].tag + '.xml')

    def _mock_manager_current_re_srx_index_err(self, *args, **kwargs):
        if args:
            if args[0].tag == 'file-show' and args[0].xpath(
                    'filename')[0].text == '/usr/share/cevo/cevo_version':
                raise RpcError
            else:
                return self._read_file('current_re_srx_index_err_' +
                                       args[0].tag + '.xml')

    def _mock_manager_current_re_jdm(self, *args, **kwargs):
        if args:
            if args[0].tag == 'file-show' and args[0].xpath(
                    'filename')[0].text == '/usr/share/cevo/cevo_version':
                raise RpcError
            elif (args[0].tag == 'get-interface-information'):
                raise RpcError()
            else:
                return self._read_file('current_re_jdm_' + args[0].tag +
                                       '.xml')

    def _mock_manager_current_re_rpc_error(self, *args, **kwargs):
        if args:
            raise RpcError()
Пример #51
0
        data = yaml.load(yml_var.read(), Loader=yaml.FullLoader)
    # read template
    with open("snmp.j2", "r") as j2_var:
        t_format = j2_var.read()

    template = Template(t_format)
    # render configuration
    myConfig = template.render(data)

    print("\nResults for device " + host + "\n-------------------")

    # show template
    print(myConfig)

    try:
        dev = Device(host=host, user="******", password=pw)
        dev.open()
        # set timeout
        dev.timeout = 10
        # start configuration
        config = Config(dev)
        config.lock()
        config.load(myConfig, merge=True, formt="text")
        # show | compare
        config.pdiff()
        # commit configuration
        config.commit()
        config.unlock()
        dev.close()
    # exceptions
    except ProbeError as e:
Пример #52
0
        print "PFE %s   , NHID %s       , PKTrate %s    , Percentage of PKTrate %s      , Byterate %s   , Percentage of Byterate %s             " % (
            lbpfe[lb], lbnhid[lb], lbnhidpkt[lb], lbnhidpktrate[lb],
            lbnhidbyte[lb], lbnhidbyterate[lb])
        lbshowfile.write(
            "PFE %s        , NHID %s       , PKTrate %s    , Percentage of PKTrate %s      , Byterate %s   , Percentage of Byterate %s             ,\n"
            % (lbpfe[lb], lbnhid[lb], lbnhidpkt[lb], lbnhidpktrate[lb],
               lbnhidbyte[lb], lbnhidbyterate[lb]))


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Enter Device information")
    parser.add_argument('-f',
                        action='store',
                        dest='LBfile',
                        help="Enter File Name for LB")
    parser.add_argument('-a',
                        action='store',
                        dest='Address',
                        help="Enter IP Address for device to monitor")
    parser.add_argument('-u',
                        action='store',
                        dest='unilistnh',
                        help="Enter Unilist NHDB ID to monitor")
    result = parser.parse_args()
    print "IP Address %s" % (result.Address)
    dev = Device(host=result.Address, user="******", passwd="xxxxx")
    dev.open()
    onlinefpcs = onlinefpcs(dev)
    print onlinefpcs
    testunilistlb(dev, onlinefpcs, result.unilistnh, result.LBfile)
Пример #53
0
class TestSW(unittest.TestCase):
    @patch('ncclient.manager.connect')
    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.dev.facts = facts
        self.sw = self.get_sw()

    @patch('jnpr.junos.Device.execute')
    def get_sw(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        return SW(self.dev)

    @patch('ncclient.operations.session.CloseSession.request')
    def tearDown(self, mock_session):
        self.dev.close()

    def test_sw_hashfile(self):
        with patch(builtin_string + '.open', mock_open(), create=True):
            import jnpr.junos.utils.sw
            with open('foo') as h:
                h.read.side_effect = ('abc', 'a', '')
                jnpr.junos.utils.sw._hashfile(h, MagicMock())
                self.assertEqual(h.read.call_count, 3)

    @patch('jnpr.junos.Device.execute')
    def test_sw_constructor_multi_re(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.sw = SW(self.dev)
        self.assertTrue(self.sw._multi_RE)

    @patch('jnpr.junos.Device.execute')
    def test_sw_constructor_multi_vc(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.sw = SW(self.dev)
        self.assertFalse(self.sw._multi_VC)

    @patch(builtin_string + '.open')
    def test_sw_local_sha256(self, mock_built_open):
        package = 'test.tgz'
        self.assertEqual(
            SW.local_checksum(package, algorithm='sha256'),
            'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934'
            'ca495991b7852b855')

    @patch(builtin_string + '.open')
    def test_sw_local_md5(self, mock_built_open):
        package = 'test.tgz'
        self.assertEqual(self.sw.local_checksum(package, algorithm='md5'),
                         'd41d8cd98f00b204e9800998ecf8427e')

    @patch(builtin_string + '.open')
    def test_sw_local_sha1(self, mock_built_open):
        package = 'test.tgz'
        self.assertEqual(SW.local_checksum(package, algorithm='sha1'),
                         'da39a3ee5e6b4b0d3255bfef95601890afd80709')

    def test_sw_local_checksum_unknown_alg(self):
        self.assertRaises(ValueError,
                          SW.local_checksum,
                          'foo.tgz',
                          algorithm='foo')

    def test_sw_progress(self):
        with self.capture(SW.progress, self.dev, 'running') as output:
            self.assertEqual('1.1.1.1: running\n', output)

    @patch('jnpr.junos.Device.execute')
    @patch('paramiko.SSHClient')
    @patch('scp.SCPClient.put')
    def test_sw_progress_true(self, scp_put, mock_paramiko, mock_execute):
        mock_execute.side_effect = self._mock_manager
        with self.capture(SW.progress, self.dev, 'testing') as output:
            self.sw.install('test.tgz',
                            progress=True,
                            checksum=345,
                            cleanfs=False)
            self.assertEqual('1.1.1.1: testing\n', output)

    @patch('paramiko.SSHClient')
    @patch('scp.SCPClient.put')
    def test_sw_put(self, mock_scp_put, mock_scp):
        package = 'test.tgz'
        self.sw.put(package)
        self.assertTrue(
            call('test.tgz', '/var/tmp') in mock_scp_put.mock_calls)

    @patch('jnpr.junos.utils.sw.FTP')
    def test_sw_put_ftp(self, mock_ftp_put):
        dev = Device(host='1.1.1.1',
                     user='******',
                     password='******',
                     mode='telnet',
                     port=23,
                     gather_facts=False)
        sw = SW(dev)
        sw.put(package='test.tgz')
        self.assertTrue(
            call('test.tgz', '/var/tmp') in mock_ftp_put.mock_calls)

    @patch('jnpr.junos.utils.scp.SCP.__exit__')
    @patch('jnpr.junos.utils.scp.SCP.__init__')
    @patch('jnpr.junos.utils.scp.SCP.__enter__')
    def test_sw_put_progress(self, mock_enter, mock_scp, mock_exit):
        package = 'test.tgz'
        mock_scp.side_effect = self._fake_scp
        with self.capture(self.sw.put, package,
                          progress=self._my_scp_progress) as output:
            self.assertEqual('test.tgz 100 50\n', output)

    def _fake_scp(self, *args, **kwargs):
        progress = kwargs['progress']
        progress('test.tgz', 100, 50)

    @patch('jnpr.junos.Device.execute')
    def test_sw_pkgadd(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        package = 'test.tgz'
        self.assertTrue(self.sw.pkgadd(package))

    @patch('jnpr.junos.Device.execute')
    def test_sw_install_single_re(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.sw._multi_RE = False
        self.assertTrue(self.sw.install('test.tgz', no_copy=True))

    @patch('jnpr.junos.Device.execute')
    def test_sw_install_issu(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        package = 'test.tgz'
        self.assertTrue(self.sw.install(package, issu=True, no_copy=True))

    @patch('jnpr.junos.Device.execute')
    def test_sw_install_nssu(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        package = 'test.tgz'
        self.assertTrue(self.sw.install(package, nssu=True, no_copy=True))

    @patch('jnpr.junos.Device.execute')
    def test_sw_install_issu_nssu_both_error(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        try:
            self.sw.install('test.tgz', issu=True, nssu=True)
        except TypeError as ex:
            self.assertEqual(
                str(ex),
                'install function can either take issu or nssu not both')

    @patch('jnpr.junos.Device.execute')
    def test_sw_install_issu_single_re_error(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.sw._multi_RE = False
        try:
            self.sw.install('test.tgz', issu=True)
        except TypeError as ex:
            self.assertEqual(str(ex), 'ISSU/NSSU requires Multi RE setup')

    @patch('jnpr.junos.Device.execute')
    def test_sw_install_issu_nssu_single_re_error(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        package = 'test.tgz'
        self.sw._multi_RE = False
        self.assertRaises(TypeError,
                          self.sw.install,
                          package,
                          nssu=True,
                          issu=True)

    @patch('jnpr.junos.Device.execute')
    def test_sw_pkgaddISSU(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        package = 'test.tgz'
        self.assertTrue(self.sw.pkgaddISSU(package))

    @patch('jnpr.junos.Device.execute')
    def test_sw_pkgaddNSSU(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        package = 'test.tgz'
        self.assertTrue(self.sw.pkgaddNSSU(package))

    @patch('jnpr.junos.Device.execute')
    def test_sw_pkgadd_pkg_set(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        pkg_set = ['abc.tgz', 'pqr.tgz']
        self.sw._mixed_VC = True
        self.sw.pkgadd(pkg_set)
        self.assertEqual(
            [i.text for i in mock_execute.call_args[0][0].findall('set')],
            pkg_set)

    @patch('jnpr.junos.Device.execute')
    def test_sw_validate(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.assertTrue(self.sw.validate('package.tgz'))

    @patch('jnpr.junos.Device.execute')
    def test_sw_validate_nssu(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.sw.log = MagicMock()
        # get_config returns false
        self.assertFalse(self.sw.validate('package.tgz', nssu=True))
        self.sw.log.assert_called_with(
            'Requirement FAILED: GRES is not Enabled in configuration')

    @patch('jnpr.junos.Device.execute')
    def test_sw_validate_issu(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.dev.rpc.get_config = MagicMock()
        self.assertTrue(self.sw.validate('package.tgz', issu=True))

    @patch('jnpr.junos.Device.execute')
    def test_sw_val_issu_request_shell_execute_gres_on(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.dev.rpc.get_config = MagicMock()
        self.dev.rpc.request_shell_execute = MagicMock()
        self.dev.rpc.request_shell_execute.return_value = etree.fromstring(
            """<rpc-reply>
        <output>Graceful switchover: On</output>
        </rpc-reply>""")
        self.assertTrue(self.sw.validate('package.tgz', issu=True))

    @patch('jnpr.junos.Device.execute')
    def test_sw_validate_issu_2re_false(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.dev.facts['2RE'] = False
        self.assertFalse(self.sw.validate('package.tgz', issu=True))
        self.dev.facts['2RE'] = True

    @patch('paramiko.SSHClient')
    @patch('jnpr.junos.utils.start_shell.StartShell.wait_for')
    def test_sw_validate_issu_request_shell_execute(self, mock_ss, mock_ssh):
        self._issu_test_helper()
        with patch('jnpr.junos.utils.start_shell.StartShell.run') as ss:
            ss.return_value = (True, 'Graceful switchover: On')
            self.assertTrue(self.sw.validate('package.tgz', issu=True))

    @patch('paramiko.SSHClient')
    @patch('jnpr.junos.utils.start_shell.StartShell.wait_for')
    def test_sw_validate_issu_ss_login_other_re_fail(self, mock_ss, mock_ssh):
        self._issu_test_helper()
        with patch('jnpr.junos.utils.start_shell.StartShell.run') as ss:
            ss.return_value = (False, 'Graceful switchover: On')
            self.assertFalse(self.sw.validate('package.tgz', issu=True))
        self.sw.log.assert_called_with(
            'Requirement FAILED: Not able run "show system switchover"')

    @patch('paramiko.SSHClient')
    @patch('jnpr.junos.utils.start_shell.StartShell.wait_for')
    def test_sw_validate_issu_ss_graceful_off(self, mock_ss, mock_ssh):
        self._issu_test_helper()
        with patch('jnpr.junos.utils.start_shell.StartShell.run') as ss:
            ss.return_value = (True, 'Graceful switchover: Off')
            self.assertFalse(self.sw.validate('package.tgz', issu=True))
        self.sw.log.assert_called_with(
            'Requirement FAILED: Graceful switchover status is not On')

    def _issu_test_helper(self):
        self.sw.log = MagicMock()
        self.dev.rpc.request_shell_execute = MagicMock()
        self.dev.rpc = MagicMock()
        self.dev.rpc.get_routing_task_replication_state.return_value = \
            self._read_file('get-routing-task-replication-state.xml')
        self.dev.rpc.check_in_service_upgrade.return_value = \
            self._read_file('check-in-service-upgrade.xml')
        self.dev.rpc.request_shell_execute.side_effect = \
            RpcError(rsp='not ok')

    @patch('jnpr.junos.Device.execute')
    def test_sw_validate_issu_stateful_replication_off(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.dev.rpc.get_config = MagicMock()
        self.dev.rpc.get_routing_task_replication_state = MagicMock()
        self.sw.log = MagicMock()
        self.assertFalse(self.sw.validate('package.tgz', issu=True))
        self.sw.log.assert_called_with(
            'Requirement FAILED: Either Stateful Replication is not Enabled or RE mode\nis not Master'
        )

    @patch('jnpr.junos.Device.execute')
    def test_sw_validate_issu_commit_sync_off(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.dev.rpc.get_config = MagicMock()
        self.dev.rpc.get_config.return_value = etree.fromstring("""
        <configuration>
            <chassis>
                <redundancy>
                    <graceful-switchover>
                    </graceful-switchover>
                </redundancy>
            </chassis>
        </configuration>""")
        self.sw.log = MagicMock()
        self.assertFalse(self.sw.validate('package.tgz', issu=True))
        self.sw.log.assert_called_with(
            'Requirement FAILED: commit synchronize is not Enabled in configuration'
        )

    @patch('jnpr.junos.Device.execute')
    def test_sw_validate_issu_nonstop_routing_off(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.dev.rpc.get_config = MagicMock()
        self.dev.rpc.get_config.side_effect = iter([
            etree.fromstring("""
        <configuration>
            <chassis>
                <redundancy>
                    <graceful-switchover>
                    </graceful-switchover>
                </redundancy>
            </chassis>
        </configuration>"""),
            etree.fromstring("""
        <configuration>
            <system>
                <commit>
                    <synchronize/>
                </commit>
            </system>
        </configuration>"""),
            etree.fromstring("""<configuration>
        <routing-options></routing-options>
        </configuration>""")
        ])
        self.sw.log = MagicMock()
        self.assertFalse(self.sw.validate('package.tgz', issu=True))
        self.sw.log.assert_called_with(
            'Requirement FAILED: NSR is not Enabled in configuration')

    @patch('jnpr.junos.Device.execute')
    def test_sw_validate_issu_validation_succeeded(self, mock_execute):
        rpc_reply = """<rpc-reply><output>mgd: commit complete
                        Validation succeeded
                        </output>
                        <package-result>1</package-result>
                        </rpc-reply>"""
        mock_execute.side_effect = etree.fromstring(rpc_reply)
        package = 'package.tgz'
        self.assertFalse(self.sw.validate(package, issu=True))

    @patch('jnpr.junos.Device.execute')
    def test_sw_remote_checksum_not_found(self, mock_execute):
        xml = '''<rpc-error>
        <error-severity>error</error-severity>
        <error-message>
        md5: /var/tmp/123: No such file or directory
        </error-message>
        </rpc-error>'''
        mock_execute.side_effect = RpcError(rsp=etree.fromstring(xml))
        package = 'test.tgz'
        self.assertEqual(self.sw.remote_checksum(package), None)

    @patch('jnpr.junos.Device.execute')
    def test_sw_remote_checksum_not_rpc_error(self, mock_execute):
        xml = '''<rpc-error>
        <error-severity>error</error-severity>
        <error-message>
        something else!
        </error-message>
        </rpc-error>'''
        mock_execute.side_effect = RpcError(rsp=etree.fromstring(xml))
        package = 'test.tgz'
        with self.assertRaises(RpcError):
            self.sw.remote_checksum(package)

    @patch('jnpr.junos.Device.execute')
    def test_sw_remote_checksum_md5(self, mock_execute):
        xml = '''<rpc-reply>
                     <checksum-information>
                         <file-checksum>
                             <computation-method>MD5</computation-method>
                             <input-file>/var/tmp/foo.tgz</input-file>
                             <checksum>8a04cfc475e21507be5145bc0e82ce09</checksum>
                         </file-checksum>
                     </checksum-information>
                 </rpc-reply>'''
        mock_execute.side_effect = etree.fromstring(xml)
        package = 'foo.tgz'
        self.assertEqual(self.sw.remote_checksum(package),
                         '8a04cfc475e21507be5145bc0e82ce09')

    @patch('jnpr.junos.Device.execute')
    def test_sw_remote_checksum_sha1(self, mock_execute):
        xml = '''<rpc-reply>
                     <checksum-information>
                         <file-checksum>
                             <computation-method>SHA1</computation-method>
                             <input-file>/var/tmp/foo.tgz</input-file>
                             <checksum>33c12913e81599452270ee849511e2e7578db00c</checksum>
                         </file-checksum>
                     </checksum-information>
                 </rpc-reply>'''
        mock_execute.side_effect = etree.fromstring(xml)
        package = 'foo.tgz'
        self.assertEqual(self.sw.remote_checksum(package, algorithm='sha1'),
                         '33c12913e81599452270ee849511e2e7578db00c')

    @patch('jnpr.junos.Device.execute')
    def test_sw_remote_checksum_sha256(self, mock_execute):
        xml = '''<rpc-reply>
                     <checksum-information>
                         <file-checksum>
                             <computation-method>SHA256</computation-method>
                             <input-file>/var/tmp/foo.tgz</input-file>
                             <checksum>27bccf64babe4ea6687d3461e6d724d165aa140933e77b582af615dad4f02170</checksum>
                         </file-checksum>
                     </checksum-information>
                 </rpc-reply>'''
        mock_execute.side_effect = etree.fromstring(xml)
        package = 'foo.tgz'
        self.assertEqual(
            self.sw.remote_checksum(package, algorithm='sha256'),
            '27bccf64babe4ea6687d3461e6d724d165aa140933e77b582af615dad4f02170')

    @patch('jnpr.junos.Device.execute')
    def test_sw_safe_copy(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        package = 'safecopy.tgz'
        self.sw.put = MagicMock()
        with patch('jnpr.junos.utils.sw.SW.local_md5'):
            self.assertTrue(
                self.sw.safe_copy(package,
                                  progress=self._myprogress,
                                  cleanfs=True,
                                  checksum='96a35ab371e1ca10408c3caecdbd8a67'))

    @patch('jnpr.junos.Device.execute')
    @patch('jnpr.junos.utils.sw.SW.local_checksum')
    def test_sw_safe_copy_missing_local_file(self, mock_checksum,
                                             mock_execute):
        mock_execute.side_effect = self._mock_manager
        mock_checksum.side_effect = IOError()
        package = 'foo.tgz'
        self.assertFalse(
            self.sw.safe_copy(package, progress=self._myprogress,
                              cleanfs=True))

    @patch('jnpr.junos.Device.execute')
    def test_sw_safe_copy_cleanfs_fail(self, mock_execute):
        mock_execute.side_effect = RpcError()
        package = 'foo.tgz'
        self.assertFalse(
            self.sw.safe_copy(package,
                              progress=self._myprogress,
                              cleanfs=True,
                              checksum='96a35ab371e1ca10408c3caecdbd8a67'))

    @patch('jnpr.junos.Device.execute')
    def test_sw_safe_copy_return_false(self, mock_execute):
        # not passing checksum value, will get random from magicmock
        mock_execute.side_effect = self._mock_manager
        package = 'safecopy.tgz'
        self.sw.put = MagicMock()
        with patch('jnpr.junos.utils.sw.SW.local_md5'):
            self.assertFalse(
                self.sw.safe_copy(package,
                                  progress=self._myprogress,
                                  cleanfs=True))

    @patch('jnpr.junos.Device.execute')
    def test_sw_safe_copy_checksum_none(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        package = 'safecopy.tgz'
        self.sw.put = MagicMock()
        with patch('jnpr.junos.utils.sw.SW.local_md5',
                   MagicMock(return_value='96a35ab371e1ca10408c3caecdbd8a67')):
            self.assertTrue(
                self.sw.safe_copy(package,
                                  progress=self._myprogress,
                                  cleanfs=True))

    @patch('jnpr.junos.Device.execute')
    def test_sw_safe_install(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        package = 'install.tgz'
        self.sw.put = MagicMock()
        with patch('jnpr.junos.utils.sw.SW.local_md5',
                   MagicMock(return_value='96a35ab371e1ca10408c3caecdbd8a67')):
            self.assertTrue(
                self.sw.install(package,
                                progress=self._myprogress,
                                cleanfs=True))

    @patch('jnpr.junos.utils.sw.SW.safe_copy')
    def test_sw_safe_install_copy_fail(self, mock_copy):
        mock_copy.return_value = False
        self.assertFalse(self.sw.install('file'))

    @patch('jnpr.junos.utils.sw.SW.validate')
    def test_sw_install_validate(self, mock_validate):
        mock_validate.return_value = False
        self.assertFalse(self.sw.install('file', validate=True, no_copy=True))

    @patch(builtin_string + '.print')
    @patch('jnpr.junos.utils.sw.SW.pkgadd')
    def test_sw_install_multi_mx(self, mock_pkgadd, mock_print):
        mock_pkgadd.return_value = True
        self.sw._multi_RE = True
        self.sw._multi_MX = True
        self.assertTrue(self.sw.install('file', no_copy=True, progress=True))

    @patch('jnpr.junos.utils.sw.SW.pkgadd')
    def test_sw_install_multi_vc(self, mock_pkgadd):
        mock_pkgadd.return_value = True
        self.sw._multi_RE = True
        self.sw._multi_VC = True
        self.sw._RE_list = ('version_RE0', 'version_RE1')
        self.assertTrue(self.sw.install('file', no_copy=True))

    @patch('jnpr.junos.utils.sw.SW.pkgadd')
    def test_sw_install_mixed_vc(self, mock_pkgadd):
        mock_pkgadd.return_value = True
        self.sw._mixed_VC = True
        self.sw._RE_list = ('version_RE0', 'version_RE1')
        self.assertTrue(
            self.sw.install(pkg_set=['abc.tgz', 'pqr.tgz'], no_copy=True))

    @patch('jnpr.junos.utils.sw.SW.pkgadd')
    def test_sw_install_multi_vc_mode_disabled(self, mock_pkgadd):
        mock_pkgadd.return_value = True
        self.dev._facts = {
            '2RE': True,
            'domain': None,
            'RE1': {
                'status': 'OK',
                'model': 'RE-EX8208',
                'mastership_state': 'backup'
            },
            'ifd_style': 'SWITCH',
            'version_RE1': '12.3R7.7',
            'version_RE0': '12.3',
            'serialnumber': 'XXXXXX',
            'fqdn': 'XXXXXX',
            'RE0': {
                'status': 'OK',
                'model': 'RE-EX8208',
                'mastership_state': 'master'
            },
            'switch_style': 'VLAN',
            'version': '12.3R5-S3.1',
            'master': 'RE0',
            'hostname': 'XXXXXX',
            'HOME': '/var/home/sn',
            'vc_mode': 'Disabled',
            'model': 'EX8208',
            'vc_capable': True,
            'personality': 'SWITCH'
        }
        sw = self.get_sw()
        sw.install(package='abc.tgz', no_copy=True)
        self.assertFalse(sw._multi_VC)
        calls = [
            call('/var/tmp/abc.tgz', dev_timeout=1800, re0=True),
            call('/var/tmp/abc.tgz', dev_timeout=1800, re1=True)
        ]
        mock_pkgadd.assert_has_calls(calls)

    @patch('jnpr.junos.utils.sw.SW.pkgadd')
    def test_sw_install_mixed_vc_with_copy(self, mock_pkgadd):
        mock_pkgadd.return_value = True
        self.sw._mixed_VC = True
        self.sw.put = MagicMock()
        self.sw.remote_checksum = MagicMock(
            return_value='d41d8cd98f00b204e9800998ecf8427e')
        self.sw._RE_list = ('version_RE0', 'version_RE1')
        with patch('jnpr.junos.utils.sw.SW.local_md5',
                   MagicMock(return_value='d41d8cd98f00b204e9800998ecf8427e')):
            self.assertTrue(
                self.sw.install(pkg_set=['install.tgz', 'install.tgz'],
                                cleanfs=False))

    @patch('jnpr.junos.utils.sw.SW.pkgadd')
    def test_sw_install_mixed_vc_safe_copy_false(self, mock_pkgadd):
        mock_pkgadd.return_value = True
        self.sw._mixed_VC = True
        self.sw.safe_copy = MagicMock(return_value=False)
        self.sw.remote_checksum = MagicMock(
            return_value='d41d8cd98f00b204e9800998ecf8427e')
        self.sw._RE_list = ('version_RE0', 'version_RE1')
        with patch('jnpr.junos.utils.sw.SW.local_md5',
                   MagicMock(return_value='d41d8cd98f00b204e9800998ecf8427e')):
            self.assertFalse(
                self.sw.install(pkg_set=['install.tgz', 'install.tgz'],
                                cleanfs=False))

    @patch('jnpr.junos.utils.sw.SW.pkgadd')
    def test_sw_install_mixed_vc_ValueError(self, mock_pkgadd):
        mock_pkgadd.return_value = True
        self.sw._mixed_VC = True
        self.sw.remote_checksum = MagicMock(
            return_value='d41d8cd98f00b204e9800998ecf8427e')
        self.sw._RE_list = ('version_RE0', 'version_RE1')
        with patch('jnpr.junos.utils.sw.SW.local_md5',
                   MagicMock(return_value='d41d8cd98f00b204e9800998ecf8427e')):
            self.assertRaises(ValueError,
                              self.sw.install,
                              pkg_set='install.tgz',
                              cleanfs=False)

    @patch('jnpr.junos.utils.sw.SW.pkgadd')
    def test_sw_install_mixed_vc_TypeError(self, mock_pkgadd):
        self.assertRaises(TypeError, self.sw.install, cleanfs=False)

    @patch('jnpr.junos.Device.execute')
    def test_sw_install_kwargs_force_host(self, mock_execute):
        self.sw.install('file', no_copy=True, force_host=True)
        rpc = [
            '<request-package-add><force-host/><no-validate/><re1/><package-name>/var/tmp/file</package-name></request-package-add>',
            '<request-package-add><package-name>/var/tmp/file</package-name><no-validate/><force-host/><re1/></request-package-add>',
            '<request-package-add><package-name>/var/tmp/file</package-name><no-validate/><re1/><force-host/></request-package-add>',
            '<request-package-add><force-host/><no-validate/><package-name>/var/tmp/file</package-name><re1/></request-package-add>',
            '<request-package-add><force-host/><re1/><no-validate/><package-name>/var/tmp/file</package-name></request-package-add>',
            '<request-package-add><no-validate/><re1/><package-name>/var/tmp/file</package-name><force-host/></request-package-add>',
            '<request-package-add><no-validate/><package-name>/var/tmp/file</package-name><force-host/><re1/></request-package-add>',
            '<request-package-add><force-host/><package-name>/var/tmp/file</package-name><no-validate/><re1/></request-package-add>',
            '<request-package-add><re1/><no-validate/><package-name>/var/tmp/file</package-name><force-host/></request-package-add>',
            '<request-package-add><re1/><force-host/><package-name>/var/tmp/file</package-name><no-validate/></request-package-add>',
            '<request-package-add><re1/><package-name>/var/tmp/file</package-name><force-host/><no-validate/></request-package-add>',
            '<request-package-add><re1/><force-host/><no-validate/><package-name>/var/tmp/file</package-name></request-package-add>',
            '<request-package-add><no-validate/><force-host/><re1/><package-name>/var/tmp/file</package-name></request-package-add>',
            '<request-package-add><package-name>/var/tmp/file</package-name><force-host/><no-validate/><re1/></request-package-add>',
            '<request-package-add><no-validate/><re1/><force-host/><package-name>/var/tmp/file</package-name></request-package-add>',
            '<request-package-add><package-name>/var/tmp/file</package-name><force-host/><re1/><no-validate/></request-package-add>',
            '<request-package-add><no-validate/><force-host/><package-name>/var/tmp/file</package-name><re1/></request-package-add>',
            '<request-package-add><force-host/><no-validate/><package-name>/var/tmp/file</package-name></request-package-add>',
            '<request-package-add><force-host/><package-name>/var/tmp/file</package-name><no-validate/></request-package-add>',
            '<request-package-add><package-name>/var/tmp/file</package-name><no-validate/><force-host/></request-package-add>',
            '<request-package-add><no-validate/><force-host/><package-name>/var/tmp/file</package-name></request-package-add>',
            '<request-package-add><no-validate/><package-name>/var/tmp/file</package-name><force-host/></request-package-add>',
            '<request-package-add><package-name>/var/tmp/file</package-name><force-host/><no-validate/></request-package-add>',
            '<request-package-add><package-name>/var/tmp/file</package-name><re1/><no-validate/><force-host/></request-package-add>',
            '<request-package-add><package-name>/var/tmp/file</package-name><re1/><force-host/><no-validate/></request-package-add>',
            '<request-package-add><force-host/><package-name>/var/tmp/file</package-name><re1/><no-validate/></request-package-add>',
            '<request-package-add><re1/><package-name>/var/tmp/file</package-name><no-validate/><force-host/></request-package-add>',
            '<request-package-add><no-validate/><package-name>/var/tmp/file</package-name><re1/><force-host/></request-package-add>',
            '<request-package-add><re1/><no-validate/><force-host/><package-name>/var/tmp/file</package-name></request-package-add>',
            '<request-package-add><force-host/><re1/><package-name>/var/tmp/file</package-name><no-validate/></request-package-add>'
        ]
        self.assertTrue(
            etree.tostring(mock_execute.call_args[0][0]).decode('utf-8') in
            rpc)

    @patch('jnpr.junos.Device.execute')
    def test_sw_rollback(self, mock_execute):
        rsp = '<rpc-reply><output>junos-vsrx-12.1X46-D30.2-domestic will become active at next reboot</output></rpc-reply>'
        mock_execute.side_effect = etree.XML(rsp)
        msg = 'junos-vsrx-12.1X46-D30.2-domestic will become active at next reboot'
        self.assertEqual(self.sw.rollback(), msg)

    @patch('jnpr.junos.Device.execute')
    def test_sw_rollback_multi(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        msg = {
            'fpc1': "Junos version 'D10.2' will become active at next reboot",
            'fpc0': 'JUNOS version "D10.2" will become active at next reboot'
        }
        self.assertEqual(eval(self.sw.rollback()), msg)

    @patch('jnpr.junos.Device.execute')
    def test_sw_rollback_multi_exception(self, mock_execute):
        fname = 'request-package-rollback-multi-error.xml'
        mock_execute.side_effect = self._read_file(fname)
        self.assertRaises(SwRollbackError, self.sw.rollback)

    @patch('jnpr.junos.Device.execute')
    def test_sw_rollback_exception(self, mock_execute):
        rsp = '<rpc-reply><output>WARNING: Cannot rollback, /packages/junos.old is not valid</output></rpc-reply>'
        mock_execute.side_effect = etree.XML(rsp)
        self.assertRaises(SwRollbackError, self.sw.rollback)

    def test_sw_inventory(self):
        self.sw.dev.rpc.file_list = \
            MagicMock(side_effect=self._mock_manager)
        self.assertEqual(self.sw.inventory, {
            'current': None,
            'rollback': None
        })

    @patch('jnpr.junos.Device.execute')
    def test_sw_reboot(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.sw._multi_MX = True
        self.assertTrue('Shutdown NOW' in self.sw.reboot())

    @patch('jnpr.junos.Device.execute')
    def test_sw_reboot_at(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.assertTrue('Shutdown at' in self.sw.reboot(at='201407091815'))

    @patch('jnpr.junos.Device.execute')
    def test_sw_reboot_multi_re_vc(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.sw._multi_RE = True
        self.sw._multi_VC = False
        self.assertTrue('Shutdown NOW' in self.sw.reboot())

    @patch('jnpr.junos.Device.execute')
    def test_sw_reboot_mixed_vc(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.sw._mixed_VC = True
        self.sw._multi_VC = True
        self.sw.reboot()
        self.assertTrue('all-members' in (
            etree.tostring(mock_execute.call_args[0][0]).decode('utf-8')))

    @patch('jnpr.junos.Device.execute')
    def test_sw_reboot_mixed_vc_all_re_false(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.sw._mixed_VC = True
        self.sw._multi_VC = True
        self.sw.reboot(all_re=False)
        self.assertTrue('all-members' not in (
            etree.tostring(mock_execute.call_args[0][0]).decode('utf-8')))

    @patch('jnpr.junos.Device.execute')
    def test_sw_reboot_exception(self, mock_execute):
        rsp = etree.XML('<rpc-reply><a>test</a></rpc-reply>')
        mock_execute.side_effect = RpcError(rsp=rsp)
        self.assertRaises(Exception, self.sw.reboot)

    @patch('jnpr.junos.Device.execute')
    def test_sw_reboot_exception_RpcTimeoutError(self, mock_execute):
        rsp = (self.dev, 'request-reboot', 60)
        mock_execute.side_effect = RpcTimeoutError(*rsp)
        self.assertRaises(Exception, self.sw.reboot)

    @patch('jnpr.junos.Device.execute')
    def test_sw_poweroff(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.sw._multi_MX = True
        self.assertTrue('Shutdown NOW' in self.sw.poweroff())

    @patch('jnpr.junos.Device.execute')
    def test_sw_poweroff_exception(self, mock_execute):
        rsp = etree.XML('<rpc-reply><a>test</a></rpc-reply>')
        mock_execute.side_effect = RpcError(rsp=rsp)
        self.assertRaises(Exception, self.sw.poweroff)

    @patch('jnpr.junos.Device.execute')
    def test_sw_poweroff_multi_re_vc(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.sw._multi_RE = True
        self.sw._multi_VC = False
        self.assertTrue('Shutdown NOW' in self.sw.poweroff())

    def _myprogress(self, dev, report):
        pass

    def _my_scp_progress(self, _path, _total, _xfrd):
        print(_path, _total, _xfrd)

    @contextmanager
    def capture(self, command, *args, **kwargs):
        out, sys.stdout = sys.stdout, StringIO()
        command(*args, **kwargs)
        sys.stdout.seek(0)
        yield sys.stdout.read()
        sys.stdout = out

    def _read_file(self, fname):
        from ncclient.xml_ import NCElement

        fpath = os.path.join(os.path.dirname(__file__), 'rpc-reply', fname)
        foo = open(fpath).read()
        rpc_reply = NCElement(foo,
                              self.dev._conn._device_handler.transform_reply()
                              )._NCElement__doc[0]
        return rpc_reply

    def _mock_manager(self, *args, **kwargs):
        if kwargs:
            # Little hack for mocked execute
            if 'dev_timeout' in kwargs:
                return self._read_file(args[0].tag + '.xml')
            if 'path' in kwargs:
                if kwargs['path'] == '/packages':
                    return self._read_file('file-list_dir.xml')
            device_params = kwargs['device_params']
            device_handler = make_device_handler(device_params)
            session = SSHSession(device_handler)
            return Manager(session, device_handler)

        elif args:
            if args[0].find('at') is not None:
                return self._read_file('request-reboot-at.xml')
            else:
                return self._read_file(args[0].tag + '.xml')
Пример #54
0
cmdline = argparse.ArgumentParser(
    description="Python JUNOS PyEZ Command Line Tool")
cmdline.add_argument("target", help="Target router to query")
cmdline.add_argument("command", help="Command line to run")
cmdline.add_argument("-p", metavar="port", help="TCP port", default=830)
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

rpc = dev.display_xml_rpc(args.command)

if type(rpc) is etree._Element:
    rpc.attrib['format'] = 'text'
    result = dev.rpc(rpc)
    print result.text

else:
    print "XML RPC for command not available: ", rpc

dev.close()
Пример #55
0
class Junos(GenericDevice):
    @classmethod
    def get_functions(cls):
        return ['up_interfaces', 'lldp']

    def __init__(self, aIP, aID=None):
        GenericDevice.__init__(self, aIP, aID)
        from jnpr.junos import Device as JunosDevice
        from jnpr.junos.utils.config import Config
        from sdcp.SettingsContainer import SC
        self._router = JunosDevice(self._ip,
                                   user=SC['netconf']['username'],
                                   password=SC['netconf']['password'],
                                   normalize=True)
        self._config = Config(self._router)
        self._model = ""
        self._version = ""
        self._interfacesname = {}

    def __str__(self):
        return "{} Model:{} Version:{}".format(str(self._router), self._model,
                                               self._version)

    def __enter__(self):
        if self.connect():
            return self
        else:
            raise RuntimeError("Error connecting to host")

    def __exit__(self, *ctx_info):
        self.close()

    def connect(self):
        try:
            self._router.open()
            self._model = self._router.facts['model']
            self._version = self._router.facts['version']
        except Exception as err:
            self.log_msg("System Error - Unable to connect to router: " +
                         str(err))
            return False
        return True

    def close(self):
        try:
            self._router.close()
        except Exception as err:
            self.log_msg(
                "System Error - Unable to properly close router connection: " +
                str(err))

    def get_rpc(self):
        return self._router.rpc

    def get_dev(self):
        return self._router

    def get_interface_name(self, aifl):
        return self._interfacesname.get(aifl.split('.')[0])

    #
    # Netconf shit
    #
    def ping_rpc(self, ip):
        result = self._router.rpc.ping(host=ip, count='1')
        return len(result.xpath("ping-success"))

    def get_facts(self, akey):
        return self._router.facts[akey]

    def load_interfaces_name(self):
        interfaces = self._router.rpc.get_interface_information(
            descriptions=True)
        for interface in interfaces:
            ifd = interface.find("name").text
            description = interface.find("description").text
            self._interfacesname[ifd] = description

    def up_interfaces(self):
        interfaces = self._router.rpc.get_interface_information()
        ret = []
        for ifd in interfaces:
            entry = {
                'Interface': ifd[0].text,
                'State': ifd[2].text,
                'SNMP': ifd[4].text,
                'Type': ifd[5].text
            }
            # Split ge-0/0/0 into ge and 0/0/0, remove extra numbers for aeX interfaces
            tp = entry['Interface'].partition('-')[0].rstrip('0123456789')
            if tp in ['ge', 'fe', 'xe', 'et', 'st0', 'ae'
                      ] and entry['State'] == "up":
                ret.append(entry)
        return ret

    def lldp(self):
        neighbors = self._router.rpc.get_lldp_neighbors_information()
        ret = []
        for neigh in neighbors:
            # Remote system always last, remote port second to last, local is always first and pos 3 (2) determines if there is a mac or not
            fields = len(neigh) - 1
            ret.append({
                'Neighbor':
                neigh[fields].text,
                'MAC':
                neigh[3].text if neigh[2].text == "Mac address" else '-',
                'Local_port':
                neigh[0].text,
                'Destination_port':
                neigh[fields - 1].text
            })
        return ret

    def configuration(self, argdict):
        from sdcp.SettingsContainer import SC
        base = "set groups default_system"
        ret = ["set system host-name %s" % (argdict['hostname'])]
        if SC['netconf']['username'] == 'root':
            ret.append(
                "set system root-authentication encrypted-password \"%s\"" %
                (SC['netconf']['encrypted']))
        else:
            ret.append('set system login user %s class super-user' %
                       (SC['netconf']['username']))
            ret.append(
                'set system login user %s authentication encrypted-password "%s"'
                % (SC['netconf']['username'], SC['netconf']['encrypted']))
        ret.extend([
            '%s system domain-name %s' % (base, argdict['domain']),
            '%s system domain-search %s' % (base, argdict['domain']),
            '%s system name-server %s' % (base, SC['netconf']['dnssrv']),
            '%s system services ssh root-login allow' % base,
            '%s system services netconf ssh' % base,
            '%s system syslog user * any emergency' % base,
            '%s system syslog file messages any notice' % base,
            '%s system syslog file messages authorization info' % base,
            '%s system syslog file interactive-commands interactive-commands any'
            % base,
            '%s system archival configuration transfer-on-commit' % base,
            '%s system archival configuration archive-sites ftp://%s' %
            (base, SC['netconf']['anonftp']),
            '%s system commit persist-groups-inheritance' % base,
            '%s system ntp server %s' % (base, SC['netconf']['ntpsrv']),
            '%s routing-options static route 0.0.0.0/0 next-hop %s' %
            (base, argdict['gateway']),
            '%s routing-options static route 0.0.0.0/0 no-readvertise' % base,
            '%s snmp community %s clients %s/%s' %
            (base, SC['snmp']['read_community'], argdict['subnet'],
             argdict['mask']),
            '%s protocols lldp port-id-subtype interface-name' % base,
            '%s protocols lldp interface all' % base,
            '%s class-of-service host-outbound-traffic forwarding-class network-control'
            % base, 'set apply-groups default_system'
        ])
        return ret
Пример #56
0
def hardCodeOut(fpcList, fpcType):
    for fpc in fpcList:
        print("<fpc>")
        for key, val in fpc.items():
            #print key
            #print val
            #This retrieves the chip type needed to run the correct YAML files, which is tested by the if-statements inside the for-loop.
            for chip, num in val["center_chip"].items():

                if chip == "xm":
                    #The tables had to be imported conditionally because although there are separate YAML files and tables for each chip type, the tables have the same exact name, so the tables cannot be imported all at the same time

                    from chip_agnostic_command_package.chip_agnostic_command.yamls.xm_li_error import CChipLiInterruptStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.xm_wi_statistics import CChipWiStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.xm_wo_statistics import CChipWoStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.xm_fo_statistics import CChipFOStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.xm_fi_statistics import CChipFiStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.xm_fi_error import CChipFiErrTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.xm_lo_statistics import CChipLoStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.xm_host_drop import CChipHostDropTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.xm_drd_error import CChipDRDErrTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.xm_pt_statistics import CChipPTStatTable

                    with Device() as dev:

                        for i in range(num):
                            print("<fpc-num>{}</fpc-num>".format(key+" "+"chip instance "+str(i)))
                            for fpcKey, typeVal in fpcType.items():
                                if fpcKey == key:
                                    printFpcType = typeVal
                            print("<fpc-type>fpc type {}</fpc-type>".format(str(printFpcType)))
                            print("<chip-instance>")

                            #Since there are multiple instances for some center chips and multiple fpcs online, the fpc name and instance must be passed as variables to each YAML file by giving arguments to the get() method
                            dataPrint = {}
                            xm = CChipLiInterruptStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/xm_li_error.yml", 'r') as stream:
                                counterDict = getEvalDicts(xm.items())
                                dataList = parseOut(xm, stream, counterDict)
                                dataPrint.update({xm: dataList})

                            xm = CChipWiStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/xm_wi_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(xm.items())
                                dataList = parseOut(xm, stream, counterDict)
                                dataPrint.update({xm: dataList})

                            xm = CChipWoStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/xm_wo_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(xm.items())
                                dataList = parseOut(xm, stream, counterDict)
                                dataPrint.update({xm: dataList})

                            xm = CChipFOStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/xm_fo_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(xm.items())
                                dataList = parseOut(xm, stream, counterDict)
                                dataPrint.update({xm: dataList})

                            xm = CChipFiStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/xm_fi_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(xm.items())
                                dataList = parseOut(xm, stream, counterDict)
                                dataPrint.update({xm: dataList})

                            xm = CChipFiErrTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/xm_fi_error.yml", 'r') as stream:
                                counterDict = getEvalDicts(xm.items())
                                dataList = parseOut(xm, stream, counterDict)
                                dataPrint.update({xm: dataList})

                            xm = CChipLoStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/xm_lo_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(xm.items())
                                dataList = parseOut(xm, stream, counterDict)
                                dataPrint.update({xm: dataList})

                            xm = CChipHostDropTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/xm_host_drop.yml", 'r') as stream:
                                counterDict = getEvalDicts(xm.items())
                                dataList = parseOut(xm, stream, counterDict)
                                dataPrint.update({xm: dataList})

                            xm = CChipDRDErrTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/xm_drd_error.yml", 'r') as stream:
                                counterDict = getEvalDicts(xm.items())
                                dataList = parseOut(xm, stream, counterDict)
                                dataPrint.update({xm: dataList})

                            xm = CChipPTStatTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/xm_pt_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(xm.items())
                                dataList = parseOut(xm, stream, counterDict)
                                dataPrint.update({xm: dataList})

                            col_width = 0
                            for k,v in dataPrint.items():
                                if v:
                                    if col_width == 0 or col_width < (max(len(word) for row in v for word in row) + 2):
                                        col_width = max(len(word) for row in v for word in row) + 2

                            print("<cchip>")
                            print("<outputs>")
                            for k,v in dataPrint.items():

                                strXM = str(k)
                                sep = ":"
                                rest = strXM.split(sep, 1)[0]
                                print("<cchip-table>")
                                print("<table-name>{}</table-name>".format(rest))
                                print("<cchip-table-data>")
                                for row in v:
                                    print("<counter-list>")
                                    print("<counter>{}</counter>".format("".join(word.ljust(col_width) for word in row)))
                                    print("<nested-counter></nested-counter>")
                                    print("</counter-list>")
                                print("</cchip-table-data>")
                                print("</cchip-table>")

                            print("</outputs>")
                            print("</cchip>")

                            print("</chip-instance>")

                if chip == "mqss":

                    from chip_agnostic_command_package.chip_agnostic_command.yamls.ea_li_error import CChipLiInterruptStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.ea_wi_statistics import CChipWiStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.ea_wo_statistics import CChipWoStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.ea_fo_statistics import CChipFOStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.ea_fi_statistics import CChipFiStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.ea_fi_error import CChipFiErrTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.ea_lo_statistics import CChipLoStatsTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.ea_host_drop import CChipHostDropTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.ea_drd_error import CChipDRDErrTable
                    from chip_agnostic_command_package.chip_agnostic_command.yamls.ea_pt_statistics import CChipPTStatTable

                    with Device() as dev:
                        for i in range(num):
                            dataPrint = {}
                            print("<fpc-num>{}</fpc-num>".format(key+" "+"chip instance "+str(i)))
                            for fpcKey, typeVal in fpcType.items():
                                if fpcKey == key:
                                    printFpcType = typeVal
                            print("<fpc-type>fpc type {}</fpc-type>".format(str(printFpcType)))
                            print("<chip-instance>")

                            ea = CChipLiInterruptStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/ea_li_error.yml", 'r') as stream:
                                counterDict = getEvalDicts(ea.items())
                                dataList = parseOut(ea, stream, counterDict)
                                dataPrint.update({ea: dataList})

                            ea = CChipWiStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/ea_wi_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(ea.items())
                                dataList = parseOut(ea, stream, counterDict)
                                dataPrint.update({ea: dataList})

                            ea = CChipWoStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/ea_wo_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(ea.items())
                                dataList = parseOut(ea, stream, counterDict)
                                dataPrint.update({ea: dataList})

                            ea = CChipFOStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/ea_fo_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(ea.items())
                                dataList = parseOut(ea, stream, counterDict)
                                dataPrint.update({ea: dataList})

                            ea = CChipFiStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/ea_fi_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(ea.items())
                                dataList = parseOut(ea, stream, counterDict)
                                dataPrint.update({ea: dataList})

                            ea = CChipFiErrTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/ea_fi_error.yml", 'r') as stream:
                                counterDict = getEvalDicts(ea.items())
                                dataList = parseOut(ea, stream, counterDict)
                                dataPrint.update({ea: dataList})

                            ea = CChipLoStatsTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/ea_lo_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(ea.items())
                                dataList = parseOut(ea, stream, counterDict)
                                dataPrint.update({ea: dataList})

                            ea = CChipHostDropTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/ea_host_drop.yml", 'r') as stream:
                                counterDict = getEvalDicts(ea.items())
                                dataList = parseOut(ea, stream, counterDict)
                                dataPrint.update({ea: dataList})

                            ea = CChipDRDErrTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/ea_drd_error.yml", 'r') as stream:
                                counterDict = getEvalDicts(ea.items())
                                dataList = parseOut(ea, stream, counterDict)
                                dataPrint.update({ea: dataList})

                            ea = CChipPTStatTable(dev).get(target = key, args = {'chip_instance': i})
                            with open(path+"/ea_pt_statistics.yml", 'r') as stream:
                                counterDict = getEvalDicts(ea.items())
                                dataList = parseOut(ea, stream, counterDict)
                                dataPrint.update({ea: dataList})

                            col_width = 0
                            for k,v in dataPrint.items():
                                if v:
                                    if col_width == 0 or col_width < (max(len(word) for row in v for word in row) + 2):
                                        col_width = max(len(word) for row in v for word in row) + 2

                            print("<cchip>")
                            print("<outputs>")
                            i = 0
                            for k,v in dataPrint.items():

                                strXM = str(k)
                                sep = ":"
                                rest = strXM.split(sep, 1)[0]
                                print("<cchip-table>")
                                print("<table-name>{}</table-name>".format(rest))
                                print("<cchip-table-data>")
                                for row in v:
                                    i = i+1
                                    #if "plane" not in str(row) and "cchip-fo-total-packets-sent" not in str(row):
                                    print("<counter-list>")
                                    print("<counter>{}</counter>".format("".join(word.ljust(col_width) for word in row)))
                                    print("<nested-counter></nested-counter>")
                                    print("</counter-list>")

                                    #else:
                                        #if "plane" in str(row):
                                        #    print("<counter-list>")
                                            #print("<counter>{}</counter>".format("".join(word.ljust(col_width) for word in row)))
                                        #    print("<counter>{}".format("".join(word.ljust(col_width) for word in row))+str(i)+"</counter>")

                                        #if "cchip-fo-total-packets-sent" in str(row):
                                            #print("<nested-counter>{}</nested-counter>".format("".join(word.ljust(col_width) for word in row)))
                                        #    print("<nested-counter>{}".format("".join(word.ljust(col_width) for word in row))+str(i)+"</nested-counter>")
                                        #    print("</counter-list>")

                                print("</cchip-table-data>")
                                print("</cchip-table>")

                            print("</outputs>")
                            print("</cchip>")

                            print("</chip-instance>")

        print("</fpc>")
Пример #57
0
# template to configure junos
f=open('junos_configuration/junos.j2')
my_template = Template(f.read())
f.close()

# get devices list. each item has an ip, name, username, password.
f=open('variables.yml', 'r')
devices_list = load(f.read())['junos']
f.close()

# get junos variables: interfaces, asn, ....
f=open('junos_configuration/junos.yml', 'r')
junos_vars = load(f.read())
f.close()

for item in devices_list:
    device=Device (host=item['ip'], user=item['username'], password=item['passwd'])
    host_vars = junos_vars[item['name']]
    f=open('junos_configuration/' + item['name'] + '.conf','w')
    f.write(my_template.render(host_vars))
    f.close()
    junos_conf = 'junos_configuration/' + item['name'] + '.conf'
    device.open()
    cfg=Config(device)
    cfg.load(path=junos_conf, format='text')
    cfg.commit()
    device.close()
    print 'configured device ' + item['name']


Пример #58
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 = "******"

print "\nPlease provide password for user '" + user + "' on device '" + sys.argv[
    1] + "'."
passwd = getpass()

dev = Device(sys.argv[1], user=user, password=passwd)
try:
    dev.open()
    print "Connected to " + sys.argv[1] + " as", (user)
except:
    print "Connection failed. :-("
    print "\n** Type exit() to quit **"


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


#print FPC hardware Table
#get-chassis-inventory
Пример #59
0
        'id': '40'
    }, {
        'name': 'test5',
        'id': '50'
    }, {
        'name': 'test6',
        'id': '60'
    }]
}

# Filter warnings
warnings.filterwarnings(action='ignore', module='.*paramiko.*')

# Create vlans
for a_vqfx in all_vqfx:
    dev = Device(host=a_vqfx['host'], user=a_vqfx['user'], port=a_vqfx['port'])
    try:
        dev.open()
        print('\nConfiguring vlans for {0}{1} - {2}{3}\n'.format(
            INFO, a_vqfx['host'], a_vqfx['port'], NORMAL))
        with Config(dev, mode='exclusive') as cu:
            cu.load(template_path=conf_file,
                    template_vars=config_vars,
                    merge=True)
            cu.commit()
    except ConnectError as err:
        print('Cannot connect to device: {0}'.format(err))
        sys.exit(1)
    except Exception as err:
        print(err)
        sys.exit(1)
Пример #60
0
import sys
import os
import getpass
import json
import xmltodict
from lxml import etree
from jnpr.junos import Device
from jnpr.junos.exception import *
from jnpr.junos.factory.factory_loader import FactoryLoader


def lict(lict_data):
    try:
        if isinstance(lict_data, list):
            return lict_data
        elif isinstance(lict_data, dict):
            return [lict_data]
    except (RuntimeError, TypeError, NameError):
        pass


intf_type = ['fe', 'ge', 'xe', 'et', 'irb', 'st0', 'vlan']

dev = Device(host='localhost', user='******', passwd='Juniper', port='2222')

dev.open()
intf = dev.rpc.get_interface_information()
hostname = dev.facts.get("hostname")
dev.close()
data = xmltodict.parse(etree.tostring(intf))
print(json.dumps(data, indent=4))