5 de mai. de 2018

NAPALM - Parte III

Olá Pessoal Boa Tarde, hoje vamos utilizar NAPALM para mudar as configurações dos nossos roteadores.

A topologia física vai ser a mesma utilizada até agora. Dois roteadores R1-IOS e R2-JunOS, e um host representando pela nuvem Cloud1.



Ambos os roteadores estão rodando OSPF, e todas as suas interfaces estão na área 0.

O objetivo será, trocar de OSPF para BGP. Ficando R1 no AS100 e R2 no AS200.

Os novos arquivos de configuração podem ser baixados de:

https://github.com/JoseBalbuena/BlogNetFinders/blob/master/NAPALM_PARTEIII_R2.conf

https://github.com/JoseBalbuena/BlogNetFinders/blob/master/NAPALM_PARTEIII_R1.conf


Dessa vez vamos utilizar o método load_replace_candidate() da livraria NAPALM.

O único detalhe a ter em consideração é que eu preciso começar a configurar pelo roteador R2, isso porque quando faça a troca de configuração eu vou perder a conetividade com R2, porém quando configure R1 e o peer BGP fechar a conexão irá voltar.

Se eu começar por R1, vou perder conetividade com R2 e nunca mais vou ter acesso.

O meu script ficaria assim:


#!/usr/bin/python

import napalm

#Router diccionario
R1={'so':'ios','hostname':'R1','ip':'1.1.1.1','username':'napalm','password':'napalm','secret':'cisco','newfile':'/home/jose/Automatizacao/R1_new.conf'}
R2={'so':'junos','hostname':'R2','ip':'2.2.2.2','username':'napalm','password':'napalm123','newfile':'/home/jose/Automatizacao/R2_new.conf'}

#Listado dos meus roteadores
routers=[R2,R1] #R2 primeiro na lista


#BEGIN


#Loop para fazer varredura
for router in routers:
 #Caso seja um roteador IOS, utilizar o parametro optional_args com a senha de enable
 if router['so'] == 'ios':
  optional_args={'secret':router['secret']}
 else:
  optional_args={}
 #Selecctiona o driver
 driver = napalm.get_network_driver(router['so'])
 #Coneta ao roteador, dentro de um try..execpt, caso de algum erro o erro eh printado
 try:
  device = driver (hostname=router['ip'], username=router['username'], password=router['password'],optional_args=optional_args)
  device.open()
  #Carrega o arquivo das atualizacoes a serem feitas
  device.load_replace_candidate(filename=router['newfile'])
  #Faz o commit
  device.commit_config()
  #Fecha a conexao
  device.close()
 except Exception as error:
  print "Problemas com driver/sessao do roteador %s" % router['ip']
  print error

#FIM


Quando executamos o script:

jose@rejane:~/Automatizacao$ ./napalm_newconf_ex3.py 
Problemas com driver/sessao do roteador 2.2.2.2
RpcTimeoutError(host: 2.2.2.2, cmd: commit-configuration, timeout: 60)
jose@rejane:~/Automatizacao$ 

Podemos apreciar que ao executar o script,  NAPALM atacha um erro no "commit_config()" para R2, esse erro acontece pelo fato de que quando o commit é executado em R2, automaticamente a nossa conexão ao roteador é perdida. O NAPALM não recebe a resposta do "commit" em R2 e atacha o erro acima. Mas a configuração foi aplicada em R2, a única coisa que falto foi o NAPALM receber a resposta. Resumindo o erro é na livraria do NAPALM e não no "commit" em R2.

O ideal é não perder a conetividade, quem sabe manter o OSPF rodando, mas para própositos de testes e de saber como funcionam as coisas, esta tudo OK.

Verificando em R1:

R1#sh ip bgp summary 
BGP router identifier 1.1.1.1, local AS number 100
BGP table version is 5, main routing table version 5
4 network entries using 592 bytes of memory
4 path entries using 256 bytes of memory
2/2 BGP path/bestpath attribute entries using 272 bytes of memory
1 BGP AS-PATH entries using 24 bytes of memory
0 BGP route-map cache entries using 0 bytes of memory
0 BGP filter-list cache entries using 0 bytes of memory
BGP using 1144 total bytes of memory
BGP activity 4/0 prefixes, 4/0 paths, scan interval 60 secs

Neighbor        V           AS MsgRcvd MsgSent   TblVer  InQ OutQ Up/Down  State/PfxRcd
10.10.10.2      4          200      45      45        5    0    0 00:18:38        2
R1#sh ip bgp
BGP table version is 5, local router ID is 1.1.1.1
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal, 
              r RIB-failure, S Stale, m multipath, b backup-path, f RT-Filter, 
              x best-external, a additional-path, c RIB-compressed, 
Origin codes: i - IGP, e - EGP, ? - incomplete
RPKI validation codes: V valid, I invalid, N Not found

     Network          Next Hop            Metric LocPrf Weight Path
 *>  1.1.1.0/24       0.0.0.0                  0         32768 i
 *>  2.2.2.0/24       10.10.10.2                             0 200 i
 r>  10.10.10.0/24    10.10.10.2                             0 200 i
 *>  192.168.200.0    0.0.0.0                  0         32768 i
R1#



Verificando em R2:

napalm@JunOS-R2> show bgp summary 
Groups: 1 Peers: 1 Down peers: 0
Table          Tot Paths  Act Paths Suppressed    History Damp State    Pending
inet.0                 2          2          0          0          0          0
Peer                     AS      InPkt     OutPkt    OutQ   Flaps Last Up/Dwn State|#Active/Received/Accepted/Damped...
10.10.10.1              100         43         43       0       0       17:57 2/2/2/0              0/0/0/0

napalm@JunOS-R2> 

napalm@JunOS-R2> show route          

inet.0: 6 destinations, 6 routes (6 active, 0 holddown, 0 hidden)
+ = Active Route, - = Last Active, * = Both

1.1.1.0/24         *[BGP/170] 00:18:18, MED 0, localpref 100
                      AS path: 100 I
                    > to 10.10.10.1 via em0.0
2.2.2.0/24         *[Direct/0] 01:00:02
                    > via lo0.0
2.2.2.2/32         *[Local/0] 01:00:02
                      Local via lo0.0
10.10.10.0/24      *[Direct/0] 01:00:03
                    > via em0.0
10.10.10.2/32      *[Local/0] 01:00:03
                      Local via em0.0
192.168.200.0/24   *[BGP/170] 00:05:38, MED 0, localpref 100
                      AS path: 100 I
                    > to 10.10.10.1 via em0.0

napalm@JunOS-R2> 


Podemos ver que o BGP foi estabelecido e as rotas tb estão OK.

Desde o host conseguimos pingar tanto para R1 e R2.

jose@rejane:~$ ping 1.1.1.1
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
64 bytes from 1.1.1.1: icmp_seq=1 ttl=255 time=11.4 ms
64 bytes from 1.1.1.1: icmp_seq=2 ttl=255 time=9.09 ms
^C
--- 1.1.1.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 9.090/10.258/11.427/1.172 ms
jose@rejane:~$ ping 2.2.2.2
PING 2.2.2.2 (2.2.2.2) 56(84) bytes of data.
64 bytes from 2.2.2.2: icmp_seq=1 ttl=63 time=11.6 ms
64 bytes from 2.2.2.2: icmp_seq=2 ttl=63 time=20.1 ms
^C
--- 2.2.2.2 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 11.603/15.891/20.180/4.290 ms
jose@rejane:~$ 


Bom é isso ai pessoal, nesse três últimos post aprendimos como "coletar informação", "Atualizar a configuração" e "Reemplazar a configuração", utilizando a livraria NAPALM.

Os script são simples, visto que o próposito deles é o ensino, mas vocês podem incluir muitas coisas neles, como logs, entrada de teclado quem sabe ler as configurações dos roteadores de algum banco de dados etc etc..

O próximo post iremos falar de YAML e JINJA2..

Abçs e um ótimo final de semana!!
Jose



37 comentários:

  1. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    full Stack developer Training in Bangalore

    ResponderExcluir
  2. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
    Click here:
    python training in OMR
    Click here:
    python training in Bangalore

    ResponderExcluir
  3. I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community.
    Blue Prism Training in Pune

    Blueprism training in tambaram

    Blueprism training in annanagar

    ResponderExcluir
  4. I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community.
    Blue Prism Training in Pune

    Blueprism training in tambaram

    Blueprism training in annanagar

    ResponderExcluir
  5. Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
    java training in tambaram | java training in velachery

    java training in omr | oracle training in chennai

    ResponderExcluir
  6. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    python training in tambaram | python training in annanagar | python training in jayanagar

    ResponderExcluir
  7. Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
    python training in bangalore

    ResponderExcluir
  8. I Got Job in my dream company with decent 12 Lacks Per Annum salary, I have learned this world most demanding course out there in the current IT Market from the data science training in pune Providers who helped me a lot to achieve my dreams comes true. Really worth trying instant approval blog commenting sites

    ResponderExcluir
  9. Este comentário foi removido pelo autor.

    ResponderExcluir
  10. I want to appreciate for this wonderful blog!

    BEST ANGULAR JS TRAINING IN CHENNAI WITH PLACEMENT

    https://www.acte.in/angular-js-training-in-chennai
    https://www.acte.in/angular-js-training-in-annanagar
    https://www.acte.in/angular-js-training-in-omr
    https://www.acte.in/angular-js-training-in-porur
    https://www.acte.in/angular-js-training-in-tambaram
    https://www.acte.in/angular-js-training-in-velachery

    ResponderExcluir
  11. Your good knowledge and kindness in playing with all the pieces were very useful. I don't know what I would have done if I had not encountered such a step like this.
    IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    Spoken english classes in chennai | Communication training

    ResponderExcluir
  12. This was nice and amazing and the given contents were very useful and the precision has given here is good.

    Data Science Training Institute in Bangalore

    ResponderExcluir
  13. we are as a matter of fact grateful in your weblog proclaim. you will find a ton of approaches subsequent to traveling your screen. I was precisely endeavoring to find. gratitude for such say and make grin shop it taking area. extraordinary do whatever it takes..! Antimalware Keygen

    ResponderExcluir
  14. I portt any expression to comprehend this pronounce.....really i'm dazzled from this publicize....the individual who make this guarantee it turned into a pleasurable human..thank you for shared this toward the rear of than us..! https://wishesquotz.com/meaningful-fathers-day-quotes/

    ResponderExcluir