Network Automation menggunakan Python – Napalm

Network Automation Python

NAPALM (Network Automation and Programmability Abstraction Layer with Multivendor support) merupakan salah satu library python yang dapat digunakan untuk melakukan network automation. Napalm mendukung beberapa OS jaringan seperti, Arista EOS, Cisco IOS, Cisco IOS-XR, Cisco NX-OS dan Juniper JunOS. Kebanyakan Napalm digunakan untuk mendapatkan informasi dari perangkat jaringan, misalkan OS Version, hostname dan list interface.

Instalasi Napalm

$ pip3 install napalm
$ apt install libssl-dev libffi-dev python-dev python-cffi

Di bawah ini adalah contoh sederhana penggunaan Napalm di python. Perangkat yang digunakan adalah Cisco (IOS). Jangan lupa untuk melakukan konfigurasi SSH pada perangkat sebelum melakukan konfigurasi atau otomasi menggunakan Napalm.

Contoh 1

from napalm import get_network_driver

driver = get_network_driver('ios')
enpass = {'secret':'enablepass'}
device = driver(hostname='192.168.124.130',username='cisco',password='ciscopass',optional_args=enpass)
device.open()

devshow = device.get_facts()
print(devshow)

device.close()
$ python3 napalm-1.py

{'uptime': 3300, 'vendor': 'Cisco', 'os_version': 'Linux Software (I86BI_LINUXL2-ADVENTERPRISEK9-M), Version 15.2(CML_NIGHTLY_20150703)FLO_DSGS7, EARLY DEPLOYMENT DEVELOPMENT BUILD, synced to  DSGS_PI5_POSTCOLLAPSE_TEAM_TRACK_CLONE', 'serial_number': '2048001', 'model': 'Unknown', 'hostname': 'S1', 'fqdn': 'S1.cisco.com', 'interface_list': ['Ethernet0/0', 'Ethernet0/0.10', 'Ethernet0/1', 'Ethernet0/2', 'Ethernet0/3', 'Ethernet1/0', 'Ethernet1/1', 'Ethernet1/2', 'Ethernet1/3', 'Ethernet2/0', 'Ethernet2/1', 'Ethernet2/2', 'Ethernet2/3', 'Ethernet3/0', 'Ethernet3/1', 'Ethernet3/2', 'Ethernet3/3', 'Vlan1']}

get_network_driver : menentukan jenis os pada perangkat yang akan di-remote.
enpass : variabel untuk menyimpan password enable (privilege mode).
driver : variabel untuk menyimpan informasi mengenai perangkat yang akan di-remote.
open() : melakukan koneksi ke perangkat.
get_facts() : mendapatkan informasi pada perangkat.

Contoh 2 – Menggunakan Format JSON

from napalm import get_network_driver
import json

driver = get_network_driver('ios')
enpass = {'secret':'enablepass'}
device = driver(hostname='192.168.124.130',username='cisco',password='ciscopass',optional_args=enpass)
device.open()

devshow = device.get_facts()
print(json.dumps(devshow, indent=3))

device.close()

json.dumps(devshow, indent=3) : informasi yang didapatkan dari fungsi get_facts() akan ditampilkan dalam format JSON.

$ python3 napalm-1.py

{
   "uptime": 3000,
   "vendor": "Cisco",
   "os_version": "Linux Software (I86BI_LINUXL2-ADVENTERPRISEK9-M), Version 15.2(CML_NIGHTLY_20150703)FLO_DSGS7, EARLY DEPLOYMENT DEVELOPMENT BUILD, synced to  DSGS_PI5_POSTCOLLAPSE_TEAM_TRACK_CLONE",
   "serial_number": "2048001",
   "model": "Unknown",
   "hostname": "S1",
   "fqdn": "S1.cisco.com",
   "interface_list": [
      "Ethernet0/0",
      "Ethernet0/0.10",
      "Ethernet0/1",
      "Ethernet0/2",
      "Ethernet0/3",
      "Ethernet1/0",
      "Ethernet1/1",
      "Ethernet1/2",
      "Ethernet1/3",
      "Ethernet2/0",
      "Ethernet2/1",
      "Ethernet2/2",
      "Ethernet2/3",
      "Ethernet3/0",
      "Ethernet3/1",
      "Ethernet3/2",
      "Ethernet3/3",
      "Vlan1"
   ]
}

Contoh 3 – ARP Table

from napalm import get_network_driver
import json

driver = get_network_driver('ios')
enpass = {'secret':'enablepass'}
device = driver(hostname='192.168.124.130',username='cisco',password='ciscopass',optional_args=enpass)
device.open()

devshow = device.get_arp_table()
print(json.dumps(devshow, indent=3))

device.close()

get_arp_table() : fungsi untuk mendapatkan ARP table.

$ python3 napalm-3.py

[
   {
      "interface": "Vlan1",
      "mac": "00:50:56:C0:00:08",
      "ip": "192.168.124.1",
      "age": 0.0
   },
   {
      "interface": "Vlan1",
      "mac": "00:50:56:F9:03:B8",
      "ip": "192.168.124.2",
      "age": 9.0
   },
   {
      "interface": "Vlan1",
      "mac": "AA:BB:CC:80:01:00",
      "ip": "192.168.124.130",
      "age": 0.0
   }
]

Contoh 4 – Mengkonfigurasi Banyak Perangkat

from napalm import get_network_driver
import json

hosts = ['192.168.124.130','192.168.124.131']

for host in hosts:
	driver = get_network_driver('ios')
	enpass = {'secret':'enablepass','port':'2222'}
	device = driver(hostname=host,username='cisco',password='ciscopass',optional_args=enpass)
	device.open()

	devshow = device.get_arp_table()
	print(json.dumps(devshow, indent=3))

device.close()

hosts : list untuk menampung IP host atau perangkat yang akan dikonfigurasi.

$ python3 napalm-4.py

[
   {
      "interface": "Vlan1",
      "mac": "00:50:56:C0:00:08",
      "ip": "192.168.124.1",
      "age": 8.0
   },
   {
      "interface": "Vlan1",
      "mac": "00:50:56:F9:03:B8",
      "ip": "192.168.124.2",
      "age": 0.0
   },
   {
      "interface": "Vlan1",
      "mac": "AA:BB:CC:80:01:00",
      "ip": "192.168.124.130",
      "age": 0.0
   },
   {
      "interface": "Vlan1",
      "mac": "AA:BB:CC:80:02:00",
      "ip": "192.168.124.131",
      "age": 41.0
   }
]
[
   {
      "interface": "Vlan1",
      "mac": "00:50:56:C0:00:08",
      "ip": "192.168.124.1",
      "age": 8.0
   },
   {
      "interface": "Vlan1",
      "mac": "00:50:56:F9:03:B8",
      "ip": "192.168.124.2",
      "age": 1.0
   },
   {
      "interface": "Vlan1",
      "mac": "AA:BB:CC:80:01:00",
      "ip": "192.168.124.130",
      "age": 41.0
   },
   {
      "interface": "Vlan1",
      "mac": "AA:BB:CC:80:02:00",
      "ip": "192.168.124.131",
      "age": 0.0
   }
]

Contoh 5 – Port SSH Dirubah

from napalm import get_network_driver
import json

hosts = ['192.168.124.130','192.168.124.131']

for host in hosts:
	driver = get_network_driver('ios')
	argumen = {'secret':'enablepass','port':2222}
	device = driver(hostname=host,username='cisco',password='ciscopass',optional_args=argumen)
	device.open()

	devshow = device.get_facts()

	hostname = devshow['hostname']
	uptime = devshow['uptime']

	print('host {} is up for {}'.format(hostname,uptime))

device.close()

‘port’:2222 : untuk menspesifikasikan port SSH.
hostname : variabel untuk mendapatkan informasi spesifik dari get_facts() yaitu hostname.
uptime : variabel untuk mendapatkan informasi spesifik dari get_facts() yaitu uptime.

$ python3 napalm-5.py

host S1 is up for 2700
host S2 is up for 2700

Contoh 6 – Backup Config

from napalm import get_network_driver

hostlist = ['192.168.124.148']

for host in hostlist:
    driver = get_network_driver('ios')
    other_args = {'secret':'cisco','port':22}
    device = driver(hostname=host, username='cisco', password='cisco', optional_args=other_args)
    device.open()

    # mendapatkan konfigurasi (all)
    device_config = device.get_config()

    # mendapatkan running config
    device_config_running = device_config['running']

    # mendapatkan startup config
    device_config_startup = device_config['startup']

    # mendapatkan candidate config
    device_config_candidate = device_config['candidate']

    # menuliskan running config ke file
    file = open('config_running_{}'.format(host), 'w')
    file.write(device_config_running)
    file.close()

    # menuliskan startup config ke file
    file = open('config_startup_{}'.format(host), 'w')
    file.write(device_config_startup)
    file.close()

device.close()

Pada contoh ini file konfigurasi akan disimpan dalam sebuah file. Pada kode di atas maka akan terdapat 2 file yaitu file running config dan startup config. Jika menggunakan Linux atau Mac, maka dapat menggunakan diff untuk melihat perbedaan dari 2 file tersebut.

$ diff config_startup_192.168.124.148 config_running_192.168.124.148

Contoh 7 – Load & Merge Config

from napalm import get_network_driver

driver = get_network_driver("ios")
others = {
			"secret" : "cisco",
			"dest_file_system" : "nvram:",
			'inline_transfer': True
			}
# device config
device = driver(hostname="192.168.124.150", username="cisco", password="cisco", optional_args=others)
device.open()

# load dan merge config dengan file 'candidate'
device.load_merge_candidate(filename="candidate")

# membandingkan config
compare = device.compare_config()
print(compare)

# melakukan commit untuk melakukan merge
device.commit_config()

device.close()

Isi file candidate seperti di bawah ini:

hostname Router

interface Loopback1
 ip address 10.10.10.1 255.255.255.0

interface Loopback2
 ip address 20.20.20.1 255.255.255.0

end

Jadi ketika melakukan merge, running config akan di-load terlebih dahulu. Kemudian dilakukan pembandingan antara running config dan file konfigurasi yang dibuat. Kemudian akan terlihat perbedaanya. Setelah itu baru dilakukan merge atau penggabungan konfigurasi. Keterangan baris kode dapat dilihat pada baris komentar.

compare_config() : melakukan pembandingan antara running config dan file konfigurasi yang dibuat. Jika terdapat tanda + maka disitulah letak perbedaannya.
load_merge_candidate() : akan load running config dan di-merge dengan file konfigurasi yang dibuat.
commit_config() : melakukan commit.

+hostname Router
+interface Loopback1
+ip address 10.10.10.1 255.255.255.0
+interface Loopback2
+ip address 20.20.20.1 255.255.255.0

Contoh 7 – Load & Merge Config Jika Ada Perubahan

from napalm import get_network_driver

driver = get_network_driver("ios")
others = {
			"secret" : "cisco",
			"dest_file_system" : "nvram:",
			'inline_transfer': True
			}
# device config
device = driver(hostname="192.168.124.150", username="cisco", password="cisco", optional_args=others)
device.open()

# load and merge config with file 'candidate'
device.load_merge_candidate(filename="candidate")

# compare config
compare = device.compare_config()

if len(compare) > 0:
	print(compare)
	
	if input("commit? (Y/n): ") == "n":
		# discard to commit
		device.discard_config()
		print("cancelled.")
	else:
		# commit to merge config
		device.commit_config()
		print("config has been merged successfully")
else:
	# discard to commit
	device.discard_config()
	print("config has no change.")

device.close()
hostname R2

interface Loopback1
 ip address 10.10.10.1 255.255.255.0

interface Loopback2
 ip address 20.20.20.1 255.255.255.0

end

Pada contoh ini, jika ada perubahan pada file maka kita akan dilakukan verifikasi untuk melakukan perubahan atau tidak. Pada contoh ini, terlihat ada perubahan dari hostname. Jika diinputkan karakter apa saja selain ‘n‘, maka perubahan atau penggabungan akan dilakukan.

+hostname R2
commit? (Y/n): 
config has been merged succesfully

Contoh 8 – Replace Config

from napalm import get_network_driver

driver = get_network_driver("ios")
others = {
			"secret" : "cisco",
			"dest_file_system" : "nvram:",
			'inline_transfer': True
			}
# device config
device = driver(hostname="192.168.124.150", username="cisco", password="cisco", optional_args=others)
device.open()

# load and replace config with file 'candidate'
device.load_replace_candidate(filename="candidate")

# compare
compare = device.compare_config()
print(compare)

device.commit_config()

device.close()
hostname Cisco

end

load_replace_candidate() : digunakan untuk mengganti konfigurasi yang berjalan dengan file konfigurasi baru.

+hostname Cisco
-service timestamps debug datetime msec
-service timestamps log datetime msec
-no service password-encryption
-hostname R2
-boot-start-marker
-boot-end-marker
.....

LANJUTKAN BACA MATERI LENGKAP


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.