def test_verbose_ping_ttl_exception(self): with patch("sys.stdout", new=io.StringIO()), patch("ping3.EXCEPTIONS", True): with self.assertRaises( (ping3.errors.TimeToLiveExpired, ping3.errors.Timeout )): # When TTL expired, some routers report nothing. ping3.verbose_ping(DEST_DOMAIN, ttl=1)
def main(assigned_args: list = None): """ Parse and execute the call from command-line. Args: assigned_args: List of strings to parse. The default is taken from sys.argv. Returns: Formatted ping results printed. """ parser = argparse.ArgumentParser(prog="ping3", description="A pure python3 version of ICMP ping implementation using raw socket.", epilog="!!Note: ICMP messages can only be sent from processes running as root.") parser.add_argument("-v", "--version", action="version", version=ping3.__version__) parser.add_argument(dest="dest_addr", metavar="DEST_ADDR", nargs="*", default=("example.com", "8.8.8.8"), help="The destination address, can be an IP address or a domain name. Ex. 192.168.1.1/example.com.") parser.add_argument("-c", "--count", dest="count", metavar="COUNT", type=int, default=4, help="How many pings should be sent. Default is 4.") parser.add_argument("-w", "--wait", dest="timeout", metavar="TIMEOUT", type=float, default=4, help="Time to wait for a response, in seconds. Default is 4.") parser.add_argument("-i", "--interval", dest="interval", metavar="INTERVAL", type=float, default=0, help="Time to wait between each packet, in seconds. Default is 0.") parser.add_argument("-I", "--interface", dest="interface", metavar="INTERFACE", default="", help="LINUX ONLY. The gateway network interface to ping from. Default is None.") parser.add_argument("-t", "--ttl", dest="ttl", metavar="TTL", type=int, default=64, help="The Time-To-Live of the outgoing packet. Default is 64.") parser.add_argument("-l", "--load", dest="size", metavar="SIZE", type=int, default=56, help="The ICMP packet payload size in bytes. Default is 56.") parser.add_argument("--debug", action="store_true", dest="debug", help="Turn on DEBUG mode.") parser.add_argument("--exceptions", action="store_true", dest="exceptions", help="Turn on EXCEPTIONS mode.") args = parser.parse_args(assigned_args) ping3.DEBUG = args.debug ping3.EXCEPTIONS = args.exceptions for addr in args.dest_addr: ping3.verbose_ping(addr, count=args.count, ttl=args.ttl, timeout=args.timeout, size=args.size, interval=args.interval, interface=args.interface)
def run(config): while True: for _host, hostconf in config.hostsconf.items(): ping3.verbose_ping( hostconf.address, count=1, timeout=int(hostconf.timeout)) time.sleep(int(config.main.period))
def test_verbose_ping_bind(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: my_ip = socket.gethostbyname(socket.gethostname()) dest_addr = "example.com" if my_ip == "127.0.0.1" or my_ip == "127.0.1.1": # This may caused by /etc/hosts settings. dest_addr = my_ip # only localhost can send and receive from 127.0.0.1 (or 127.0.1.1 on Ubuntu). ping3.verbose_ping(dest_addr, src_addr=my_ip) self.assertRegex(fake_out.getvalue(), r".*[0-9]+ms.*")
def test_verbose_ping_interval(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: start_time = time.time() ping3.verbose_ping("example.com", interval=1.7) end_time = time.time() self.assertTrue((end_time - start_time) >= 5.1) # time_expect = (count - 1) * interval self.assertFalse('Timeout' in fake_out.getvalue())
def test_verbose_ping_src_addr(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: my_ip = socket.gethostbyname(socket.gethostname()) if my_ip in ( "127.0.0.1", "127.0.1.1"): # This may caused by /etc/hosts settings. dest_addr = my_ip # only localhost can send and receive from 127.0.0.1 (or 127.0.1.1 on Ubuntu). else: dest_addr = DEST_DOMAIN ping3.verbose_ping(dest_addr, src_addr=my_ip) self.assertRegex(fake_out.getvalue(), r".*[0-9]+ms.*")
def test_verbose_ping_interval(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: delay = ping3.ping(DEST_DOMAIN) self.assertTrue( 0 < delay < 0.75 ) # If interval does not work, the total delay should be < 3s (4 * 0.75s) start_time = time.time() ping3.verbose_ping( DEST_DOMAIN, interval=1 ) # If interval does work, the total delay should be > 3s (3 * 1s) end_time = time.time() self.assertTrue((end_time - start_time) >= 3) # time_expect = (count - 1) * interval self.assertNotIn("Timeout", fake_out.getvalue()) # Ensure no timeout
def test_verbose_ping_interface(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: try: route_cmd = os.popen("ip -o -4 route show to default") default_route = route_cmd.read() finally: route_cmd.close() my_interface = default_route.split()[4] try: socket.if_nametoindex( my_interface) # test if the interface exists. except OSError: self.fail("Interface Name Error: {}".format(my_interface)) ping3.verbose_ping(DEST_DOMAIN, interface=my_interface) self.assertRegex(fake_out.getvalue(), r".*[0-9]+ms.*")
def ping(self, count: int, log): lost = 0 all_time = 0 for i in range(count): try: p = 0.0 if log: print('ping', self.ip) p = ping3.verbose_ping(self.ip) print('ping result', self.ip) else: p = ping3.ping(self.ip) p *= 1000 # get as ms #if self.ping_max == PING_MAX: self.ping_max = max(p, self.ping_max) #if self.ping_min == PING_MAX: self.ping_min = min(p, self.ping_min) all_time += p except Exception as ex: if log: print('ping except: ', ex) lost += 1 if lost == count: self.ping_failed() if count == lost: self.ping_avg = PING_MAX else: self.ping_avg = all_time / (count - lost) self.lost_rate = lost / count
def read_zyxel_ping_rxtx(poz_type, name_well, ip_well, ip_poz, ip_obrab, name_base, ippoz_modem, ip_signal, ip_dvr, ip_cam1, ip_cam2, ip_cam3, ip_cam4, ip_ub1, ip_ub2, ip_sbor, analogdvr, ubi_ver): #Speed Время измерения c = 5 average, ml, rx, tx, mrx, mtx, signal, dvr, cam1, cam2, cam3, cam4, ub1, ub2, sbor, ub1amc, ub1amq, ub1signal, ub2amc, ub2amq, ub2signal, mlrx, mltx = -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -100.0, -1.0, -1.0, -100.0, -1.0, -1.0, -1.0, -1.0 #pools={ip_well,ip_dvr,ip_ub1,ip_ub2,ip_sbor,ip_cam1,ip_cam2,ip_cam3,ip_cam4} #Mlcache out1 = mlcache.mlcacheOn(ip_obrab) if (len(out1) == 1 or len(out1) == 2): ml = 2 else: ml = -1 if (len(out1) == 5): ml = 1.8 average = -1 print "mlcache\n" if (poz_type): #Speed poz_br0 rx, tx = tellnet.speed(ip_poz, "5188", int(c)) else: #Speed zyxel # if (name_well == "604"): # tx,rx = zyxel_wan_all.speed_zyxel(ip_poz,"5188",int(c), "213.80.235.178") # else: # tx,rx=zyxel.speed_zyxel(ip_poz,"5188",int(c)) tx, rx = zyxel_wan_all.speed_zyxel(ip_poz, "5188", int(c), "213.80.235.178") mlrx, mltx = zyxel_sngs_port2206.speed_zyxel(ip_poz, "5188", int(c), "213.80.235.178") #tx,rx=-1,-1 print "speed zyxel/poz\n" #Speed poz_modem mrx, mtx = pozmodem.speed(ippoz_modem, "5188", int(c)) print "speed poz\n" #Signal level signal = pozmodemsignal.signal(ip_signal, "5188", int(c)) print "signal poz\n" #Signal Ubi1 ubisignal how connect! ub1signal, ub1amq, ub1amc = ubisignal_ap.ubisignal(ip_ub1, "22", 5, 2, True, ubi_ver) print "ubi1\n" #Signal Ubi2 ub2signal, ub2amq, ub2amc = ubisignal_ap.ubisignal(ip_ub2, "22", 5, 2, False, ubi_ver) print "ubi2\n" threadLock.acquire() #pings #white adrr # average,dvr,ub1,ub2,sbor,cam1,cam2,cam3,cam4 = megamultiping.ping(pools) average = verbose_ping(ip_well) print "ping well\n" #average = megamultiping.ping(ip_well) #ip_well,ip_dvr,ip_ub1,ip_ub2,ip_sbor,ip_cam1,ip_cam2,ip_cam3,ip_cam4) #dvr dvr = verbose_ping(ip_dvr) print "ping dvr\n" #dvr = megamultiping.ping(ip_dvr) #Ubi1_Ap ub1 = verbose_ping(ip_ub1) print "ping ubi1\n" #ub1 = megamultiping.ping (ip_ub1) #Ubi2_Client ub2 = verbose_ping(ip_ub2) print "ping ubi2\n" #ub2 = megamultiping.ping (ip_ub2) #Sbor sbor = verbose_ping(ip_sbor) print "ping sbor\n" #sbor = megamultiping.ping (ip_sbor) #cams if (analogdvr != True): cam1 = verbose_ping(ip_cam1) cam2 = verbose_ping(ip_cam2) cam3 = verbose_ping(ip_cam3) cam4 = verbose_ping(ip_cam4) print "ping cams\n" # cam1 = megamultiping.ping (ip_cam1) # cam2 = megamultiping.ping (ip_cam2) # cam3 = megamultiping.ping (ip_cam3) # cam4 = megamultiping.ping (ip_cam4) else: if (dvr > 0): #DO TEST ANALOG CAMS! cam1 = badanalogcam.check_crash_cam("/var/www/html/mon/poz/" + name_well + "_1.jpg") cam2 = badanalogcam.check_crash_cam("/var/www/html/mon/poz/" + name_well + "_2.jpg") cam3 = badanalogcam.check_crash_cam("/var/www/html/mon/poz/" + name_well + "_3.jpg") cam4 = badanalogcam.check_crash_cam("/var/www/html/mon/poz/" + name_well + "_4.jpg") # cam1=1 # cam2=1 # cam3=1 # cam4=1 threadLock.release() # #Текущее время timestamp = int(time.time()) + 60 * 60 * 4 db_name = name_base db = MySQLdb.connect(host="127.0.0.1", user="******", passwd="goodman1978", db="pozitron", charset='utf8') cursor = db.cursor() sql = "INSERT INTO " + db_name + "(date, value, rx, tx, ml, mrx, mtx, sigpoz, dvr, cam1, cam2, cam3, cam4, ub1, ub2, sbor, ub1amc, ub1amq, ub1sig, ub2amc, ub2amq, ub2sig, mlrx, mltx) VALUE (" + str( timestamp) + "," + str(average) + "," + str(rx) + "," + str( tx) + "," + str(ml) + "," + str(mrx) + "," + str(mtx) + "," + str( signal) + "," + str(dvr) + "," + str(cam1) + "," + str( cam2) + "," + str(cam3) + "," + str(cam4) + "," + str( ub1) + "," + str(ub2) + "," + str(sbor) + "," + str( ub1amc) + "," + str(ub1amq) + "," + str( ub1signal) + "," + str(ub2amc) + "," + str( ub2amq) + "," + str(ub2signal) + "," + str( mlrx) + "," + str(mltx) + ")" print sql cursor.execute(sql) db.commit() db.close()
print("The colour will change too if things get bad.") print( "The idea is that you don't have to keep looking at the screen to know how the network is doing" ) try: while True: for x in range(len(pingTargets)): ip = pingTargets[x] print(Back.WHITE + "Target", x + 1) val = verbose_ping(ip, interval=0.5, count=3) if ping(ip) == None: print(Fore.RED + Back.BLACK + "WARNING! ENTIRE SWITCH IS DOWN!") #mixer.Sound.play(malf_sound) print(Style.RESET_ALL) else: try: #this is because sometimes it wasn't working snapshot = ping(ip) * 1000 except: snapshot = 42 #this is my favorite number print("Oooops")
def test_verbose_ping_count(self): with patch('sys.stdout', new=io.StringIO()) as fake_out: ping3.verbose_ping('example.com', count=1) self.assertRegex(fake_out.getvalue(), r'.*[0-9]+ms.*')
msg = input('') msg = bytes(msg, 'utf8') #http://condor.depaul.edu/sjost/lsp121/documents/ascii-npr.htm try: while msg != '\x11': verif = msg.decode('utf8') if verif == 'ping' or verif == 'Ping': print('----') print('Ping|') print('------------') ping_alvo = str(ping('127.0.0.1', unit='ms', size=56)) print(ping_alvo) verbose_ping_alvo = verbose_ping('127.0.0.1', count=4) verbose_ping_alvo = str(verbose_ping_alvo).replace( 'None', '------------') print(verbose_ping_alvo) break elif verif == 'perda de pacote' or verif == 'perda de pacotes': print('-----------------------') print('Perda de Pacote (Teste)|') print('-----------------------') x = 0 int(x) while True: x += 1
def test_verbose_ping_timeout_exception(self): with patch("sys.stdout", new=io.StringIO()): with patch("ping3.EXCEPTIONS", True): with self.assertRaises(errors.Timeout): ping3.verbose_ping("example.com", timeout=0.0001)
def test_verbose_ping_unit(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: ping3.verbose_ping("example.com", unit="ms") self.assertRegex(fake_out.getvalue(), r".*[0-9]+ms.*")
def test_verbose_ping_ttl_exception(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: ping3.verbose_ping("example.com", ttl=1) self.assertRegex(fake_out.getvalue(), r".*Timeout.*")
import ping3 from errors import PingError from ping3 import verbose_ping ping3.EXCEPTIONS = True try: verbose_ping("192.168.0.1") except PingError as Ex: print("Error")
def test_verbose_ping_timeout_exception(self): with patch("ping3.EXCEPTIONS", True): with self.assertRaises(ping3.errors.Timeout): ping3.verbose_ping(DEST_DOMAIN, timeout=0.0001)
def test_verbose_ping_size_exception(self): with self.assertRaises(OSError): ping3.verbose_ping(DEST_DOMAIN, size=99999)
def test_verbose_ping_size(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: ping3.verbose_ping(DEST_DOMAIN, size=100) self.assertRegex(fake_out.getvalue(), r".*[0-9]+ms.*")
def test_verbose_ping_count(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: ping3.verbose_ping("example.com", count=1) self.assertEqual(fake_out.getvalue().count("\n"), 1)
"Welcome to A86 Configurator\n Please choose an option \n 1. Add Target \n 2. Delete Target" "\n 3. Add Email to notify \n 4. Add Sender Email \n 5. Set Password\n 6. Sender Email\n 7. Delete Receipient\n" " 8. Set Outgoing Email Server\n")) print("Test") if menu == 1: more = True while more: more = False target_name = input( "Please input target name. This is what the monitored target will be referred to in emails!\n" ) ip = input( "Please input the IP of the target that will be pinged. If you havent set this to a static IP. You should" " do this before setting it here!\n") try: verbose_ping(ip) addTarget(target_name, ip) doMore = input( "Added Task, do you want to add another target? Use Y for Yes and N for No\n" ) if doMore.lower() == "y": more = True except PingError as Ex: print("Was not able to ping target with IP " + ip + " could not add target") elif menu == 2: while more: more = False if len(monitordata["targets"]["target-list"]) == 0: print("There are no targets configured") else:
这里推荐大家几个挺不错的 ping 模块。 ping3 代码地址:https://github.com/kyan001/ping3 功能很强大,使用简单,缺点也比较明显——需要 root 权限。 Note that ICMP messages can only be sent from processes running as root. 需要 root 权限运行的 process 才能发送 ICMP 数据。 >>> from ping3 import ping, verbose_ping >>> ping('example.com') # Returns delay in seconds. 0.215697261510079666 >>> verbose_ping('example.com') # Ping 4 times in a row. ping 'example.com' ... 215ms ping 'example.com' ... 216ms ping 'example.com' ... 219ms ping 'example.com' ... 217ms 1 2 3 4 5 6 7 8 9 MultiPing 代码地址:https://github.com/romana/multi-ping/
from ping3 import ping, verbose_ping regionIP = { "NA": "104.160.131.3", "EUW": "104.160.141.3", "EUNE": "104.160.142.3", "OCE": "104.160.156.1", "LAN": "104.160.136.3", } while True: choice = input( "Which server would you like?:\n1. NA\n2. EUW\n3. EUNE\n4. OCE\n5. LAN\n\n" ) if choice in ['1', '2', '3', '4', '5']: break # process the input if choice == '1': verbose_ping(regionIP.get("NA"), timeout=10, count=16) elif choice == '2': verbose_ping(regionIP.get("EUW"), timeout=10, count=16) elif choice == '3': verbose_ping(regionIP.get("EUNE"), timeout=10, count=16) elif choice == '4': verbose_ping(regionIP.get("OCE"), timeout=10, count=16) elif choice == '5': verbose_ping(regionIP.get("LAN"), timeout=10, count=16)
def test_verbose_ping_timeout(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: ping3.verbose_ping("example.com", timeout=0.0001) self.assertRegex(fake_out.getvalue(), r".*Timeout \> [0-9\.]+s.*")
passwd="goodman1978", db="pozitron", charset='utf8') cursor = db.cursor() sql = "INSERT INTO " + db_name + "(date, value, rx, tx, ml, mrx, mtx, sigpoz, dvr, cam1, cam2, cam3, cam4, ub1, ub2, sbor) VALUE (" + str( timestamp) + "," + str(average) + "," + str(rx) + "," + str( tx) + "," + str(ml) + "," + str(mrx) + "," + str(mtx) + "," + str( signal) + "," + str(dvr) + "," + str(cam1) + "," + str( cam2) + "," + str(cam3) + "," + str(cam4) + "," + str( ub1) + "," + str(ub2) + "," + str(sbor) + ")" cursor.execute(sql) db.commit() #8888 average8888 = verbose_ping('8.8.8.8') #62.220.55.149 average62220 = verbose_ping('62.220.55.149') #80.247.113.226 average8084 = verbose_ping('80.247.113.226') #192.168.77.3 average773 = verbose_ping('192.168.77.3') #31.173.187.210 average3117 = verbose_ping('31.173.187.210') #Текущее время timestamp = int(time.time()) + 60 * 60 * 4
def test_verbose_ping_size(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: ping3.verbose_ping("example.com", size=100) self.assertRegex(fake_out.getvalue(), r".*[0-9]+ms.*") with self.assertRaises(OSError): ping3.ping("example.com", size=9999)
def read_zyxel_ping_rxtx(poz_type, name_well, ip_well, ip_poz, ip_obrab, name_base, ippoz_modem, ip_signal, ip_dvr, ip_cam1, ip_cam2, ip_cam3, ip_cam4, ip_ub1, ip_ub2, ip_sbor, analogdvr): #Speed Время измерения c = 10 rx, tx, mrx, mtx, signal, dvr, cam1, cam2, cam3, cam4, ub1, ub2, sbor = -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0 #Mlcache out1 = mlcache.mlcacheOn(ip_obrab) if (len(out1) == 1): ml = 2 else: ml = -1 if (len(out1) == 5): ml = 1.8 average = -100 if (poz_type): #Speed poz_br0 rx, tx = tellnet.speed(ip_poz, "5188", int(c)) else: #Speed zyxel tx, rx = zyxel.speed_zyxel(ip_poz, "5188", int(c)) #Speed poz_modem mrx, mtx = pozmodem.speed(ippoz_modem, "5188", int(c)) #Signal level signal = pozmodemsignal.signal(ip_signal, "5188", int(c)) #white adrr average = verbose_ping(ip_well) #dvr dvr = verbose_ping(ip_dvr) #cams if (analogdvr != True): cam1 = verbose_ping(ip_cam1) cam2 = verbose_ping(ip_cam2) cam3 = verbose_ping(ip_cam3) cam4 = verbose_ping(ip_cam4) else: if (dvr > 0): #DO TEST ANALOG CAMS! cam1 = 1 cam2 = 1 cam3 = 1 cam4 = 1 #Ubi1_Ap ub1 = verbose_ping(ip_ub1) #Ubi2_Client ub2 = verbose_ping(ip_ub2) #Sbor sbor = verbose_ping(ip_sbor) # #Текущее время timestamp = int(time.time()) + 60 * 60 * 4 db_name = name_base db = MySQLdb.connect(host="127.0.0.1", user="******", passwd="goodman1978", db="pozitron", charset='utf8') cursor = db.cursor() sql = "INSERT INTO " + db_name + "(date, value, rx, tx, ml, mrx, mtx, sigpoz, dvr, cam1, cam2, cam3, cam4, ub1, ub2, sbor) VALUE (" + str( timestamp) + "," + str(average) + "," + str(rx) + "," + str( tx) + "," + str(ml) + "," + str(mrx) + "," + str(mtx) + "," + str( signal) + "," + str(dvr) + "," + str(cam1) + "," + str( cam2) + "," + str(cam3) + "," + str(cam4) + "," + str( ub1) + "," + str(ub2) + "," + str(sbor) + ")" cursor.execute(sql) db.commit()
def test_verbose_ping_bind(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: my_ip = socket.gethostbyname(socket.gethostname()) ping3.verbose_ping("example.com", src_addr=my_ip) self.assertRegex(fake_out.getvalue(), r".*[0-9]+ms.*")
from ping3 import verbose_ping ping3.EXCEPTIONS = True stop = False targets = None failed_targets = [] print("A86Monitor V1.1") with open("monitor.json", "r") as jsonFile: monitordata = json.load(jsonFile) jsonFile.close() targets = monitordata["targets"] while not stop: for target in targets["target-list"]: try: verbose_ping(monitordata["targets"][target]["ip"], count=10) try: index = failed_targets.index(target) failed_targets.remove(target) sendRestoredEmail(email, target, monitordata["sender"], monitordata["password"], monitordata["sender-name"], monitordata["sender-server"], monitordata["sender-port"]) except KeyError: print("Target not found") except ValueError: print("Target not found") except PingError as Ex: try: