9 Mart 2023 Perşembe

Dhcp 2

 address 25.0.0.5 client-id "Fa1/0/5" ascii


ip dhcp use subscriber-id client-id

ip dhcp subscriber-id interface-name

IP dhcp pool VLAN2

network 25.0.0.0 255.255.255.0

address 25.0.0.1 client-id "Fa1/0/0" ascii

address 25.0.0.2 client-id "Fa1/0/1" ascii

interface FastEthernet 1/0/1

switchport access vlan 2

switchport mode access

ip dhcp server use subscriber-id client-id

spanning-tree portfast

7 Aralık 2020 Pazartesi

PYHTON KODLARI LDAP , NETWORK OTOMASYON YEDEK ALMA , WOWZA CODE

LDAP KULLANICI CEKME

import sys
 
from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, AUTO_BIND_NO_TLS, SUBTREE
from ldap3.core.exceptions import LDAPCursorError


server = Server('192.168.1.2',get_info=ALL)
conn = Connection(server, user='XXX\\Administrator'password='Ta14551748'authentication=NTLM)
conn.bind()
fusers = ['Administrator','test','deneme','deneme1','bindu','MA977956''MA625841','gopal','govind','MA177397','MA259156']
status = ''


format_string = '{:25} {:21} '
print(format_string.format('User ID''Account Status'))


conn.search('cn=Users,dc=XXX,dc=local','(objectclass=person)',attributes=['sAMAccountName'])

for x in fusers:
    for e in conn.entries:
        if x in e.sAMAccountName:
            # status = 'active' +"\t\t\t\t"
            status = 'active'
            break
        else:
            status = "Not Active"
    print(format_string.format(str(x),str(status)))


Wowza URL Takip 


Stream ve Address txt dosyası olmalı.


C:\Program Files (x86)\Wowza Media Systems\Wowza Streaming Engine 4.7.3\conf server.xml dosyasinda ;

<RESTInterface> altinda

<IPWhiteList>*</IPWhiteList> yapilir.


import tkinter

import queue

from tkinter import *

import json

import requests

from requests.auth import HTTPDigestAuth

import time

import threading

import os



starting = 0  #başlangıç durumu kontrol için kullanılmaktadır.



desired_run_condition = "mini"

#desired_run_condition = "full"



username = "admin"

password = "admin"



cluster_ip = "localhost"



headers = {

    "Accept":"application/json",

    "Content-Type":"application/json",

    "charset":"utf-8"

}



record_payload = {"instanceName""_definst_",

                   "fileVersionDelegateName""",

                   "serverName""",

                   "recorderName""",

                   "currentSize"0,

                   "segmentSchedule""",

                   "startOnKeyFrame"True,

                   "outputPath""",

                   "currentFile""",

                   "saveFieldList": [

                       ""

                   ],

                   "recordData"False,

                   "applicationName""",

                   "moveFirstVideoFrameToZero"False,

                   "recorderErrorString""",

                   "segmentSize"0,

                   "defaultRecorder"False,

                   "splitOnTcDiscontinuity"False,

                   "version""",

                   "baseFile""",

                   "segmentDuration"0,

                   "recordingStartTime""",

                   "fileTemplate""",

                   "backBufferTime"0,

                   "segmentationType""",

                   "currentDuration"0,

                   "fileFormat""",

                   "recorderState""",

                   "option"""

                   }



stream_payload = {

   "name""",

   "serverName""_defaultServer_",

   "uri"""

}





url_get_stream = 'http://' + cluster_ip + ':8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/live/streamfiles'

url_get_record = 'http://' + cluster_ip + ':8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/live/instances/_definst_/streamrecorders'



if os.path.exists("WoW_log.txt"):

    os.remove("WoW_log.txt")



recording_list = [""]

break_val = 0



with open("Stream.txt""r"as stream:

    stream_name = stream.read().split()



stream_list = stream_name

record = [""] * len(stream_list)

for z in range(len(stream_list)):

    record[z] = stream_list[z] + ".stream"

record.sort()



with open("Address.txt""r"as address:

    address_name = address.read().split()



def logging(log_text):

    time_info = time.asctime(time.localtime(time.time()))

    with open("WoW_log.txt""a+"as file_log:

        file_log.write(time_info + "  ->  " + "  ->  " + log_text + "\n")



print("---------------------------------%Starting%-----------------------------------------------")

#logging("---------------------------------%Starting%-----------------------------------------------")



print("stream_list=     ", stream_list)

#logging("stream_list=" + str(stream_list))

print("record           ", record)

#logging("record=" + str(record))



stream_uri = address_name

print("stream_uri=      ", stream_uri)

#logging("stream_uri=" + str(stream_uri))

url_stream = []



color_stream = ["red"] * len(stream_list)

#color_record = ["red"] * len(stream_list)

addStream = [Button] * len(stream_list)

#addRecord = [Button] * len(stream_list)





class StreamPart:

    def __init__(self):

        self.s = requests.get(url_get_stream, auth=HTTPDigestAuth(username, password), headers=headers, timeout=10)

        self.s_json = self.s.json()

        self.r = requests.get(url_get_record, auth=HTTPDigestAuth(username, password), headers=headers, timeout=10)

        self.r_json = self.r.json()

        #print(json.dumps(self.r_json, indent=2))

        print(self.s.status_code)

        print(self.r.status_code)

        print(json.dumps(self.r_json, indent=4))



    def check_streaming(self):

        global root

        global frame_1

        global frame_2

        global color_stream

        #global color_record

        global stream

        #global s_json

        global stream_payload

        global record_payload

        stream_OK = []

        try:

            #for y in range(len(stream_list)):

            yt = len(self.s_json["streamFiles"])

            yt_value = yt

            if yt == 0:

                 yt_value = len(stream_list)

            for y in range(yt_value):

                for z in range(len(stream_list)):

                    stream_payload["name"] = stream_list[z]

                    stream_payload["uri"] = stream_uri[z]

                    if self.s_json["streamFiles"][y]["id"] == stream_list[z]:

                        print("\"{stream_name}.stream\" is OK".format(stream_name=stream_list[z]))

                        #logging("\"{stream_name}.stream\" is OK".format(stream_name=stream_list[z]))

                        self.connect_stream(stream_list[z], z)

                        stream_OK.append(stream_list[z])

                        #print("stream_OK=", stream_OK)

                    try:

                        aaa = stream_OK.index(stream_list[z])

                        #print("aaa=", aaa)

                    except:

                        aaa = ""

                        #print("aaa=", aaa)



                    if self.s_json["streamFiles"][y]["id"] != stream_list[z] and aaa == "":

                        #print("Streaming has just stopped for", "\"", stream_list[z], ".stream", "\""". Trying to start streaming again...")

                        #print("stream_payload=", stream_payload)

                        s = requests.post(url_get_stream, auth=HTTPDigestAuth(username, password), data=json.dumps(stream_payload),

                                          headers=headers, timeout=10)

                        self.connect_stream(stream_list[z], z)

            self.tkinter_GUI()



        except:

            for y in range(len(stream_list)):

                stream_payload["name"] = stream_list[y]

                stream_payload["uri"] = stream_uri[y]

                print("Stream has just stopped for""\"", stream_list[y], ".stream""\""". Trying to start streaming again...(except)")

                print("url_get_stream= ", url_get_stream)

                print("stream_payload=", stream_payload)

                s = requests.post(url_get_stream, auth=HTTPDigestAuth(username, password), data=json.dumps(stream_payload),

                                  headers=headers, timeout=10)

                print(s)

                print("Code:", s.status_code)

                if s.status_code == 200:

                    print("Stream created...(except)")

                    self.connect_stream(self, stream_list[z], z)

                else:

                    print("problem...(except)")

                    color_stream[y] = "red"

                self.tkinter_GUI()

        return



    def connect_stream(selfstream_list_valval_index):

        global stream

        global stream_payload

        global record_payload

        global color_stream

        #global color_record

        try:

            uri_connect = "http://" + cluster_ip + ":8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/live/streamfiles/"str(stream_list_val) + "/actions/connect?connectAppName=live&appInstance=_definst_&mediaCasterType=rtp"

            #print("Connect for", "\"", stream_list_val, ".stream")

            #print("uri_connect=", uri_connect)

            c = requests.put(uri_connect, auth=HTTPDigestAuth(username, password), headers=headers, timeout=10)

            #print("Code:", c.status_code)

            if c.status_code == 200:

                #print("Stream created for {stream_list_val_val}".format(stream_list_val_val=stream_list_val))

                color_stream[val_index] = "yellow"

            else:

                print("problem")

                #logging("problem")

                color_stream[val_index] = "red"

            #self.tkinter_GUI()



        except:

            uri_connect = "http://" + cluster_ip + ":8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/live/streamfiles/" + str(

                stream_list[y]) + "/actions/connect?connectAppName=live&appInstance=_definst_&mediaCasterType=rtp"

            #print ("Connect for", "\"", stream_list_val, ".stream")

            c = requests.put(uri_connect, auth=HTTPDigestAuth(username, password), headers=headers, timeout=10)

            #print("Code:", c.status_code)

            if c.status_code == 200:

                print("Stream created...")

            else:

                print("problem")

            self.tkinter_GUI(self)

        return



    def tkinter_GUI(self):

        global th_timer

        global root

        global frame_1

        global frame_2

        global color_stream

        #global color_record

        global stream_list

        #global s_json

        global stream_payload

        global record_payload

        #global addRecord

        global addStream

        #print("color_stream=", color_stream, "color_record=", color_record)

        try:

            for z in range(len(stream_list)):

                addStream[z].configure(bg=color_stream[z], command=threading.Thread().start())

                #addRecord[z].configure(bg=color_record[z], command=threading.Thread().start())

                #print("color_stream[{z_value}]=".format(z_value=z), color_stream[z])

                #print("color_record[{z_value}]=".format(z_value=z), color_record[z])

        except:

            ...

        return



    def check_recording(self):

        global root

        global frame_1

        global frame_2

        global color_stream

        #global color_record

        global url_stream

        global record

        #global r_json

        global stream_payload

        global record_payload

        global break_val



        try:

            recording_list = [""] * len(self.r_json["streamrecorder"])

            for it in range(len(self.r_json["streamrecorder"])):

                recording_list[it] = self.r_json["streamrecorder"][it]["recorderName"]

        except:

            recording_list = []



        recording_list.sort()

        print(recording_list)



        deletions = [x for x in record if x not in recording_list]

        deletions.sort()



        existing = [x for x in record if x not in deletions]

        existing.sort()



        try:

            # print(len(r_json["streamrecorder"]))

            record_waiting = []

            for y in range(len(self.r_json["streamrecorder"])):

                if self.r_json["streamrecorder"][y]["recorderState"] != "Recording in Progress":

                    # print(r_json["streamrecorder"][y]["recorderName"])

                    record_waiting.append(self.r_json["streamrecorder"][y]["recorderName"])

        except:

            print("...")



        existing_and_recorded = [x for x in existing if x not in record_waiting]

        existing_and_recorded.sort()



        # print("record=              ", record)

        # print("recording_list=      ", recording_list)

        print("deletions=                       ", deletions)

        #logging("deletions=" + str(deletions))

        print("record_waiting=                  ", record_waiting)

        #logging("record_waiting=" + str(record_waiting))

        print("existing=                        ", existing)

        #logging("existing=" + str(existing))

        print("existing_and_recorded=           ", existing_and_recorded)

        #logging("existing_and_recorded=" + str(existing_and_recorded))



        for z in range(len(deletions)):

            print("----------------Deletions----------------------------")

            record_payload["recorderName"] = deletions[z]

            url_start_record = 'http://' + cluster_ip + ':8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/live/instances/_definst_/streamrecorders/' + str(

                deletions[z])

            r = requests.post(url_start_record, auth=HTTPDigestAuth(username, password),

                              data=json.dumps(record_payload),

                              headers=headers, timeout=10)

            print("Code:", r.status_code, "recorderName=", deletions[z], url_start_record)

            #logging("Code:" + str(r.status_code) + "recorderName=" + str(deletions[z]) + str(url_start_record))



        #for i in range(len(record)):

        #    color_record[i] = "red"

        for i in record:

            for k in existing_and_recorded:

                if i == k:

                    #color_record[record.index(i)] = "green"

                    color_stream[record.index(i)] = "green"

                else:

                    ...

            for b in record_waiting:

                if i == b:

                    #color_record[record.index(i)] = "yellow"

                    color_stream[record.index(i)] = "blue"

                else:

                    ...

        # print("color_record=", color_record)

        self.tkinter_GUI()

        return



    def check_recording_mini(self):

        global root

        global frame_1

        global frame_2

        global color_stream

        #global color_record

        global url_stream

        global record

        #global r_json

        global stream_payload

        global record_payload

        global break_val



        try:

            recording_list = [""] * len(self.r_json["streamrecorder"])

            for it in range(len(self.r_json["streamrecorder"])):

                recording_list[it] = self.r_json["streamrecorder"][it]["recorderName"]

        except:

            recording_list = []



        recording_list.sort()

        #print(recording_list)



        deletions = [x for x in record if x not in recording_list]

        deletions.sort()



        existing = [x for x in record if x not in deletions]

        existing.sort()



        try:

            # print(len(r_json["streamrecorder"]))

            record_waiting = []

            for y in range(len(self.r_json["streamrecorder"])):

                if self.r_json["streamrecorder"][y]["recorderState"] != "Recording in Progress":

                    # print(r_json["streamrecorder"][y]["recorderName"])

                    record_waiting.append(self.r_json["streamrecorder"][y]["recorderName"])

        except:

            print("...")



        existing_and_recorded = [x for x in existing if x not in record_waiting]

        existing_and_recorded.sort()



        # print("record=              ", record)

        # print("recording_list=      ", recording_list)

        print("deletions=                       ", deletions)

        #logging("deletions=" + str(deletions))

        print("record_waiting=                  ", record_waiting)

        #logging("record_waiting=" + str(record_waiting))

        print("existing=                        ", existing)

        #logging("existing=" + str(existing))

        print("existing_and_recorded=           ", existing_and_recorded)

        #logging("existing_and_recorded=" + str(existing_and_recorded))



        #for i in range(len(record)):

        #    color_record[i] = "red"

        for i in record:

            for k in existing_and_recorded:

                if i == k:

                    #color_record[record.index(i)] = "green"

                    color_stream[record.index(i)] = "green"

                else:

                    ...

            for b in record_waiting:

                if i == b:

                    #color_record[record.index(i)] = "yellow"

                    color_stream[record.index(i)] = "blue"

                else:

                    ...

            for kb in deletions:

                if i == kb:

                    #color_record[record.index(i)] = "green"

                    color_stream[record.index(i)] = "red"

                else:

                    ...

        # print("color_record=", color_record)

        self.tkinter_GUI()

        return





class GuiPart:

    def __init__(selfmasterqueueendCommand):

        self.queue = queue

        # Set up the GUI

        if desired_run_condition == "full":

            frame_1 = LabelFrame(root, text="Red= Not Connected, Yellow= Just Connected, Blue= Connected and Waiting, Green= Recording"width=100height=1padx=1pady=1,

                                 command=threading.Thread().start())

            frame_1.grid(row=0column=0columnspan=3)

        if desired_run_condition == "mini":

            frame_1 = LabelFrame(root, text="Red= Not Connected, Blue= Connected and Waiting, Green= Recording"width=100height=1padx=1pady=1,

                                 command=threading.Thread().start())

            frame_1.grid(row=0column=0columnspan=3)

        #frame_2 = LabelFrame(root, text="Record-> Green = Recording, Red = Not Recording, Yellow = Waiting for Stream", width=100, height=1, padx=1, pady=1,

        #                     command=threading.Thread().start())

        #frame_2.grid(row=1, column=0, columnspan=3)

        for z in range(len(stream_list)):

            addStream[z] = Button(frame_1, bg=color_stream[z], text=stream_list[z], padx=40pady=20width=15height=1,

                                  command=threading.Thread().start())

            addStream[z].grid(row=0column=0 + z)

            #addRecord[z] = Button(frame_2, bg=color_record[z], text=stream_list[z], padx=40, pady=20, width=10, height=1,

            #                      command=threading.Thread().start())

            #addRecord[z].grid(row=0, column=0 + z)

        # Add more GUI stuff here depending on your specific needs



    def processIncoming(self):

        """Handle all messages currently in the queue, if any."""

        while self.queue.qsize(  ):

            try:

                msg = self.queue.get(0)

                # Check contents of message and do whatever is needed. As a

                # simple test, print it (in real life, you would

                # suitably update the GUI's display in a richer fashion).

                #print(msg)

            except queue.Empty:

                # just on general principles, although we don't

                # expect this branch to be taken in this case

                pass



class ThreadedClient:

    """

    Launch the main part of the GUI and the worker thread. periodicCall and

    endApplication could reside in the GUI part, but putting them here

    means that you have all the thread controls in a single place.

    """

    def __init__(selfmaster):

        """

        Start the GUI and the asynchronous threads. We are in the main

        (original) thread of the application, which will later be used by

        the GUI as well. We spawn a new thread for the worker (I/O).

        """

        self.master = master



        # Create the queue

        self.queue = queue.Queue(  )



        # Set up the GUI part

        self.gui = GuiPart(master, self.queue, self.endApplication)



        # Set up the thread to do asynchronous I/O

        # More threads can also be created and used, if necessary

        self.running = 1

        self.thread1 = threading.Thread(target=self.workerThread1)

        self.thread1.start(  )



        # Start the periodic call in the GUI to check if the queue contains

        # anything

        self.periodicCall(  )



    def periodicCall(self):

        """

        Check every 200 ms if there is something new in the queue.

        """

        #self.gui.processIncoming(  )

        if not self.running:

            # This is the brutal stop of the system. You may want to do

            # some cleanup before actually shutting it down.

            import sys

            sys.exit(1)

        self.master.after(200self.periodicCall)



    def workerThread1(self):

        """

        This is where we handle the asynchronous I/O. For example, it may be

        a 'select(  )'. One important thing to remember is that the thread has

        to yield control pretty regularly, by select or otherwise.

        """

        global starting

        while self.running:

            S1 = StreamPart()

            if desired_run_condition =="full":

                if starting < 2:

                    S1.check_streaming()

                else:

                    if starting - 10 == 0:

                        starting = 0

                starting += 1

                S1.check_recording()

            if desired_run_condition == "mini":

                S1.check_recording_mini()





    def endApplication(self):

        self.running = 0



#rand = random.Random(  )

root = tkinter.Tk(  )



client = ThreadedClient(root)

root.mainloop(  )



NETWORK OTOMASYON

1- Temel
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)


2-Cisco Konfig

import string
# from dotevn import load_dotenv
from netmiko import ConnectHandler
from colorama import init, Fore, Back, Style
import pickle
import threading
import json
import re
#import xmltodict
import time
import socket
from tkinter import *
#rom PIL import ImageTk, Image
import sqlite3
# import xlrd
import glob
import os
from string import punctuation, digits

cisco3 = {
    "device_type""cisco_ios",
    "host""10.112.1.51" ,
    "port"22 ,
    "username""R1220",
    "password""Ta14551748",
    "secret""Ta14551748"
}
net_connect2 = ConnectHandler(**cisco3)
net_connect2.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_connect2.send_config_set(commands)
try:
    show_run = net_connect2.send_command('show run')
    result = re.findall(r"ip msdp peer 1.1.1.1"str(show_run))
    if result[0] == 'ip msdp peer 1.1.1.1':
        print('OK ANA YSHA ROUTER 10.112.1.52')
    else:
        print('HATA ANA YSHA ROUTER 10.112.1.52')
except Exception as e:
    print(e)

Network  YEDEK ALMA

https://networksareawesome.com/python-for-network-engineers/python-script-library/fortinet-python-library/fortigate-configuration-backup/

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()


NETWORK İZLEME 
İPleri Router.txt ve Switch.txt'den alıyor.

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

init(autoreset=True)

success_message = "#"
fail_message = "!"
access_fail_message = "?"

tafics_failure = 0
tafics_failure_count = 3  # TAFICS hatası sayma

cpu_max = 20  # maximum CPU oranı

with open("../../../Desktop/pyhton_projeleri/pycurl/IP_LIST_Router.txt""r"as Router_Count:
    Router_Count_Info = Router_Count.read()
    Router_Count_Info_List = Router_Count_Info.splitlines()
    print("Total Number of Router: {count}, Router IP: {IP}".format(count=len(Router_Count_Info_List), IP= Router_Count_Info_List))
    numberOfRouterDevice = 2  # YSHA Router Toplam Sayısı

with open("../../../Desktop/pyhton_projeleri/pycurl/IP_LIST_Switch.txt""r"as Switch_Count:
    Switch_Count_Info = Switch_Count.read()
    Switch_Count_Info_List = Switch_Count_Info.splitlines()
    print("Total Number of Switch: {count}, Switch IP: {IP}".format(count = len(Switch_Count_Info_List), IP = Switch_Count_Info_List))
    numberOfSwitchDevice = 1  # YSHA Switch Toplam Sayısı

numberOFRouterDataToSend = 64   # YSHA Router başına ölçüm yapılacak bilgi sayısı
numberOFSwitchDataToSend = 64   # YSHA Switch başına ölçüm yapılacak bilgi sayısı

# Gönderilecek veri için dizin oluşturulması
a, b = numberOFRouterDataToSend, numberOfRouterDevice
data = [["0" for x in range(a)] for y in range(b)]
data1 = ["0"] * (a * b)


# Interface hata durum değişkenleri
router_1_gigabitetnernet10_interface_problem = 1
router_1_gigabitetnernet20_interface_problem = 1
router_2_gigabitetnernet10_interface_problem = 1
router_2_gigabitetnernet20_interface_problem = 1

bit_number = 0
check_first_time = 0
a = 0

if os.path.exists("../../../Desktop/pyhton_projeleri/pycurl/b_len.txt"):
    os.remove("../../../Desktop/pyhton_projeleri/pycurl/b_len.txt")

if os.path.exists("../../../Desktop/pyhton_projeleri/pycurl/NKY_log.txt"):
    os.remove("../../../Desktop/pyhton_projeleri/pycurl/NKY_log.txt")



# %%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router Setting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router IP Setting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
with open('../../../Desktop/pyhton_projeleri/pycurl/IP_LIST_Router.txt'as IP_file_router:
    IP_lines_router = IP_file_router.read().splitlines()

router = [""] * len(IP_lines_router)
IP_lines_router_index = 0
for IP in IP_lines_router:
    router[IP_lines_router_index] = {
        'device_type''cisco_ios',
        'ip': IP,
        'username''cisco',
        'password''cisco',
        'secret''cisco'
    }
    IP_lines_router_index += 1

# %%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router ID Setting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
with open('../../../Desktop/pyhton_projeleri/pycurl/ID_LIST_Router.txt'as ID_file_router:
    ID_lines_router = ID_file_router.read().splitlines()

router_id = [""] * len(ID_lines_router)
ID_lines_router_index = 0
for x in range(len(ID_lines_router)):
    router_id[x] = ID_lines_router[x]


# %%%%%%%%%%%%%%%%%%%%%%%%% Data Send Socket Set %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
try:
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    ip = "5.5.5.5"
    port = 11111
except Exception as e:
    logging("UDP Socket Fail"1# "0" is INFO, "1" is WARNING"

def logging(log_textWCA):
    time_info = time.asctime(time.localtime(time.time()))
    if WCA == 0#INFO
        WCA_text = "INFO   "
    if WCA == 1#FAIL
        WCA_text = "FAILURE"
    if WCA == 2#WARNING
        WCA_text = "WARNING"
    with open("../../../Desktop/pyhton_projeleri/pycurl/NKY_log.txt""a+"as file_log:
        file_log.write(time_info + "  ->  "  +  WCA_text + "  ->  " + log_text + "\n")
        print(log_text)
    return
def load_default(eq_index_for_router):
    global data
    data[eq_index_for_router] = ["&"] * len(data[eq_index_for_router]) # "&" means not used bytes
def text_arrange(text_getlen_value):
    l = len(text_get)
    if l < len_value:
        l_new = ["0"] * (len_value - l)
        l_mid = ''.join(l_new)
        text_get = ''.join(text_get)
        l_last = l_mid + text_get
    else:
        l_last = text_get
    return l_last
def data_prepare(prepare_eqprepare_data):
    global data
    global bit_number
    for luk in router_id:
        if prepare_data == luk:
            bit_number = 0
    for fuh in prepare_data:
        data[prepare_eq][bit_number] = fuh
        bit_number += 1
def header_prepare(msg_type_vareq_len):
    # ayın ilk gününden geçen milisaniye değerini bulmak
    tm = str(time.localtime())
    tm = tm.split(",")
    tt = []
    for tm_ind in tm:
        tt.append(tm_ind.strip(" "))
    tt_day = str(tt[2])
    tt_hour = str(tt[3])
    tt_min = str(tt[4])
    tt_sec = str(tt[5])
    m_day = int(tt_day[8:len(tt_day):])
    m_hour = int(tt_hour[8:len(tt_hour):])
    m_min = int(tt_min[7:len(tt_min):])
    m_sec = int(tt_sec[7:len(tt_sec):])
    m_msec = (m_day * 24 * 60 * 60 * 1000) + (m_hour * 60 * 60 * 1000) + (m_min * 60 * 1000) + (m_sec * 1000)

    ################################################################
    # Mesaj Zarfı ##################################################
    ################################################################
    IDD = binascii.unhexlify("322e3030303030303030")  # Veri boyutu 10 byte. Varsayılan olarak atanmıştır (2.00000000)
    Msg_Instance = m_msec.to_bytes(4byteorder='big'# ayın ilk gününden itibaren geçen milisaniye
    # Message tipleri aşağıdaki gibidir;
    # 2001: YSHA Router Durum Bilgisi
    # 3001: YSHA Switch Durum Bilgisi
    Msg_Type = msg_type_var.to_bytes(4byteorder='big'# Mesaj tipi
    Msg_Len = (numberOFRouterDataToSend * eq_len).to_bytes(4byteorder='big')  # Mesaj tipi
    Stream_ID_constant = 4294967295 # Varsayılan olarak atanmıştır (0xFFFFFFFF)
    Stream_ID = Stream_ID_constant.to_bytes(4byteorder='big')
    Package_Sequence_constant = 4294967295 # Varsayılan olarak atanmıştır (0xFFFFFFFF)
    Package_Sequence = Package_Sequence_constant.to_bytes(4byteorder='big')
    Msg_header = IDD + Msg_Instance + Msg_Type + Msg_Len + Stream_ID + Package_Sequence
    yuh = bytes(Msg_header)
    return yuh
def dataSend():
    global th
    global data
    global data1
    global ip
    global port
    global yuh
    yuh_new = header_prepare(2001len(router_id))
    yuh_new_switch = header_prepare(3001len(switch_id))
    yz = 0
    for y in range(len(data)):
        for z in range(len(data[0])):
            data1[yz] = data[y][z]
            yz += 1
    b = bytearray()
    for ji in data1:
        data1_join = ''.join(data1)
    for kkll in data1_join:
        b.extend(kkll.encode(encoding='utf-8'))
    b_new = yuh_new + b

    with open("../../../Desktop/pyhton_projeleri/pycurl/b_len.txt""a+"as b_len_file:
        b_len_file.write("\n" + str(len(data1_join)) + "  ")
        b_len_file.write(str(data1_join))

    #CRC-32 calculation
    b_new_crc = format(zlib.crc32(b_new), 'x')
    b_new_crc_int = int(b_new_crc, 16)
    b_new_crc_bytes = b_new_crc_int.to_bytes(4byteorder='big'# 4 bytes
    b_new += b_new_crc_bytes
    s.sendto(b_new, (ip, port))
    th.cancel()
    th = threading.Timer(3, dataSend)
    th.start()

th = threading.Timer(1, dataSend)
th.start()

while TRUE:
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    eq_index = 0  # Router-1
    try:
        # %%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 1 Connection Check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        if connection_router_1.is_alive() == True:
            logging("YSHA Router 1 SSH Connection OK"0# "0" is INFO, "1" is WARNING"
            data_prepare(eq_index, router_id[eq_index])
            data_prepare(eq_index, success_message)
            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 1 Internal Check (Power, Temperature) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            try:
                env = connection_router_1.send_command('show env'use_textfsm=True)
                # print(json.dumps(env, indent=2))
                env_str = (str(env).strip()).splitlines()
                for rear in range(len(env_str)):
                    env_str[rear] = env_str[rear].strip()
                num_of_critical_alarm = env_str[0][26:len(env_str[0])].strip()
                num_of_major_alarm = env_str[1][26:len(env_str[1])].strip()
                num_of_minor_alarm = env_str[2][26:len(env_str[2])].strip()
                fan0_RPM = env_str[6][23:30].strip()
                fan1_RPM = env_str[7][23:30].strip()
                fan2_RPM = env_str[8][23:30].strip()
                fan3_RPM = env_str[9][23:30].strip()
                power = env_str[10][23:30].strip()
                temp_inlet = env_str[11][23:30].strip()
                temp_interval = env_str[12][23:30].strip()
                temp_outlet = env_str[13][23:30].strip()
                temp_cpu = env_str[14][23:30].strip()
                V_12 = env_str[15][23:30].strip()
                V_5 = env_str[16][23:30].strip()
                V_33 = env_str[17][23:30].strip()
                V_30 = env_str[18][23:30].strip()
                V_25 = env_str[19][23:30].strip()
                V_135 = env_str[20][23:30].strip()
                V_18 = env_str[21][23:30].strip()
                V_12 = env_str[22][23:30].strip()
                VNN_CPU = env_str[23][23:30].strip()
                V_11 = env_str[24][23:30].strip()
                V_10 = env_str[25][23:30].strip()
                V_18_CPU = env_str[26][23:30].strip()
                DDR = env_str[27][23:30].strip()
                V_33_STBY = env_str[28][23:30].strip()
                V_15 = env_str[29][23:30].strip()
                V_10_CPU = env_str[30][23:30].strip()
                VCC_CPU = env_str[31][23:30].strip()
                V_075 = env_str[32][23:30].strip()
                V_12 = env_str[33][23:30].strip()
                PWR = env_str[34][23:30].strip()

                result = re.findall(r"Fail"str(env))
                fail = 0
                for ali in result:
                    if ali == "Fail":
                        fail += 1
                if fail == 0:
                    logging("YSHA Router 1 Internal Check PASS"0# "0" is INFO, "1" is WARNING"
                    data_prepare(eq_index, success_message)
                else:
                    logging("YSHA Router 1 Internal FAIL (temperature or power)"1# "0" is INFO, "1" is WARNING"
                    data_prepare(eq_index, fail_message)
            except Exception as e:
                # print(e)
                logging("YSHA Router 1 Internal Check can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, access_fail_message)

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 1 CPU Check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            try:
                cpu_router_1 = connection_router_1.send_command('show processes cpu'use_textfsm=True)
                # print(json.dumps(cpu_router_1, indent=2))
                if int(cpu_router_1[0]['cpu_1_min']) >= cpu_max:
                    logging('YSHA Router 1 High CPU'1# "0" is INFO, "1" is WARNING"
                    cpu_router_1_problem = 1
                    data_prepare(eq_index, fail_message)
                else:
                    logging('YSHA Router 1 Low CPU'0# "0" is INFO, "1" is WARNING"
                    cpu_router_1_problem = 0
                    data_prepare(eq_index, success_message)
            except Exception as e:
                logging("YSHA Router 1 CPU Status can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, access_fail_message)

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 1 Send Date & Time  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            try:
                time_router_1 = connection_router_1.send_command('show clock'use_textfsm=True)
                # print(json.dumps(time_router_1, indent=2))

                # print(json.dumps(time_router_1, indent=2))
                time_to_bytes = str(time_router_1[0]['time'])
                time_to_bytes = time_to_bytes.split(":")
                for pill in range(len(time_to_bytes)):
                    time_to_bytes[pill] = float(time_to_bytes[pill])
                for pill in range(len(time_to_bytes)):
                    time_to_bytes[pill] = int(time_to_bytes[pill])
                for pill in range(len(time_to_bytes)):
                    time_to_bytes[pill] = str(time_to_bytes[pill])
                day_to_bytes = str(time_router_1[0]['day'])
                logging(year_to_bytes = str(time_router_1[0]['year']))
                if time_router_1[0]['month'] == "Jan": month = "01"
                if time_router_1[0]['month'] == "Feb": month = "02"
                if time_router_1[0]['month'] == "Mar": month = "03"
                if time_router_1[0]['month'] == "Apr": month = "04"
                if time_router_1[0]['month'] == "May": month = "05"
                if time_router_1[0]['month'] == "Jun": month = "06"
                if time_router_1[0]['month'] == "Jul": month = "07"
                if time_router_1[0]['month'] == "Aug": month = "08"
                if time_router_1[0]['month'] == "Sep": month = "09"
                if time_router_1[0]['month'] == "Oct": month = "10"
                if time_router_1[0]['month'] == "Nov": month = "11"
                if time_router_1[0]['month'] == "Dec": month = "12"

                time_to_bytes[0] = text_arrange(time_to_bytes[0], 2)  # arrange to be 2 digit
                time_to_bytes[1] = text_arrange(time_to_bytes[1], 2)  # arrange to be 2 digit
                time_to_bytes[2] = text_arrange(time_to_bytes[2], 2)  # arrange to be 2 digit
                day_to_bytes = text_arrange(day_to_bytes, 2)  # arrange to be 2 digit
                year_to_bytes = text_arrange(year_to_bytes, 4)  # arrange to be 4 digit

                data_prepare(eq_index, time_to_bytes[0])
                data_prepare(eq_index, time_to_bytes[1])
                data_prepare(eq_index, time_to_bytes[2])
                data_prepare(eq_index, month)
                data_prepare(eq_index, day_to_bytes)
                data_prepare(eq_index, year_to_bytes)
            except Exception as e:
                logging("YSHA Router 1  Date & Time can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, "??")
                data_prepare(eq_index, "??")
                data_prepare(eq_index, "??")
                data_prepare(eq_index, "??")
                data_prepare(eq_index, "??")
                data_prepare(eq_index, "??")

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 1 Send Version  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            try:
                version_router_1 = connection_router_1.send_command('show version'use_textfsm=True)
                # print(json.dumps(version_router_1, indent=2))
                #print(Fore.GREEN + Back.BLACK + 'YSHA Router 1 Version: ' + str(version_router_1[0]['version']))
                ver_str = text_arrange(str(version_router_1[0]['version']), 20)  # arrange to be 20 digit
                data_prepare(eq_index, ver_str)
            except Exception as e:
                logging("YSHA Router 1 Version can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, access_fail_message)
                ver_str = "?" * 20
                data_prepare(eq_index, ver_str)

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 1 Interface Check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            try:
                router_1_interface = connection_router_1.send_command('show ip interface brief'use_textfsm=True)
                # print(json.dumps(router_1_interface, indent=2))
                i = 0
                for i in range(len(router_1_interface)):
                    if ((router_1_interface[i]['intf'] == 'GigabitEthernet0/0'and (
                            router_1_interface[i]['status'] == 'up')):
                        router_1_gigabitetnernet10_interface_problem = 0
                    else:
                        ...
                i = 0
                for i in range(len(router_1_interface)):
                    if ((router_1_interface[i]['intf'] == 'GigabitEthernet1/0'and (
                            router_1_interface[i]['status'] == 'up')):
                        router_1_gigabitetnernet20_interface_problem = 0
                    else:
                        ...
                if router_1_gigabitetnernet10_interface_problem == 0 and router_1_gigabitetnernet20_interface_problem == 0:
                    router_1_interface_problem = 1
                    logging("YSHA Router 1 Interface Check PASS"0# "0" is INFO, "1" is WARNING"
                    data_prepare(eq_index, success_message)
                else:
                    router_1_interface_problem = 0
                    logging("YSHA Router 1 Interface FAIL"1# "0" is INFO, "1" is WARNING"
                    data_prepare(eq_index, fail_message)
            except Exception as e:
                logging("YSHA Router 1 Interface Status can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, access_fail_message)

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 1 Standby Status %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            try:
                standby_router_1 = connection_router_1.send_command('show standby'use_textfsm=True)
                # print(json.dumps(standby_router_1, indent=2))
                if standby_router_1[0]['state'] == 'Active':
                    logging('YSHA Router 1 is Active'0# "0" is INFO, "1" is WARNING"
                    standby_router_problem = 0
                    active_router = 1
                    data_prepare(eq_index, success_message)
                elif standby_router_1[0]['state'] == 'Standby':
                    logging('YSHA Router 1 is Standby'2# "0" is INFO, "1" is WARNING"
                    standby_router_problem = 0
                    data_prepare(eq_index, "£")
                else:
                    logging('Redundancy FAIL'1# "0" is INFO, "1" is WARNING"
                    standby_router_problem = 1
                    active_router = 0
                    data_prepare(eq_index, fail_message)
            except Exception as e:
                logging("YSHA Router 1 Standby Status can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, access_fail_message)
        else:
            dummy_var_to_jump_exception_1 = dummy_var_to_jump_exception_2 # dummy fail mesaage to jump exception
    except Exception as e:
        logging("YSHA Router 1 SSH Connection can't be established"2# "0" is INFO, "1" is WARNING"
        load_default(eq_index)
        data_prepare(eq_index, router_id[eq_index])
        data_prepare(eq_index, fail_message)
        logging("New connection is trying to establish for " + "Router " + str(eq_index + 1) + "..."0# "0" is INFO, "1" is WARNING"
        try:
            connection_router_1 = ConnectHandler(**router[eq_index])
            text = "New connection " + "(Router " + str(eq_index + 1) + ") " + "SUCCEED..."
            logging(text, 0# "0" is INFO, "1" is WARNING"
        except:
            text = "New connection " + "(Router " + str(eq_index + 1) + ") " + "FAILED..."
            logging(text, 1# "0" is INFO, "1" is WARNING"

    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    eq_index = 1  # Router-2
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 2 Connection Check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    try:
        if connection_router_2.is_alive() == True:
            logging('YSHA Router 2 SSH Connection OK'0# "0" is INFO, "1" is WARNING"
            data_prepare(eq_index, router_id[eq_index])
            data_prepare(eq_index, success_message)
            try:
                env = connection_router_2.send_command('show env'use_textfsm=True)
                # print(json.dumps(env, indent=2))
                # print(str(env))
                env_str = (str(env).strip()).splitlines()
                for rear in range(len(env_str)):
                    env_str[rear] = env_str[rear].strip()
                    # print(rear, ":", env_str[rear])
                num_of_critical_alarm = env_str[0][26:len(env_str[0])].strip()
                num_of_major_alarm = env_str[1][26:len(env_str[1])].strip()
                num_of_minor_alarm = env_str[2][26:len(env_str[2])].strip()
                fan0_RPM = env_str[6][23:30].strip()
                fan1_RPM = env_str[7][23:30].strip()
                fan2_RPM = env_str[8][23:30].strip()
                fan3_RPM = env_str[9][23:30].strip()
                power = env_str[10][23:30].strip()
                temp_inlet = env_str[11][23:30].strip()
                temp_interval = env_str[12][23:30].strip()
                temp_outlet = env_str[13][23:30].strip()
                temp_cpu = env_str[14][23:30].strip()
                V_12 = env_str[15][23:30].strip()
                V_5 = env_str[16][23:30].strip()
                V_33 = env_str[17][23:30].strip()
                V_30 = env_str[18][23:30].strip()
                V_25 = env_str[19][23:30].strip()
                V_135 = env_str[20][23:30].strip()
                V_18 = env_str[21][23:30].strip()
                V_12 = env_str[22][23:30].strip()
                VNN_CPU = env_str[23][23:30].strip()
                V_11 = env_str[24][23:30].strip()
                V_10 = env_str[25][23:30].strip()
                V_18_CPU = env_str[26][23:30].strip()
                DDR = env_str[27][23:30].strip()
                V_33_STBY = env_str[28][23:30].strip()
                V_15 = env_str[29][23:30].strip()
                V_10_CPU = env_str[30][23:30].strip()
                VCC_CPU = env_str[31][23:30].strip()
                V_075 = env_str[32][23:30].strip()
                V_12 = env_str[33][23:30].strip()
                PWR = env_str[34][23:30].strip()

                result = re.findall(r"Fail"str(env))
                fail = 0
                for ali in result:
                    if ali == "Fail":
                        fail += 1
                if fail == 0:
                    logging("YSHA Router 2 Internal Check PASS"0# "0" is INFO, "1" is WARNING"
                    data_prepare(eq_index, success_message)
                else:
                    logging("YSHA Router 2 Internal FAIL (temperature or power"1# "0" is INFO, "1" is WARNING"
                    data_prepare(eq_index, fail_message)
            except Exception as e:
                logging("YSHA Router 2 Internal Check can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, access_fail_message)

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 2 CPU Check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            try:
                cpu_router_2 = connection_router_2.send_command('show processes cpu'use_textfsm=True)
                # print(json.dumps(cpu, indent=2))
                if int(cpu_router_2[0]['cpu_1_min']) >= cpu_max:
                    logging('YSHA Router 2 High CPU'1# "0" is INFO, "1" is WARNING"
                    data_prepare(eq_index, fail_message)
                else:
                    logging('YSHA Router 2 Low CPU'0# "0" is INFO, "1" is WARNING"
                    data_prepare(eq_index, success_message)
            except Exception as e:
                logging("YSHA Router 2 CPU Status can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, access_fail_message)

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 2 Send Date & Time  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

            try:
                time_router_2 = connection_router_2.send_command('show clock'use_textfsm=True)
                # print(json.dumps(time_router_1, indent=2))

                time_to_bytes = str(time_router_2[0]['time'])
                time_to_bytes = time_to_bytes.split(":")
                for pill in range(len(time_to_bytes)):
                    time_to_bytes[pill] = float(time_to_bytes[pill])
                for pill in range(len(time_to_bytes)):
                    time_to_bytes[pill] = int(time_to_bytes[pill])
                for pill in range(len(time_to_bytes)):
                    time_to_bytes[pill] = str(time_to_bytes[pill])

                if time_router_2[0]['month'] == "Jan": month = "01"
                if time_router_2[0]['month'] == "Feb": month = "02"
                if time_router_2[0]['month'] == "Mar": month = "03"
                if time_router_2[0]['month'] == "Apr": month = "04"
                if time_router_2[0]['month'] == "May": month = "05"
                if time_router_2[0]['month'] == "Jun": month = "06"
                if time_router_2[0]['month'] == "Jul": month = "07"
                if time_router_2[0]['month'] == "Aug": month = "08"
                if time_router_2[0]['month'] == "Sep": month = "09"
                if time_router_2[0]['month'] == "Oct": month = "10"
                if time_router_2[0]['month'] == "Nov": month = "11"
                if time_router_2[0]['month'] == "Dec": month = "12"

                time_to_bytes[0] = text_arrange(time_to_bytes[0], 2)  # arrange to be 2 digit
                time_to_bytes[1] = text_arrange(time_to_bytes[1], 2)  # arrange to be 2 digit
                time_to_bytes[2] = text_arrange(time_to_bytes[2], 2)  # arrange to be 2 digit

                data_prepare(eq_index, time_to_bytes[0])
                data_prepare(eq_index, time_to_bytes[1])
                data_prepare(eq_index, time_to_bytes[2])
                data_prepare(eq_index, month)
                data_prepare(eq_index, str(time_router_2[0]['day']))
                data_prepare(eq_index, str(time_router_2[0]['year']))
            except Exception as e:
                logging("YSHA Router 1  Date & Time can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, access_fail_message)
                data_prepare(eq_index, access_fail_message)
                data_prepare(eq_index, access_fail_message)
                data_prepare(eq_index, access_fail_message)
                data_prepare(eq_index, access_fail_message)
                data_prepare(eq_index, access_fail_message)

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 2 Send Version  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

            try:
                version_router_2 = connection_router_2.send_command('show version'use_textfsm=True)
                # print(json.dumps(version_router_1, indent=2))
                #print(Fore.GREEN + Back.BLACK + 'YSHA Router 2 Version: ' + str(version_router_2[0]['version']))
                ver_str = text_arrange(str(version_router_2[0]['version']), 20)  # arrange to be 20 digit
                data_prepare(eq_index, ver_str)
            except Exception as e:
                logging("YSHA Router 2 Version can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, access_fail_message)

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 2 Interface Check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            try:
                router_2_interface = connection_router_2.send_command('show ip interface brief'use_textfsm=True)
                # print(json.dumps(router_2_interface, indent=2))
                i = 0
                for i in range(len(router_2_interface)):
                    if ((router_2_interface[i]['intf'] == 'GigabitEthernet0/0'and (
                            router_2_interface[i]['status'] == 'up')):
                        router_2_gigabitetnernet10_interface_problem = 0
                    else:
                        ...

                i = 0
                for i in range(len(router_2_interface)):
                    if ((router_2_interface[i]['intf'] == 'GigabitEthernet1/0'and (
                            router_2_interface[i]['status'] == 'up')):
                        router_2_gigabitetnernet20_interface_problem = 0
                    else:
                        ...

                if router_2_gigabitetnernet10_interface_problem == 0 and router_2_gigabitetnernet20_interface_problem == 0:
                    router_2_interface_problem = 1
                    logging("YSHA Router 2 Interface Check PASS"0# "0" is INFO, "1" is WARNING"
                    data_prepare(eq_index, success_message)
                else:
                    router_2_interface_problem = 0
                    logging("YSHA Router 2 Interface FAIL"1# "0" is INFO, "1" is WARNING"
                    data_prepare(eq_index, fail_message)
            except Exception as e:
                logging("YSHA Router 2  Interface Status can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, "k")

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Router 2 Standby Status %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            try:
                standby_router_2 = connection_router_2.send_command('show standby'use_textfsm=True)
                if standby_router_2[0]['state'] == 'Active':
                    logging('YSHA Router 2 is Active'0# "0" is INFO, "1" is WARNING"
                    standby_router_problem = 0
                    active_router = 2
                    data_prepare(eq_index, success_message)
                elif standby_router_2[0]['state'] == 'Standby':
                    logging('YSHA Router 2 is Standby'2# "0" is INFO, "1" is WARNING"
                    standby_router_problem = 0
                    data_prepare(eq_index, "*")
                else:
                    logging('YSHA Router Redundancy FAIL'1# "0" is INFO, "1" is WARNING"
                    standby_router_problem = 1
                    active_router = 0
                    data_prepare(eq_index, fail_message)
            except Exception as e:
                logging("YSHA Router 2 Standby Status can't be reachable"2# "0" is INFO, "1" is WARNING"
                data_prepare(eq_index, active_router_connection)
        else:
            dummy_var_to_jump_exception_1 = dummy_var_to_jump_exception_2  # dummy fail mesaage to jump exception
    except Exception as e:
        logging("YSHA Router 2 SSH Connection can't be established"1# "0" is INFO, "1" is WARNING"
        load_default(eq_index)
        data_prepare(eq_index, router_id[eq_index])
        data_prepare(eq_index, fail_message)
        logging("New connection is trying to establish for " + "Router " + str(eq_index + 1) + "..."0# "0" is INFO, "1" is WARNING"
        try:
            connection_router_2 = ConnectHandler(**router[eq_index])
            text = "New connection " + "(Router " + str(eq_index + 1) + ") " + "SUCCEED..."
            logging(text, 0# "0" is INFO, "1" is WARNING"
        except:
            text = "New connection " + "(Router " + str(eq_index + 1) + ") " + "FAILED..."
            logging(text, 1# "0" is INFO, "1" is WARNING"



    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Switch CPU Check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    with open('../../../Desktop/pyhton_projeleri/pycurl/IP_LIST_Switch.txt'as IP_file_switch:
        IP_Switch = IP_file_switch.read().splitlines()

    switch = {
        'device_type''cisco_ios_telnet',
        'ip': IP_Switch[0],
        'username''cisco',
        'password''cisco',
        'secret''cisco',
        'port'23
    }
    connection_switch = ConnectHandler(**switch)
    try:
        cpu_switch_1 = connection_switch.send_command('show processes cpu'use_textfsm=True)
        # print(json.dumps(cpu_switch_1, indent=2))
        if int(cpu_switch_1_1[0]['cpu_1_min']) >= cpu_max:
            logging('YSHA Switch 1 High CPU'1# "0" is INFO, "1" is WARNING"
            cpu_switch_problem = 1
            data_prepare(eq_index, fail_message)
        else:
            logging('YSHA Switch 1 Low CPU'0# "0" is INFO, "1" is WARNING"
            cpu_switch_problem = 0
            data_prepare(eq_index, success_message)
    except Exception as e:
        logging("YSHA Switch 1 CPU Status can't be reachable"2# "0" is INFO, "1" is WARNING"
        data_prepare(eq_index, access_fail_message)
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Switch STANDBY Check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    try:
         cpu_switch = connection_switch.send_command('show switch detail'use_textfsm=True)
         print(json.dumps(cpu_switch, indent=2))
         if cpu_switch[0]['state'] == 'Ready' and cpu_switch[1]['state'] == 'Ready':
          print('YSHA Switch 1 and Switch 2 OK')
          cpu_switch_problem = 1
         else:
          print('YSHA Switch FAULT')
          cpu_switch_problem = 0
    except Exception as e:
        print(e)
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Switch INTERFACE Check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    try:
        cpu_switch = connection_switch.send_command('show logging')
        result = re.findall(r"down"str(cpu_switch))
        if result[0] == 'down':
            print(' YSHA Switch PORT KONTROL ET')
            connection_switch.send_command('clear logging\n')
            cpu_switch_problem = 1
        else:
            print('YSHA Switch 1 and Switch 2 PORT OK')
            cpu_switch_problem = 0

    except Exception as e:
        print(e)
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% YSHA Switch KRITIK HATA KONTROLU %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    try:
        kritik_hata_switch = connection_switch.send_command('show logging')
        result = re.findall(r"-1-"str(kritik_hata_switch))
        if result == '-1-':
            print(' YSHA Switch KRITIK HATA')
            connection_switch.send_command('clear logging\n')
            kritik_hata_switch_problem = 1
        else:
            print('YSHA Switch 1 and Switch 2 KRITIK HATA YOK')
            kritik_hata_switch_problem = 0

    except Exception as e:
        print(e)

    #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TAFICS Check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    try:
        if active_router == 1:
            active_router_connection = connection_router_1
            aR = router_id[0]
        elif active_router == 2:
            active_router_connection = connection_router_2
            aR = router_id[1]
        else:
            ...
        #print(json.dumps(interfaces, indent=2))
        taffics_connection = active_router_connection.send_command('ping 2.2.2.10'use_textfsm=True)
        result = re.findall(r"Success rate is 100 percent"str(taffics_connection))
        if result == ['Success rate is 100 percent']:
            logging('TAFICS Status: OK'0# "0" is INFO, "1" is WARNING"
            tafics_failure = 0

        else:
            logging('TAFICS Status: Not OK!!!'1# "0" is INFO, "1" is WARNING"
            tafics_failure += 1
            if tafics_failure > tafics_failure_count:
                tafics_failure = 1

        if tafics_failure == 0:
            check_first_time = 0
            command = active_router_connection.send_command('show ip interface brief'use_textfsm=True)
            i = 0
            for i in range(len(command)):
                if (command[i]['intf'] == 'Tunnel0'and (
                        command[i]['status'] == 'down' or
                        command[i]['status'] == 'administratively down'):
                    logging('Tunnel configuration starting (no shutdown)...'0# "0" is INFO, "1" is WARNING"
                    output = active_router_connection.send_config_set(['xinterface xtunnel 0',
                                                'ip address 3.3.3.1 255.255.255.0',
                                                'no shut',
                                                'exit'])
                else:
                    ...

            i = 0
            for i in range(len(command)):
                if command[i]['intf'] == 'Loopback0':
                    logging('Loopback 0 configuration starting (shutdown)...'0# "0" is INFO, "1" is WARNING"
                    output = active_router_connection.send_config_set(['xno interface loopback 0',
                                                'exit'])
                else:
                    ...

        if tafics_failure == tafics_failure_count:
            command = active_router_connection.send_command('show ip interface brief'use_textfsm=True)
            #print(command)
            i = 0
            for i in range(len(command)):
                if (command[i]['intf'] == 'Tunnel0'and (
                        command[i]['status'] == 'up'):
                    logging('Tunnel configuration starting (shutdown)...'0# "0" is INFO, "1" is WARNING"
                    output = active_router_connection.send_config_set(['interface xtunnel 0',
                                                'ip address 3.3.3.1 255.255.255.0',
                                                'shut',
                                                'exit'])
                else:
                    ...
            if check_first_time == 0:
                logging('Loopback 0 configuration starting (no shutdown)...'0# "0" is INFO, "1" is WARNING"
                output = active_router_connection.send_config_set(['interface xloop 0',
                                            'ip address 10.10.10.10 255.255.255.0',
                                            'exit'])
                check_first_time = 1
    except Exception as e:
        logging("###coding error### (Exception)"2)