22 Kasım 2018 Perşembe

Python Network Automation && GENİE , NETMİKO (Pycharm and vs code)

Pycharm ile python uygulamalarını rahatlıkla çalıştırabilirsiniz.
 
Ben vscode kullanıyorum . Bir cok yazılım dılı destekliyor.


Pycharm i widnows üzerinde çalıştırmak için 64 bit pyhton kurduktan sonra pyhton.exe'nin buluduğu path'i pycharm 'a ilk kuruluşta path göstererek çalıştırmak gerekiyor.

Daha sonra netmikoyu pyhton64 bit path içerisindeki script klasörü içeresinde cmd açarak pip komutları ile linux mus gibi uygulamaları kurabiliriz. platform bağımsız olarak.
not :C:\Users\Python\Scripts enviroment kısmına pyhton kurulu script yeri gösterilir.

direk username li

import getpass
import telnetlib
import ctypes

HOST = "192.168.1.2"

user='cisco'
#user = input("Enter your remote account: ")
password = 'cisco'
#password = getpass.getpass()
tn = telnetlib.Telnet(HOST)

tn.read_until(b"Username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
    tn.read_until(b"Password: ")
    tn.write(b"cisco\n")
tn.write(b"en\n")
tn.write(b"conf t\n")
tn.write(b"hostname EP1-YSHA-1-R-1\n")
tn.write(b"enable secret 5 $1$KgHj$.giJ6nu0CzWmlpxwrGEX01\n")
tn.write(b"ip domain name tai.local\n")
tn.write(b"ip multicast-routing\n")
tn.write(b"ip multicast-routing distributed\n")
tn.write(b"username R1220 secret Ta14551748\n")
tn.write(b"redundancy\n")
tn.write(b"mode none\n")
tn.write(b"archive\n")
tn.write(b"log config\n")
tn.write(b"logging enable\n")
tn.write(b"notify syslog contenttype plaintext\n")
tn.write(b"hidekeys\n")
tn.write(b"path tftp://10.111.200.150/YSHA-R1\n+ time-period 1440\n")
tn.write(b"track 1 interface Port-channel2 line-protocol\n" + b"track 2 interface Port-channel1 line-protocol\n")


tn.write(b"interface port-channel1\n" + b"description EP1-YSHA-1-EA\n" + b"ip address 10.111.200.202 255.255.255.0\n" + b"ip nat inside\n" + b"ip pim redundancy YSHA hsrp dr-priority 20\n" +  b"ip pim sparse-mode\n" +  b"standby 1 ip 10.111.200.201\n"+ b"standby 1 priority 200\n" + b"standby 1 preempt\n"+ b"standby 1 name YSHA\n" + b"standby 1 track 1 shutdown\n"+ b"negotiation auto\n")


tn.write(b" shut\n")
tn.write(b"exit\n")
tn.write(b"exit\n")
tn.write(b"exit\n")

print(tn.read_all().decode('ascii'))

ctypes.windll.user32.MessageBoxW(0, "YSHA ROUTER KONFIG OK !", "TAFICS DUZELDIGINDE", 1)


Python script exe haline getirme

yada
pip install pyinstaller
Python klasörü icinde cmd acılır dist klasörü altına atıyor.
python -m PyInstaller --onefile C:/Users/Administrator/Desktop/NetworkScript.py

Python yazı cıkarma 

you could use an import and single line code like this:

import ctypes  # An included library with Python install.   
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)

Or define a function (Mbox) like so:

import ctypes  # An included library with Python install.
def Mbox(title, text, style):
    return ctypes.windll.user32.MessageBoxW(0, text, title, style)
Mbox('Your title', 'Your text', 1)

Note the styles are as follows:

##  Styles:
##  0 : OK
##  1 : OK | Cancel
##  2 : Abort | Retry | Ignore
##  3 : Yes | No | Cancel
##  4 : Yes | No
##  5 : Retry | No 
##  6 : Cancel | Try Again | Continue

GENİE

python3 eski.py

setxkbmap

apt-get install open-vm-tools-desktop  
sudo apt-get install open-vm-tools-desktop
python3 -V
sudo apt install python3-pip

pip3 install pyats[library]
Or run this if pyats is already install in your environment:
pip3 install genie


LEARN

https://github.com/IPvZero/IPvZero/tree/master/Intro-To-Genie-Video

genie learn ospf --testbed-file testbed.yaml --output ospf-new
genie learn ospf --testbed-file testbed.yaml --output ospf-new3

genie learn acl --testbed-file testbed.yaml --output acl-new1



root@ali-virtual-machine:/home/ali/Genie# genie --help
Usage:
  genie <command> [options]

Commands:
    create              Create Testbed, parser, triggers, ...
    diff                Command to diff two snapshots saved to file or directory
    dnac                Command to learn DNAC features and save to file (Prototype)
    learn               Command to learn device features and save to file
    parse               Command to parse show commands
    run                 Run Genie triggers & verifications in pyATS runtime environment
    shell               enter Python shell, loading a pyATS testbed file and/or pickled data

General Options:
  -h, --help            Show help


PYTHON


pyats run job eski.py

python3 eski.py

test yaml


SHELL

istediğin cihaza gonderebilirsin.

genie shell --testbed-file testbed.yaml

>>> from genie.testbed import load
>>> testbed = load('testbed.yaml')

>>> testbed.devices

>>> testbed.devices['R1'].connect()


DNAC

 genie dnac interface --testbed-file testbed.yaml --output snapshot1

---
testbed:

  credentials:
    default:
      username: "john"
      password: "cisco"

devices:
  R1:
    alias: R1
    os: ios
    type: IOSv
    connections:

      defaults:
        class: unicon.Unicon
      console:
        protocol: ssh
        ip: 192.168.31.11

    custom:
      abstration:
         order: [os, type]

----
 
  
 DIFF 
genie diff ospf-new1/ ospf-new4/

PARSE

https://pubhub.devnetcloud.com/media/genie-feature-browser/docs/#/parsers

genie parse "show bgp summary" --testbed-file testbed.yaml --output bgp1

NETMİKO

from netmiko import Netmiko

cisco1 = {
    "host": "192.168.44.100",
    "port": 22,
    "username": "cisco",
    "password": "cisco",
    "device_type": "cisco_ios",
}

net_connect = Netmiko(**cisco1)

commands = ["conf t"]
commands = ["hostname P1"]
output = net_connect.send_config_set(commands)

yerine
output = net_connect.send_command('show ip int bri')

net_connect.disconnect()
print(output)

-------

commands = ["conf t"]
commands = ["hostname P1"]

yerine virgül konulabilir.

commands = ["conf t", "hostname S1"]

veya 

output = net_connect.send_command('show ip int bri')

----
from datetime import datetime
from netmiko import ConnectHandler
from getpass import getpass

host = input("Enter your hostname: ")
device = { 
    'device_type': 'cisco_ios',
    'host': host,
    'username': 'pyclass',
    'password': getpass(),
    'global_delay_factor': 2,

start_time = datetime.now()
net_connect = ConnectHandler(device)
cmd = 'copy flash:/c880data-universalk9-mz.154-2.T1.bin flash:/test1.bin'
output = net_connect.send_command(
    cmd, 
    expect_string=r'Destination filename'
)
output += net_connect.send_command('\n', expect_string=r'#')
end_time = datetime.now()
 
print("\n")
print("#" * 60) 
print(output)
print("#" * 60) 
print("\n")
print("Total time: {}".format(end_time - start_time))
print("\n")     

------
yedek alma

from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from paramiko.ssh_exception import SSHException
from netmiko.ssh_exception import AuthenticationException
import time

with open('device_ip_list.txt') as f:
device_list = f.read().splitlines()

for devices in device_list:

ip_address = devices
firewall = {
'device_type': 'fortinet',
'ip': ip_address,
'username': 'R1220',
'password': 'Ta14551748',
}

timestr = time.strftime("%Y%m%d")

try:
net_connect = ConnectHandler(**firewall)
except (AuthenticationException):
continue
except (NetMikoTimeoutException):
continue
except (EOFError):
continue
except (SSHException):
continue
except Exception as unknown_error:
continue

output = net_connect.send_command("show full-configuration", delay_factor=2)

backup_path = 'C:/Users/Administrator/Desktop/Projeler/erdem abi script/%s' % (firewall['ip'])

filename = backup_path + str("_backupfile_"+ timestr)
f = open(filename, 'w+')
f.write(output)
f.close()

net_connect.disconnect()

from netmiko import ConnectHandler
from colorama import init, Fore, Back, Style
import threading
import time
import socket
import binascii
import zlib
from tkinter import *
import json
import os

with open('../../../Desktop/IP_LIST_Router.txt') as IP_file_router:
IP_Router = IP_file_router.read().splitlines()

with open('../../../Desktop/IP_LIST_Firewall.txt') as IP_file_firewall:
IP_FW = IP_file_firewall.read().splitlines()

x = 0
y = 0
cisco1 = {
"device_type": "cisco_ios",
"host": IP_Router[x],
"port": 22,
"username": "R1220",
"password": "Ta14551748",
"secret": "Ta14551748"
}
cisco2= {
'device_type': 'cisco_asa',
"host": IP_FW[y],
"port": 22,
"username": "R1220",
"password": "Ta14551748",
"secret": "Ta14551748",
"verbose":False,
}
###### ROUTER#######
while x <= 1 :
net_connect = ConnectHandler(**cisco1)
net_connect.enable()
commands = ["conf t","ip pim rp-address 11.11.11.11","exit",]
output = net_connect.send_config_set(commands)
try:
show_run = net_connect.send_command('show run')
result = re.findall(r"ip rp-address 11.11.11.11", str(show_run))
if result[0] == 'ip rp-address 11.11.11.11':
print('OK', IP_Router[x])
else:
print('HATA', IP_Router[x])
except Exception as e:
print(e)
x = x+1
###### FİREWALL#######
while y <= 0:
net_connect = ConnectHandler(**cisco2)
net_connect.enable()
commands = ["conf t","pim rp-address 11.11.11.11","exit",]
output = net_connect.send_config_set(commands)
try:
show_run = net_connect.send_command('show run')
result = re.findall(r"rp-address 11.11.11.11", str(show_run))
if result[0] == 'rp-address 11.11.11.11':
print('OK', IP_FW[y])
else:
print('HATA', IP_FW[y] )
except Exception as e:
print(e)
y= y+1
###YSHA ROUTER 1 ELAZIG####
cisco3 = {
"device_type": "cisco_ios",
"host": '10.112.1.52' ,
"port": 22 ,
"username": "R1220",
"password": "Ta14551748",
"secret": "Ta14551748"
}
net_connect = ConnectHandler(**cisco3)
net_connect.enable()
commands = ["conf t","interface loopback 0","ip address 11.11.11.11 255.255.255.255","interface tunnel 20",
"ip address 20.20.20.2 255.255.255.0","tunnel source 98.8.14.51","tunnel destination 128.153.12.51",
"ip pim sparse-mode","router ospf 1","network 11.11.11.11 0.0.0.0 area 0",
"ip msdp peer 1.1.1.1 connect-source Loopback 0","ip msdp originator-id Loopback 0","router ospf 1",
"no network 1.1.1.1 0.0.0.0 area 0","network 11.11.11.11 0.0.0.0 area 0","redistribute static",
"ip route 10.0.0.0 255.192.0.0 20.20.20.1","ip route 1.1.1.1 255.255.255.255 20.20.20.1","do wr\n",
]
output = net_connect.send_config_set(commands)
try:
show_run = net_connect.send_command('show run')
result = re.findall(r"ip msdp peer 11.11.11.11", str(show_run))
if result[0] == 'ip msdp peer 11.11.11.11':
print('OK ANA YSHA ROUTER 1 10.112.1.52')
else:
print('HATA ANA YSHA ROUTER 1 10.112.1.52')
except Exception as e:
print(e)

###YSHA ROUTER 2 ELAZIG####
cisco4 = {
"device_type": "cisco_ios",
"host": '10.112.1.53',
"port": 22,
"username": "R1220",
"password": "Ta14551748",
"secret": "Ta14551748"
}
net_connect = ConnectHandler(**cisco4)
net_connect.enable()
commands = ["conf t", "interface loopback 0", "ip address 11.11.11.11 255.255.255.255", "interface tunnel 20",
"ip address 20.20.20.2 255.255.255.0", "tunnel source 98.8.14.51", "tunnel destination 128.153.12.51",
"ip pim sparse-mode", "router ospf 1", "network 11.11.11.11 0.0.0.0 area 0",
"ip msdp peer 1.1.1.1 connect-source Loopback 0", "ip msdp originator-id Loopback 0", "router ospf 1",
"no network 1.1.1.1 0.0.0.0 area 0", "network 11.11.11.11 0.0.0.0 area 0", "redistribute static",
"ip route 10.0.0.0 255.192.0.0 20.20.20.1", "ip route 1.1.1.1 255.255.255.255 20.20.20.1", "do wr\n",
]
output = net_connect.send_config_set(commands)
try:
show_run = net_connect.send_command('show run')
result = re.findall(r"ip msdp peer 11.11.11.11", str(show_run))
if result[0] == 'ip msdp peer 11.11.11.11':
print('OK ANA YSHA ROUTER 2 10.112.1.53')
else:
print('HATA ANA YSHA ROUTER 2 10.112.1.53')
except Exception as e:
print(e)

from netmiko import ConnectHandler

cisco_881 = {
    'device_type': 'cisco_ios',
    'host':   '10.10.10.10',
    'username': 'test',
    'password': 'password',
    'port' : 8022,          # optional, defaults to 22
    'secret': 'secret',     # optional, defaults to ''
}

Establish an SSH connection to the device by passing in the device dictionary.

net_connect = ConnectHandler(**cisco_881)

Execute show commands.

output = net_connect.send_command('show ip int brief')
print(output)
Interface                  IP-Address      OK? Method Status                Protocol
FastEthernet0              unassigned      YES unset  down                  down
FastEthernet1              unassigned      YES unset  down                  down
FastEthernet2              unassigned      YES unset  down                  down
FastEthernet3              unassigned      YES unset  down                  down
FastEthernet4              10.10.10.10     YES manual up                    up
Vlan1                      unassigned      YES unset  down                  down

Execute configuration change commands (will automatically enter into config mode)

config_commands = [ 'logging buffered 20000',
                    'logging buffered 20010',
                    'no logging console' ]
output = net_connect.send_config_set(config_commands)
print(output)
pynet-rtr1#config term
Enter configuration commands, one per line.  End with CNTL/Z.
pynet-rtr1(config)#logging buffered 20000
pynet-rtr1(config)#logging buffered 20010
pynet-rtr1(config)#no logging console
pynet-rtr1(config)#end
pynet-rtr1#




Hiç yorum yok:

Yorum Gönder