def plugin_read(self): result = False if self.initialized and self.enabled and self.readinprogress == 0: self.readinprogress = 1 try: reply = ping(self.taskdevicepluginconfig[0], timeout=0.5, unit="ms") except Exception as e: reply = None # print(e) if reply is None or reply == False: # second try try: reply = ping(self.taskdevicepluginconfig[0], timeout=1, unit="ms") except Exception as e: reply = None # print(e) if reply is None or reply == False: res = 0 else: res = 1 # print(reply,res) self.set_value(1, res, True) self._lastdataservetime = rpieTime.millis() result = True self.readinprogress = 0 return result
async def monitor_uptime(): await bot.wait_until_ready() channel = bot.get_channel(config['notification_channel']) while not bot.is_closed(): for i in servers: if ping(i["address"]) is None: if not i["address"] in currently_down: currently_down.append(i["address"]) embed = discord.Embed( title='**{0} is down!**'.format(i['name']), description='Error pinging {0} <@&{1}>'.format( i['address'], config['role_to_mention']), color=discord.Color.red()) await channel.send(embed=embed) else: if i["address"] in currently_down: embed = discord.Embed( title='**{0} is now up!**'.format(i['name']), description='Successfully pinged {0} <@&{1}>'.format( i['address'], config['role_to_mention']), color=discord.Color.green()) await channel.send(embed=embed) currently_down.remove(i["address"]) else: if config['always_notify'] is True: await channel.send( 'Received response from {0} in: '.format( i['address']) + str(int(ping(i['address'], unit='ms'))) + 'ms') await asyncio.sleep(config['secs_between_ping'])
def home(request): """ Returns render data for home screen. Will ping router and TFTP server and send status to home template. Also sends user info to home template. """ if request.method == 'GET' and request.user.id: current_user = request.user current_netbuddy_user = NetBuddyUser.objects.get( user_id=current_user.id) router_ping_info = ping(current_netbuddy_user.current_router_ip) if current_netbuddy_user.tftp_ip is not None: tftp_ping_info = ping(current_netbuddy_user.tftp_ip) else: tftp_ping_info = None template = 'home.html' context = { 'router_ping_info': router_ping_info, 'tftp_ping_info': tftp_ping_info, 'current_netbuddy_user': current_netbuddy_user } return render(request, template, context) elif request.method == 'GET': template = 'home.html' context = {} return render(request, template, context)
def ping(self): """ Pings host address and records latency and losses. :return: average latency, nested list with individual latency values, total losses, nested list with individual losses, if host resolution failed """ print("[INFO]: Starting PING test...") scans = [ping3.ping(self.host, timeout = 10, size = 64, unit = "ms"), ping3.ping(self.host, timeout = 10, size = 64, unit = "ms"), ping3.ping(self.host, timeout = 10, size = 64, unit = "ms"), ping3.ping(self.host, timeout = 10, size = 64, unit = "ms")] if False in scans: return [None, [None, None, None, None], 4, [True, True, True, True], True] else: result = [0, [scans[0], scans[1], scans[2], scans[3]], 0, [False, False, False, False], None] if scans[0] is None: result[1][0] = 0 result[2] += 1 result[3][0] = True elif scans[1] is None: result[1][1] = 0 result[2] += 1 result[3][1] = True elif scans[2] is None: result[1][2] = 0 result[2] += 1 result[3][2] = True elif scans[3] is None: result[1][3] = 0 result[2] += 1 result[3][3] = True pass result[0] = (result[1][0] + result[1][1] + result[1][2] + result[1][3])/4 print("[INFO]: PING test complete.") return result pass
async def monitor_uptime(self) -> None: """Checks the status of each server and sends up/down notifications""" await self.bot.wait_until_ready() channel = self.bot.get_channel(get_config("notification_channel")) for i in get_servers(): if i["type"] == "ping": if ping(i["address"]) is False: await self.notify_down(i, channel, "Host unknown") elif ping(i["address"]) is None: await self.notify_down(i, channel, "Timed out") else: await self.notify_up(i, channel) else: address = i["address"] timeout = get_config("http_timeout") if not address.startswith("http"): address = f"http://{address}" async with aiohttp.ClientSession( timeout=aiohttp.ClientTimeout(total=timeout) ) as session: try: async with session.get(address) as res: if res.ok: await self.notify_up(i, channel) else: await self.notify_down(i, channel, res.reason) except asyncio.TimeoutError: await self.notify_down(i, channel, "Timed out") except aiohttp.ClientError: await self.notify_down(i, channel, "Connection failed")
def checkNode(ip, port): if verbose: print("CHECKING", ip, port) state = "down" fail = True if port != 0: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.connect((ip, port)) state = "up" fail = False except: state = "down" fail = True if fail: res = ping(ip, timeout=1) res = ping(ip, timeout=2) if res == None: state = 'down' else: state = 'up' return state
def monitor(): while True: print("loop") router = ping("192.168.1.1") cloudflare = ping("1.1.1.1") timeData = datetime.datetime.now().replace(microsecond=0).isoformat() if router == None: routerSuccess = "False" router = 10000 else: routerSuccess = "True" if cloudflare == None: cloudflareSuccess = "False" cloudflare = 10000 else: cloudflareSuccess = "True" vars.cloudflarePing = cloudflare * 1000 data = [ str(timeData), routerSuccess, router * 1000, cloudflareSuccess, cloudflare * 1000 ] try: with open("export.csv", "a") as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(data) time.sleep(5) except: pass
def test_ping_hostunknown(self): not_exist_url = "not-exist.com" with patch("sys.stdout", new=io.StringIO()) as fake_out: ping3.ping(not_exist_url) self.assertRegex( fake_out.getvalue(), r"Cannot resolve {}: Unknown host".format(not_exist_url))
def main(argv): # try permission try: ping('8.8.8.8', timeout=1) except PermissionError: print('you need root privileges') try: opts, args = getopt.getopt(argv, "p:") except getopt.GetoptError: how_to_use() sys.exit(2) for opt, arg in opts: if opt == '-p': ips = str(arg).split("-") ip_to = ipaddress.IPv4Address(ips.pop()) ip_from = ipaddress.IPv4Address(ips.pop()) ping_scan(ip_from, ip_to) #send_report(ipaddress.IPv4Address(argv[2])) send_sftp(ipaddress.IPv4Address(argv[2])) sys.exit(0) how_to_use() sys.exit(0)
def test_ping_size(self): delay = ping3.ping("example.com", size=100) self.assertIsInstance(delay, float) with self.assertRaises(OSError): ping3.ping( "example.com", size=9999 ) # most router has 1480 MTU, which is IP_Header(20) + ICMP_Header(8) + ICMP_Payload(1452)
def main(): global _verbose print(ping('10.10.10.10')) print(ping('192.168.205.10')) try: opts, args = getopt.getopt(sys.argv[1:], "i:c:vh", ["help", "verbose"]) except getopt.GetoptError as err: # print help information and exit: print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for o, a in opts: if o in ("-v", "--verbose"): _verbose += 1 elif o in ("-h", "--help"): usage() sys.exit() # elif o in ("-i"): # IPAddress = a else: assert False, "unhandled option" # read fromDB deviceList = readDB() # ping to each device workersPing(deviceList) sys.exit()
def ping_test(ip): delay = [] delay.append(ping(ip,unit="ms")) delay.append(ping(ip,unit="ms")) delay.append(ping(ip,unit="ms")) delay = [x for x in delay if x != None] if len(delay) ==0: return "timeout" else: return int(numpy.mean(delay))
def is_internet_up(): '''Return True if any host in TARGET_HOSTS responds to a ping, or False if not''' for host in TARGET_HOSTS: try: ping3.ping(host, timeout=PING_TIMEOUT) return True except PermissionError: sys.exit('pingmon: must run as root') except: continue # Ping failed, try next host return False
def pingSV(ip: str, t: int = 0): if t: pingD = {"max": None, "min": None, "avg": None, "times": []} for i in range(t): pingD["times"].append(ping(ip, unit="ms")) pingD["max"] = max(pingD["times"]) pingD["min"] = min(pingD["times"]) pingD["avg"] = sum(pingD["times"]) / len(pingD["times"]) return pingD else: return ping(ip, unit="ms")
def ping_request(): # pings the two hostnames result_internet = ping3.ping(hostname_internet, unit='ms', timeout=timeout, ttl=64, size=32) result_router = ping3.ping(hostname_router, unit='ms', timeout=timeout, ttl=64, size=32) return result_internet, result_router
def ping_check(): """ ping Google.com as a somewhat reliable source for checking whether internet connection is still active, though any website could be substituted here :return: the final result of the check sequence """ loop = 0 r = ping3.ping('google.com') # loops though checks several times in case the connection loss is only a brief one while r is None and loop < 4: time.sleep(20) r = ping3.ping('google.com') loop += 1 return r
async def monitor_uptime(self): await self.bot.wait_until_ready() channel = self.bot.get_channel(cfg.config['notification_channel']) for i in cfg.servers: if ping(i["address"]) is False: await notify_down(i['name'], i["address"], channel, "Host unknown") elif ping(i["address"]) is None: await notify_down(i['name'], i["address"], channel, "Timed out") else: await notify_up(i['name'], i["address"], channel)
def pinger(ipaddr: str) -> str: ip = 110 + int(ipaddr) ping_mag = ping('192.168.100.{ip}'.format(ip=ip)) if type(ping_mag) == float: return "MAG на месте!" else: return "Караул, приставку сперли!))"
def checking(ipaddr): global winver, winver10 os.system('cls') # First string in output will be host response (by ICMP ping). print(colored('IP-address: ','green')+ipaddr) print('Status:') response = ping(ipaddr) if response == None: # If user is not responding => exit to starting point if winver10 in winver: os.system('cls') print(colored('IP-address: ','green')+ipaddr) print('Status: ' + colored('OFFLINE', 'red')) time.sleep(3) exiting_count() else: os.system('cls') print('IP-address: ' + ipaddr) print(ipaddr+' - ' + 'OFFLINE') time.sleep(2) exiting_count() else: #Okay. Host is online. Lets type it to user os.system('cls') if winver10 in winver: print(colored('IP-address: ','green')+ipaddr) print('Status:' + colored(' ONLINE', 'green')) else: print("Status: ONLINE") LM_checkin(ipaddr) # Going to check his opened sockets for remote admin soft
def read_xls(): # 获取文件对象 wb2 = load_workbook('摄像头ip.xlsx') # 通过工作表名获取到工作表对象 ws = wb2['Sheet1'] i = 1 fail_list = [] success_list = [] for row in ws.rows: ip = row[0].value print(ip) res = ping(ip) if res: success_list.append(ip) ws.cell(i, 2, 'ok') else: fail_list.append(ip) ws.cell(i, 2, 'fail') i += 1 # if i > 100: # break wb2.save('检测结果.xlsx') wb2.close() print('fail_list:', fail_list) print('success_list:', success_list)
def csv_option(): csv_name = input("\nWhat is the name of your CSV file?: ") with open(csv_name, "r") as read_obj: csv_reader = reader(read_obj) list_of_rows = list(csv_reader) # print(list_of_rows) rows = len(list_of_rows) # print(rows) while rows >= 2: rows = rows - 1 # print(list_of_rows[rows][0]) ip = list_of_rows[rows][0] ip_ping = ping(ip) if ip_ping == None: fileName = "downDevices_" + dt_string + ".txt" downDeviceOutput = open("Output-Configs/" + fileName, "a") downDeviceOutput.write(str(ip) + "\n") # print(str(ip) + " IS DOWN!") else: get_saved_config( list_of_rows[rows][0], list_of_rows[rows][1], list_of_rows[rows][2], list_of_rows[rows][3], )
def fetch_mirror(): mirror_file = "./mirrors.txt" if os.path.isfile(mirror_file) == False: print("Mirror file not detected...") bestmirror.get_best_mirrors() # Get mirrors from textfile and it starts rsync if ping goes well f = open(mirror_file, 'r') for mirror in f: mirror = mirror.replace("\n", "") url = mirror base_url = "{0.netloc}".format(urlsplit(url)) p = ping(base_url, unit='ms') if p is None: print("Error fetching mirror {mirror}".format(mirror=mirror)) pass if p is not None: print("Fetching latest packages from : {mirror}".format( mirror=mirror)) os.system( "rsync -rtlvH --delete-after --delay-updates --safe-links {mirror} {path}" .format(mirror=mirror, path="./mirror")) break print("Mirror updated successfully!")
def ping(index): while _run: delay = ping3.ping(servers[index]["host"]) if not _run: break servers[index]["delay"] = int(delay * 1000) if not _run: break time.sleep(0.5)
def test_ping_bind(self): 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). delay = ping3.ping(dest_addr, src_addr=my_ip) self.assertIsInstance(delay, float)
def run_ping(target_address): try: ping_output = ping3.ping(target_address) except OSError: ping_output = None return ping_output
def testPing(address): print('ping address: ', address) pingResult = ping(address) if pingResult: return address else: return None
def calc_fastest_ip(self): self.timestamp = datetime.now().timestamp() min_latency = 999999 self.ip = None for k, v in self.ip_to_nameserver.items(): try: tmp_len = ping3.ping(k, timeout=1) except OSError: tmp_len = None if tmp_len is None: tmp_len = 999999 if k not in self.ip_to_latency: self.ip_to_latency[k] = round(tmp_len * 1000, 2) else: self.ip_to_latency[k] = self.ip_to_latency[k] + round( tmp_len * 1000, 2) self.ip_to_latency[k] /= 2 self.ip_to_latency[k] = round(self.ip_to_latency[k], 2) if min_latency >= self.ip_to_latency[k]: min_latency = self.ip_to_latency[k] self.ip = k if self.ip is None: print(f"{self.hostname:15}: fk GFW") else: print( f"{self.hostname:15}: best ip: {self.ip}, latency: {self.ip_to_latency[self.ip]}" )
def test_if_real(email): temp = str(email).split("@") link = str(temp[1]) if ping(link): return False else: return True
def checkhost(sqlhost, ipv6): """check the socket on the other nodes""" sqlhostname = reverse_lookup(sqlhost) print("\nChecking socket on {} ...".format(sqlhostname)) if ipv6: mping = MultiPing([sqlhost]) mping.send() _, no_responses = mping.receive(1) else: no_responses = None ping_response = ping3.ping(sqlhost, timeout=2) if not ping_response: no_responses = True if no_responses: print("{}Skipping {}: ping failed{}".format(RED, sqlhostname, WHITE)) OTHER_WSREP.remove(sqlhost) else: cnx_sqlhost = None try: cnx_sqlhost = MySQLdb.connect( user='******', passwd=CREDENTIALS["monitor"], unix_socket='/var/lib/mysql/mysql.sock', host=sqlhost) except Exception: #pylint: disable=W0703 print("{}Skipping {}: socket is down{}".format( YELLOW, sqlhostname, WHITE)) OTHER_WSREP.remove(sqlhost) else: print("{}Socket on {} is up{}".format(GREEN, sqlhostname, WHITE)) finally: if cnx_sqlhost: cnx_sqlhost.close()
def test_availability(self): """ Using ping command to test availability of this server, then add results to self.availability: list. :return: Bool Type: True if test success, else False. """ logger.info(f"Testing server availability: {self.__repr__()}") # if host unknown, return False # if timeout, return None # if success, return delay in ms response = ping(f"{self.serverIP}", unit="ms") if not response: logger.info( f"Testing server availability failed: unknown host {self.__repr__()}" ) self.availability.append(ServerInfo(False, 0, time.time())) return False elif response is None: logger.info( f"Testing server availability failed: timeout {self.__repr__()}" ) self.availability.append(ServerInfo(False, 0, time.time())) return False else: logger.info( f"Testing server availability success: server {self.__repr__()}, time {response}ms" ) self.availability.append(ServerInfo(True, response, time.time())) return True
def ifping(ipaddress): #检查IP地址是否连通 result=ping( ipaddress) return result