示例#1
0
def load_ip_brief_and_routes():
    id = request.json
    device = Device.query.get(id)
    if ping(device.deviceip):

        c = SendCommands()
        print(
            c.connecting(device.deviceuserlogin, device.deviceip,
                         device.devicepassword, device.devicepasswordena))

        if not c.error_desc == 'Error de Autenticacion':
            print('passwords correctos')

            check_ip_brief, check_ip_route = c.ip_brief_and_routes()
            return jsonify(check_ip_brief=format(check_ip_brief),
                           check_ip_route=format(check_ip_route))

        else:
            output = 'Verifique que los Passwords de Acceso tanto para login como modo ENABLE sean correctos'
            return jsonify(data=output)
        return jsonify(data='algo fallo')

    else:
        return jsonify(
            data=
            'El estado del dispositivo es Down! verifique conectividad IP...')
示例#2
0
def show_result_static_route():
    group = 'Static Route'
    form = DevicesConfigStaticRoute()
    # print('static route id',form.id.data)
    if form.validate_on_submit():
        id_c = form.id.data
        device = Device.query.get(id_c)
        user = User.query.get(id_c)
        print('device ip:', device.deviceip)
        print('ip validada:', form.ip_destino.data)
        if ping(device.deviceip):
            # ip=form.ip_destino.data
            # mask=form.mascara.data
            # n_hop=form.next_hop.data
            # space=' '
            # mycall = call()
            # out = mycall.calling(ip,mask,n_hop)
            # print(out)

            c = SendCommands()
            print(
                c.connecting(device.deviceuserlogin, device.deviceip, 'cisco',
                             'cisco'))
            userlogin = device.deviceuserlogin
            deviceip = device.deviceip
            devicepassword = device.devicepassword
            devicepasswordena = device.devicepasswordena

            print(userlogin, deviceip, devicepassword, devicepasswordena)
            # c.connecting('raul','192.168.10.110','cisco','cisco')
            if not c.error_desc == 'Error de Autenticacion':
                # print(c.net_connect.find_prompt())
                output, running_config = c.static_route(
                    form.ip_destino.data, form.mascara.data,
                    form.next_hop.data)
                # output= c.net_connect.find_prompt()
                task = bg_save_executed_cm.delay(form.id.data, output,
                                                 running_config, group)
            else:
                output = 'Verifique que los Passwords de Acceso tanto para login como modo ENABLE sean correctos'
            # new_device_config = DeviceConfig(deviceconfig=device.devicename+'-'+str(datetime.utcnow()),devicecurrentconfig=out)
            # new_device_config.device= device
            # db.session.add(new_device_config)
            # db.session.commit()

            return jsonify(data=format(output))
        else:
            return jsonify(
                data=
                'El estado del dispositivo es Down! verifique conectividad IP...'
            )
    else:
        # flash_errors(form)
        # return jsonify(ip_destino=form.ip_destino.errors, mascara=form.mascara.errors, next_hop=form.next_hop.errors)
        return jsonify(error1=form.ip_destino.errors,
                       error2=form.mascara.errors,
                       error3=form.next_hop.errors)

    return jsonify(data='Error en la validacion de los datos!')
示例#3
0
def show_result_ebgp_vrf():
    form = ebgp_vrf_form()
    # print('static route id',form.id.data)
    if form.validate_on_submit():
        device = Device.query.get(form.id.data)
        if ping(device.deviceip):
            # falta terminar de configurar
            # mycall = call()
            # out = mycall.calling(ip,mask,n_hop)
            # print(out)

            # new_device_config = DeviceConfig(deviceconfig=device.devicename+'-'+str(datetime.utcnow()),devicecurrentconfig=out)
            # new_device_config.device= device
            # db.session.add(new_device_config)
            # db.session.commit()

            c = SendCommands()
            print(
                c.connecting(device.deviceuserlogin, device.deviceip,
                             device.devicepassword, device.devicepasswordena))
            userlogin = device.deviceuserlogin
            deviceip = device.deviceip
            devicepassword = device.devicepassword
            devicepasswordena = device.devicepasswordena

            print(userlogin, deviceip, devicepassword, devicepasswordena)
            # c.connecting('raul','192.168.10.110','cisco','cisco')
            if not c.error_desc == 'Error de Autenticacion':
                # print(c.net_connect.find_prompt())
                output = c.eBGP_vrf(form.bgp_process.data, form.bgp_as.data,
                                    form.bgp_neighbor.data, form.bgp_vrf.data)
                # output= c.net_connect.find_prompt()
            else:
                output = 'Verifique que los Passwords de Acceso tanto para login como modo ENABLE sean correctos'
            # new_device_config = DeviceConfig(deviceconfig=device.devicename+'-'+str(datetime.utcnow()),devicecurrentconfig=out)
            # new_device_config.device= device
            # db.session.add(new_device_config)
            # db.session.commit()
            return jsonify(data=format(output))

            return jsonify(data=format(out))
        else:
            return jsonify(
                data=
                'El estado del dispositivo es Down! verifique conectividad IP...'
            )
    else:
        # flash_errors(form)
        # return jsonify(ip_destino=form.ip_destino.errors, mascara=form.mascara.errors, next_hop=form.next_hop.errors)
        return jsonify(error1=form.bgp_process.errors,
                       error2=form.bgp_as.errors,
                       error3=form.bgp_neighbor.errors,
                       erro4=form.bgp_network,
                       error5=form.bgp_mascara)

    return jsonify(data='Error en la validacion de los datos!')
示例#4
0
def test_ping():
    print("\nStart ping to test {} for {} times".format(ip_addr, ping_count))
    average_rtt, loss = ping(ip_addr, ping_count)
    status = False

    # Fail condition
    if loss < 30 and average_rtt <= 3:
        status = True

    assert status == True
示例#5
0
def show_result_interface_vrf():
    form = DeviceConfigInterfaces_vrf()
    # print('static route id',form.id.data)
    if form.validate_on_submit():
        device = Device.query.get(form.id.data)
        if ping(device.deviceip):
            interface = form.interface.data
            interface_ip = form.interface_ip.data
            interface_mascara = form.interface_mascara.data

            # new_device_config = DeviceConfig(deviceconfig=device.devicename+'-'+str(datetime.utcnow()),devicecurrentconfig=out)
            # new_device_config.device= device
            # db.session.add(new_device_config)
            # db.session.commit()

            c = SendCommands()
            print(
                c.connecting(device.deviceuserlogin, device.deviceip,
                             device.devicepassword, device.devicepasswordena))

            # c.connecting('raul','192.168.10.110','cisco','cisco')
            if not c.error_desc == 'Error de Autenticacion':
                # print(c.net_connect.find_prompt())
                output = c.interfaces_vrf(form.interface.data,
                                          form.interface_vrf.data,
                                          form.interface_ip.data,
                                          form.interface_mascara.data, 'Up')
                # output= c.net_connect.find_prompt()
            else:
                output = 'Verifique que los Passwords de Acceso tanto para login como modo ENABLE sean correctos'
            # new_device_config = DeviceConfig(deviceconfig=device.devicename+'-'+str(datetime.utcnow()),devicecurrentconfig=out)
            # new_device_config.device= device
            # db.session.add(new_device_config)
            # db.session.commit()

            return jsonify(data=format(output))
        else:
            return jsonify(
                data=
                'El estado del dispositivo es Down! verifique conectividad IP...'
            )
    else:
        # flash_errors(form)
        # return jsonify(ip_destino=form.ip_destino.errors, mascara=form.mascara.errors, next_hop=form.next_hop.errors)
        return jsonify(error1=form.interface.errors,
                       error2=form.interface_ip.errors,
                       error3=form.interface_mascara.errors)

    return jsonify(data='Error en la validacion de los datos!')
示例#6
0
文件: serv.py 项目: ipconfiger/pingit
def worker(node_id,ip_addr):
    ping_ok = True
    current_status = ping_ok
    last_status = ping_ok
    last_error_id = None
    while(True):
        if reduce(lambda a,b: a and b,[ping(ip_addr) for i in xrange(int(config["ping_times"]))]):
              if last_status != ping_ok:
                  #上次如果是失败的话就重置状态为成功
                  Q.put((node_id, True, last_error_id))
                  last_status = ping_ok
                  last_error_id = None
        else:
            if last_status == ping_ok:
                #如果上次是成功的话就重置状态为失败,如果已经是失败状态就不重复操作
                last_error_id = uuid.uuid4().hex
                Q.put((node_id, False, last_error_id))
                last_status = False
        gevent.sleep(seconds=int(config["wait"]))
示例#7
0
def bg_task(id):
    # Chequeo Asyncrono para que no interrumpa las solicitudes http get o post
    up = ''

    device = Device.query.get(id)
    if ping(device.deviceip):
        print('Levanto!', device.deviceip)
        up = 'Up'
    else:
        print('Down!', device.deviceip)
        up = 'Down'

    print('device status:', up)

    s = snmpcall()  
    i = s.interfaces(device.devicesnmp,device.deviceip)
    lista_inter = ''
    for inter in i:
        lista_inter += inter + ' '

    #result = jsonify(status=up,interfaces_snmp=lista_inter)
    return up, lista_inter
示例#8
0
def load_device():
    up = ''
    # print('request json',request.json)
    device = Device.query.get(request.json)
    if ping(device.deviceip):
        up = 'Up'
    else:
        up = 'Down'

    s = snmpcall()
    i = s.interfaces(device.devicesnmp, device.deviceip)
    lista_inter = ''
    for inter in i:
        lista_inter += inter + ' '

    # print('device data:',device.devicename,device.deviceip,device.devicerol)
    return jsonify(devicename=device.devicename,
                   devicerol=device.devicerol,
                   deviceip=device.deviceip,
                   status=up,
                   devicesnmp=device.devicesnmp,
                   interfaces_snmp=lista_inter)
示例#9
0
#Get the Local IP
end = re.search('^[\d]{1,3}.[\d]{1,3}.[\d]{1,3}.[\d]{1,3}', ip)

#Chop down the last IP Digits
create_ip = re.search('^[\d]{1,3}.[\d]{1,3}.[\d]{1,3}.', ip)

#Print IP to the user
print "Your IP Address is: " + str(end.group(0))

#Pinging the IP
def ping(ip):
	if verbose_ping(ip) == True:
		print ip, 'is Online'

#Check IP 
def CheckLoopBack(ip):
	if (end.group(0) == '127.0.0.1'):
		return True
		print "Either your IP is a Loop Back or it does not belong in local IP range"

print "Pinging IP's..."


if(CheckLoopBack(create_ip)):
	print "Either your IP is a Loop Back or it does not belong in local IP range"
else:
	for i in range(1, 244):
		ping(str(create_ip.group(0)) + str(i))
	os.system('clear')
示例#10
0
                print bc.dtm + time.ctime(
                ) + bc.ENDC + ' - Updating Gateway Record to Database \n\n'
                cur.execute(
                    'UPDATE gateway SET sync = %s, location = %s, reboot = %s, find_gw = %s where id = %s',
                    (0, ip, 1, 0, 1))
                con.commit()
            print "-" * 65
            s.close()
            exit()
        else:
            print bc.dtm + time.ctime(
            ) + bc.ENDC + ' - Scanning for Next Alive IP Address'


#Check IP
def CheckLoopBack(ip):
    if (end.group(0) == '127.0.0.1'):
        return True
        print bc.dtm + time.ctime(
        ) + bc.ENDC + ' - Either your IP is a Loop Back or it does not belong in local IP range'


print bc.dtm + time.ctime() + bc.ENDC + ' - Pinging Local Network IP Range '

if (CheckLoopBack(create_ip)):
    print bc.dtm + time.ctime(
    ) + bc.ENDC + ' - Either your IP is a Loop Back or it does not belong in local IP range'
else:
    for i in range(1, 254):
        ping(str(create_ip.group(0)) + str(i))
示例#11
0
import unittest
from ping import *
result = ping ("google.com")


class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.result = ping ("google.com")

    def test_packet_loss(self):
        self.assertTrue("packet loss" in self.result)

    def test_number_ping(self):
        self.assertRaises(TypeError, ping, 12312312)

    def test_list_ping(self):
        self.assertRaises(TypeError, ping, [1,2,3,4,5])

    def test_tuple_ping(self):
        self.assertRaises(TypeError, ping, (1,2,3,4,5))

if __name__ == '__main__':
    unittest.main()
示例#12
0
# Ping_Test.py

from cyberbot import *
from ping import *

bot(22).tone(2000, 300)

while True:
    distance = ping(8).distance()
    print('Dist() = %d' % distance)
    distance = ping(8).distance('cm')
    print('Dist(cm) = %d' % distance)
    distance = ping(8).distance('in')
    print('Dist(in) = %d' % distance)
    distance = ping(8).distance('us')
    print('Dist(us) = %d\r' % distance)
    #display.scroll(str(distance), 125)
    sleep(750)
示例#13
0
C = colored

#ping = verbose_ping
ping = quiet_ping


def check_result(res):
    if res != 1.0:
        return C("√", "green")
    else:
        return C("×", "red", attrs=["bold"])


for hmi_com_board in hmi_com_boards:
    print(C("正在检查{0}控显机通信板状态...".format(hmi_com_board["NAME"]), "yellow"))
    # check A
    res = ping(hmi_com_board['A'])
    print(
        C(
            "   正在检查A口通信状态,ip:{0}         [{1}]".format(
                hmi_com_board['A'], check_result(res[3])), "yellow"))

    # check B
    res = ping(hmi_com_board['B'])
    print(
        C(
            "   正在检查B口通信状态,ip:{0}         [{1}]".format(
                hmi_com_board['B'], check_result(res[3])), "yellow"))

    print()
示例#14
0
import time, os
from urllib2 import urlopen
import conf
from ping import *

content = ""
while True:
    result = ping(conf.route)
    try:
        content = urlopen(conf.message_url).read()
    except urllib2.HTTPError:
        print "wrong url or server down"    #most like 404

    if "100% packet loss" in result:
        print "server down"
        if content != "":
            message = "server down!" + content
        else: message = "The server you were monitoring is DOWN!"
        #server down, do procedure

        Mailing.mail(conf.email, "Server is down", message)
        print "email sent"
        if conf.sms_alarm and conf.sms_company.lower() == "movistar":
            Mailing.mail(conf.sms_number+"@sms.movistar.net.ar", "", message)
        if conf.sms_alarm and conf.sms_company.lower() == "verizon":
            Mailing.mail(conf.sms_number+"@vtext.com", "", message)
        if conf.sms_alarm and conf.sms_company.lower() == "at&t":
            Mailing.mail(conf.sms_number+"@txt.att.net", "", message)
        if conf.sms_alarm and conf.sms_company.lower() == "sprint":
            Mailing.mail(conf.sms_number+"@messaging.sprintpcs.com", "", message)
        if conf.sms_alarm and conf.sms_company.lower() == "t-mobile":
示例#15
0
 def setUp(self):
     self.result = ping("google.com")
示例#16
0
import unittest
from ping import *
result = ping("google.com")


class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.result = ping("google.com")

    def test_packet_loss(self):
        self.assertTrue("packet loss" in self.result)

    def test_number_ping(self):
        self.assertRaises(TypeError, ping, 12312312)

    def test_list_ping(self):
        self.assertRaises(TypeError, ping, [1, 2, 3, 4, 5])

    def test_tuple_ping(self):
        self.assertRaises(TypeError, ping, (1, 2, 3, 4, 5))


if __name__ == '__main__':
    unittest.main()
示例#17
0
import time, os
from urllib2 import urlopen
import conf
from ping import *

content = ""
while True:
    result = ping(conf.route)
    try:
        content = urlopen(conf.message_url).read()
    except urllib2.HTTPError:
        print "wrong url or server down"  #most like 404

    if "100% packet loss" in result:
        print "server down"
        if content != "":
            message = "server down!" + content
        else:
            message = "The server you were monitoring is DOWN!"
        #server down, do procedure

        Mailing.mail(conf.email, "Server is down", message)
        print "email sent"
        if conf.sms_alarm and conf.sms_company.lower() == "movistar":
            Mailing.mail(conf.sms_number + "@sms.movistar.net.ar", "", message)
        if conf.sms_alarm and conf.sms_company.lower() == "verizon":
            Mailing.mail(conf.sms_number + "@vtext.com", "", message)
        if conf.sms_alarm and conf.sms_company.lower() == "at&t":
            Mailing.mail(conf.sms_number + "@txt.att.net", "", message)
        if conf.sms_alarm and conf.sms_company.lower() == "sprint":
            Mailing.mail(conf.sms_number + "@messaging.sprintpcs.com", "",
示例#18
0
 def setUp(self):
     self.result = ping ("google.com")
示例#19
0
# Ping_Push_Pull.py

from cyberbot import *
from ping import *
from feedback360 import *

setPoint = 25
kP = -7

bot(22).tone(2000, 300)

drive.connect()

while True:
    distance = ping(8).distance('cm')

    errorVal = setPoint - distance
    speed = kP * errorVal

    if speed > 0:
        display.show(Image("00000:" "00000:" "99999:" "09090:" "00900"))
    elif speed < 0:
        display.show(Image("00900:" "09090:" "99999:" "00000:" "00000"))
    else:
        display.show(Image.DIAMOND)

    drive.speed(speed, speed)
示例#20
0
        ]

colorama.init()

C = colored

#ping = verbose_ping
ping = quiet_ping

def check_result(res):
    if res != 1.0:
        return C("√","green")
    else:
        return C("×","red",attrs=["bold"])

for hmi_com_board in hmi_com_boards:
    print(C("正在检查{0}控显机通信板状态...".format(hmi_com_board["NAME"]),"yellow"))
    # check A
    res = ping(hmi_com_board['A'])
    print(C("   正在检查A口通信状态,ip:{0}         [{1}]"
        .format(hmi_com_board['A'],check_result(res[3])),"yellow"))

    # check B
    res = ping(hmi_com_board['B'])
    print(C("   正在检查B口通信状态,ip:{0}         [{1}]"
        .format(hmi_com_board['B'],check_result(res[3])),"yellow"))

    print()