def is_nas_online(self, nas_ip): self.nas_ip = nas_ip ping_response = ping.quiet_ping(self.nas_ip, count=1) if ping_response[0] != 0: time.sleep(5) ping_response2 = ping.quiet_ping(self.nas_ip, count=1) if ping_response2 != 0: temp = "It seems that the server, {}, is offline.".format(self.nas_ip) log.add(temp) return False else: self.isonline = True temp = "The server, {}, is online.".format(self.nas_ip) log.add(temp) return True
def getserverstatus(file, output): html_fp = open(output, 'w') now = datetime.datetime.now() html_fp.write("""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n <meta http-equiv=Content-Type content="text/html;charset=us-ascii">\n <meta http-equiv="refresh" content="5" >\n <head>Lab Server Status Report</head>\n <body style="font-family:Verdana,Tahoma,sans-serif">\n """) html_fp.write("<h3>"+now.strftime("%Y-%m-%d %H:%M")+"</h3>\n") html_fp.write("<table border=1>\n<tr style=font-weight:bold><td>Server Address</td><td>Comments</td><td>Status</td></tr>\n") server_list = readserverlist(file) if len(server_list) > 0: for ip in sorted(server_list.keys()): ping_result = ping.quiet_ping(ip) if ping_result[0] == 0: html_fp.write("<tr><td>"+ip+"</td><td>"+server_list[ip]+"</td><td><span style='color: green'>Connected</span></td></tr>\n") elif ping_result[0] < 50: html_fp.write("<tr><td>"+ip+"</td><td>"+server_list[ip]+"</td><td><span style='color: yellow'>Unstable</span></td></tr>\n") elif ping_result[0] < 100: html_fp.write("<tr><td>"+ip+"</td><td>"+server_list[ip]+"</td><td><span style='color: orange'>Slow</span></td></tr>\n") else: html_fp.write("<tr><td>"+ip+"</td><td>"+server_list[ip]+"</td><td><span style='color: red'>Disconnected</span></td></tr>\n") else: html_fp.write("<tr><td></td><td></td><td></td></tr>\n") html_fp.write("</table>\n</body>")
def is_server_available(): install_ping() import ping lost_packet_percent = ping.quiet_ping(REPO_SERVER, timeout=3, count=5)[0] return lost_packet_percent < 50
def device_is_present(host, tries=3, timeout=3): """ Determines whether a device is present on the network using its IP address or hostname. If the device can be pinged successfully, it will return True, and False otherwise. Winston needs to run as root to use this function, since ICMP pings need root to run. That is even true for the ping command, so there is no way to circumvent this. See this post for details: http://stackoverflow.com/questions/1189389/python-non-privileged-icmp :param host: hostname or IP address :param tries: number of tries before giving up :param timeout: timeout in seconds """ try: response = ping.quiet_ping(host, tries, timeout) # Returns true if more than 0% of packets were returned return (response[0] > 0) except: return False
def gen_json(outfile): output = [] for h in hosts: lost, _, rtt = ping.quiet_ping(h["hostname"]) status = lost is not 100 services = [] for s in h["services"]: if s["type"] == "port": c = PortServiceChecker(h["hostname"], s["port"]) elif s["type"] == "ssh": c = SSHServiceChecker(h["hostname"], s["port"], s["key"]) s_up = c.do() services += [{ "name": s["name"], "up": s_up }] if not s_up: status = False output += [{ "hostname": h["hostname"], "status": status, "latency": rtt, "services": services, }] open(outfile, "w+").write(json.dumps(output))
def get_host(ip_addr): """ test ip is connected to port 443 and get ping message """ try: headers='' requests.get('https://' + ip_addr, timeout=2) return -2 except SSLError as e: name_list = [] ping_list = ping.quiet_ping(ip_addr) ping_artt = ping_list[2] ping_lost = ping_list[0] ping_value = ['delay: %.5sms, lost: %s%%' % (ping_artt, ping_lost), ping_artt] if "', '" in str(e): name_list = str(e).split("', '") name_list[0] = name_list[0].split("'")[-1] name_list[-1] = name_list[-1].split("'")[0] # print ip_addr + '\n' return [name_list, ip_addr, ping_value] elif 'match' in str(e): temp_list = str(e).split("'") name_list.append(temp_list[-2]) # print ip_addr return [name_list, ip_addr, ping_value] return e except Timeout: # print ip_addr + ' time out' return -3 except Exception as e: # print ip_addr + '\n' + str(e) return -4
def run_a_ping_and_graph(): # graphs are global so that can be retained across multiple calls to this callback global g_my_globals #===================== Do the ping =====================# response = ping.quiet_ping('google.com', timeout=1000) if response[0] == 0: ping_time = 1000 else: ping_time = response[0] #===================== Store current ping in historical array =====================# g_my_globals.ping_x_array.append(len(g_my_globals.ping_x_array)) g_my_globals.ping_y_array.append(ping_time) # ===================== Only graph last 100 items =====================# if len(g_my_globals.ping_x_array) > 100: x_array = g_my_globals.ping_x_array[-100:] y_array = g_my_globals.ping_y_array[-100:] else: x_array = g_my_globals.ping_x_array y_array = g_my_globals.ping_y_array # ===================== Call graphinc functions =====================# # clear before graphing g_my_globals.axis_ping.clear() # graph the ping values g_my_globals.axis_ping.plot(x_array, y_array)
def main(): hostname = socket.gethostname() p_timeout = max(int(math.floor(PINTERVAL / PCOUNT)), 1) # Communications handler out_q = Queue() proc = Process(target=xmit, args=(out_q, )) proc.start() # proc.join() # Start reporting thread # This is the ping and bw thread # Start all the pings at a random offset to reduce collisions on reboot next_ping = utcnow().timestamp + PINTERVAL next_bw = utcnow().timestamp + BINTERVAL * 60 p_seqn = 0 b_seqn = 0 while True: modem_usage = get_modem_usage() t_now = utcnow().timestamp next_ping = t_now + PINTERVAL res = ping.quiet_ping(SERVERNAME, count=PCOUNT, timeout=p_timeout) res = ('ping', hostname, p_seqn, t_now) + res + (modem_usage, ) res = dict( list( zip(('parm', 'hostname', 'seqn', 'ts', 'fail_pcnt', 'max', 'avg', 'modem_MB_used'), res))) print res enqueue(out_q, res, timeout=max(p_timeout, 1)) p_seqn += 1 t_stop = utcnow().timestamp # Also test BW if t_stop >= next_bw: next_bw = t_stop + BINTERVAL * 60 res = test_bw(SERVERNAME, size_bytes=BWSIZE, timeout=PINTERVAL) res = ('band', hostname, modem_usage, b_seqn, t_stop) + res + (modem_usage, ) res = dict( list( zip(('parm', 'hostname', 'seqn', 'ts', 'fail_pcnt', 'max', 'avg', 'modem_MB_used'), res))) enqueue(out_q, res) b_seqn += 1 sys.stdout.write('*') # Wait until next ping test sys.stdout.write('.') if t_stop >= next_bw: sys.stdout.write('*') sys.stdout.flush() t_end = utcnow().timestamp if t_end < next_ping: time.sleep(next_ping - t_end)
def auto_add_record(domain_name, region, username): zone = ZoneRecordDal.select_zone(domain_name) # Select an unsed ip if @domain name has no records existed. records = IpPool.query.outerjoin(DnsRecord, DnsRecord.record == IpPool.fixed_ip).add_columns( IpPool.fixed_ip, DnsRecord.record).filter(IpPool.region == region, DnsRecord.record.is_(None), IpPool.allocated.is_(True)).order_by(IpPool.fixed_ip) for item in records: ip = item.fixed_ip # By sending 8 icmp packets with 64 bytes to this ip within 0.1 second, # we can probably make sure if an ip is alive. # If this ip does not answer any pings in 0.2 second, it will be presumed to be unused. if CONF.etc.env != 'dev' and quiet_ping(ip, 0.1, 8, 64)[0] != 100: IpPool.query.filter_by(fixed_ip=ip).update({'allocated': False}) log.error("%s should have been set allocated=False since it is ping-able." % ip) continue with db.session.begin(subtransactions=True): try: iprecord = IpPool.query.filter_by(fixed_ip=ip).with_for_update(nowait=True, of=IpPool) except Exception: log.error("%s has been locked by other process" % ip) continue if DnsRecord.query.filter_by(record=ip).first(): continue insert_record = DnsRecord(domain_name=domain_name, record=ip, zone_name=zone, update_user=username, record_type='A') db.session.add(insert_record) return ZoneRecordDal.increase_serial_num(zone) else: raise BadParam("No unused ip for region:%s." % region, msg_ch=u'没有可用的ip')
def ping_idc(): result = {} addr = ['182.18.40.229', '182.18.40.223', '182.18.40.253'] for ip in addr: percent = ping.quiet_ping(ip)[0] result[ip] = percent return result # {'182.18.40.227': 0, '182.18.40.229': 100, '182.18.40.252': 0}
def get_host(ip_address): """ test ip is connected to port 443 """ try: headers='' requests.get('https://' + ip_address, timeout=2) return -2 except SSLError as e: name_list = [] ping_artt = ping.quiet_ping(ip_address)[2] if "', '" in str(e): name_list = str(e).split("', '") name_list[0] = name_list[0].split("'")[-1] name_list[-1] = name_list[-1].split("'")[0] # print ip_address + '\n' return [name_list, ip_address, ping_artt] elif 'match' in str(e): temp_list = str(e).split("'") name_list.append(temp_list[-2]) # print ip_address return [name_list, ip_address, ping_artt] return e except Timeout: # print ip_address + ' time out' return -3 except Exception as e: # print ip_address + '\n' + str(e) return -4
def getStatut(self, hostname, refresh=False): if refresh and self.has_key(hostname): del self[hostname] if not self.has_key(hostname): on_off = (ping.quiet_ping(hostname, count=2)[1] is None) self[hostname] = ("on", "off")[on_off] return self[hostname]
def getStatut( self, hostname, refresh=False ): if refresh and self.has_key( hostname ): del self[ hostname ] if not self.has_key( hostname ): on_off = ( ping.quiet_ping( hostname, count=2 )[ 1 ] is None ) self[ hostname ] = ( "on", "off" )[ on_off ] return self[ hostname ]
def test_ping(): """ Get the average ping. Returns: The average ping in ms. """ return ping.quiet_ping(test_IP, timeout=1000)[2]
def do_ping(input_address): timeout = 0.1 number_to_send = 1 ping_result = ping.quiet_ping(input_address, timeout, number_to_send) if ping_result[0] == 0: # percent dropped return input_address else: return None
def run(self): self._mqclient.connect(self._config.get("MQTT", "ServerAddress"), self._config.get("MQTT", "ServerPort"), 60) self._mqclient.loop_start() while True: a = ping.quiet_ping(self._config.get("PINGER", "AnsiIP"), timeout=1, count=1) if a[0] == 0: self._mqclient.publish("ansi/wlanPresents", "1") else: self._mqclient.publish("ansi/wlanPresents", "0") t = ping.quiet_ping(self._config.get("PINGER", "TiffyIP"), timeout=1, count=1) if t[0] == 0: self._mqclient.publish("tiffy/wlanPresents", "1") else: self._mqclient.publish("tiffy/wlanPresents", "0") time.sleep(30)
def is_node_alive_with_icmp_ping(ip): percent_lost, mrtt, artt = ping.quiet_ping(ip, timeout=1, count=1, psize=64) if percent_lost == 0: return True else: return False
def run(ip): now = datetime.datetime.now().strftime('%Y-%m-%d %T') loss,max_rtt,avg_rtt = ping.quiet_ping(ip,timeout=1, count=100, psize=8) print loss,max_rtt,avg_rtt,ip fullname = os.path.join(LOGDIR, "%s.log" % ip) with open(fullname, "a") as f: if max_rtt: f.write("%-16s %4d %8.4f %8.4f\n" %(now,loss,max_rtt,avg_rtt)) else: f.write("%-16s %4d" % (now,loss))
def run(ip): now = datetime.datetime.now().strftime('%Y-%m-%d %T') loss, max_rtt, avg_rtt = ping.quiet_ping(ip, timeout=1, count=100, psize=8) print loss, max_rtt, avg_rtt, ip fullname = os.path.join(LOGDIR, "%s.log" % ip) with open(fullname, "a") as f: if max_rtt: f.write("%-16s %4d %8.4f %8.4f\n" % (now, loss, max_rtt, avg_rtt)) else: f.write("%-16s %4d" % (now, loss))
def newProcess(queueDo, queueDone, timeout, count, numDataBytes, path_finder): while queueDo.qsize() > 0: target = queueDo.get() ping = quiet_ping(hostname=target, timeout=timeout, count=count, numDataBytes=numDataBytes, path_finder=path_finder) if ping == False: # queueDone.put({'target': target, 'maxTime': ping, 'minTime': ping, 'avrgTime': ping, 'fracLoss': ping}) queueDone.put([target, ping]) else: maxTime, minTime, avrgTime, fracLoss = ping # queueDone.put({'target': target, 'maxTime': maxTime, 'minTime': minTime, 'avrgTime': avrgTime, 'fracLoss': fracLoss}) queueDone.put([target, maxTime, minTime, avrgTime, fracLoss])
def main(): if len(sys.argv) < 2: usage() ip_list = ip_parse(sys.argv[1]) print("{0:^20s}\t{1:^25s}\t{2:>5s}\t{3:>5s}\t{4:>5s}".format( "Tag", "IP", "Per", "Max", "Avg")) for line in ip_list: tag, ip = line.split() result = ping.quiet_ping(ip, count=10) print("{0:25s}\t{1:25s}\t{2:5d}%\t{3:5d}ms\t{4:5d}ms".format( tag, ip, result[0], int(result[1]), int(result[2])))
def iplistFilter(): ''' Filte the ip can not ping success ''' with open('./iplist.py', 'r') as iplist1: for ip in iplist1: ping_result = quiet_ping(ip, timeout=1) if ping_result[1]: # ping success print ping_result iplist_filted = open('./iplist_filted.py', 'a') iplist_filted.write(ip) iplist_filted.close()
def manager(self): if self._hosts: for host in self._hosts: try: (ploss, maxrt, meanrt)=ping.quiet_ping(host, count=1) #print "%s/%d/%d" % (host, ploss, maxrt) if ploss==100: self.logger.error('unreachable host [%s]' % host) elif ploss>0: self.logger.warning('partial ping for host [%s] loss:%d%% max:%dms mean:%dms' % (host, ploss, maxrt, meanrt)) except: self.logger.error('exception occured while processing host %s' % host)
def check_ping(ip, port, dst_id, timeout, count, psize): """ Check the network situation between LRs 1. Check the service of LR is normal(ip and port), if not, do not do ping test 2. Check connection between two LR,if packet drop rate is 100%, do not do ping check 3. Do ping check: max/avg response time and packet drop rate """ if not check_lr_service(ip,port): logger.logger.error("The service of %s:%s is not running" % (ip,port)) tmp_dict = {} tmp_dict['dst_id'] = dst_id tmp_dict['percent_lost'] = 100 tmp_dict['mrtt'] = 0.0 tmp_dict['artt'] = 0.0 qos_result['data'].append(tmp_dict) else: try: test_result = ping.quiet_ping(ip, timeout=1, count=4, psize=64) except Error as e: logger.logger.error("test quiet_ping error,ip:%s;Reason:%s" % (ip,e.reason)) else: if test_result[0] == 100: tmp_dict = {} tmp_dict['dst_id'] = dst_id tmp_dict['percent_lost'] = test_result[0] tmp_dict['mrtt'] = 0.0 tmp_dict['artt'] = 0.0 qos_result['data'].append(tmp_dict) else: try: result = ping.quiet_ping(ip, timeout=timeout, count=count, psize=psize) except Error as e: logger.logger.error("normal quiet_ping error,ip:%s;Reason:%s" % (ip,e.reason)) else: tmp_dict = {} tmp_dict['dst_id'] = dst_id tmp_dict['percent_lost'] = result[0] tmp_dict['mrtt'] = round(result[1],2) tmp_dict['artt'] = round(result[2],2) qos_result['data'].append(tmp_dict)
def get_ip_score(ip, loss_mult, lag_mult, count): logger.debug("IP %s loss_mult %s lag_mult %s count %s", ip, loss_mult, lag_mult, count) result = ping.quiet_ping(ip, 2, count) (loss, lag) = (result[0], result[2]) logger.debug("loss %s lag %s", loss, lag) if not lag: lag = 1000 logger.warning("IP %s is unreachable", ip) score = loss_mult * loss + lag_mult * lag logger.debug("Returning score %s for IP %s", score, ip) return score
def is_node_alive_with_icmp_ping(ip): percent_lost, mrtt, artt = ping.quiet_ping(ip, timeout=1, count=1, psize=64) if percent_lost == 0: return True else: lock.acquire() with open(dbf, 'a') as fp: fp.write(ip + " " + now + "\n" * 2) lock.release() return False
def quietPing(ip_queue, nthread): while True: try: if not ip_queue.empty(): ipaddr = ip_queue.get() ping_result = quiet_ping(ipaddr, timeout=1) print '[%s]Thread-%-2s %-18s %r' % (str( time()), nthread, ipaddr, ping_result) else: break except: print 'exception'
def ping_idc(): is_null = lambda x : x if x != None else 0.0 # 如果x参数为空返回0.0,否则返回x参数 result = [] addr = ['182.18.40.226','182.18.40.227'] for ip in addr: percent, mrtt, artt = ping.quiet_ping(ip) for metric, v in [('ping.alive', percent), ('ping.max_rtt', is_null(mrtt)), ('ping.avg_rtt', is_null(artt))]: x = { 'metric': metric, 'value': v, 'host':ip } result.append(x) return result
def is_domain_ping(url): try: url_info = url2ip(url) if isinstance(url_info, tuple): host = str(url_info[0]) else: host = str(url_info) pings = ping.quiet_ping(host, timeout=1) if pings[0] == 0: return 1 else: return -1 except: return -1
def is_server_available(): """ Pings REPO_SERVER to diagnose packet loss and server availability. Args: REPO_SERVER: is the pre-set address count: Number of times to ping the server Returns: A boolean, True for server availability. """ import ping lost_packet_percent = ping.quiet_ping(REPO_SERVER, timeout=3, count=5)[0] return lost_packet_percent < 50
def login(address, user, password): # what do we need user and password for? shoud i write some db with users credentials? #ping 2 times with 60sec timeout lost = quiet_ping(address, count = 2, timeout=60)[0] # get % of lost #if 1 ping was success then not 100% lost so if not 100% then success success = int(not (lost == 100)) if success: #force to use global 'logged_in_time' instead of creation local global logged_in_time ### server state 'logged in' logged_in_time = datetime.now() return {'Success': success, 'ErrorCode': 0, 'Log': '', 'ResponseInfo':'logged in'}
def test_ping(config): log = logging.getLogger(__name__) address = config.get('ping.address') log.info('Trying to ping %s', address) try: lost, mrtt, artt = ping.quiet_ping(address) except Exception as e: log.error('Cannot ping: %s', traceback.format_exception_only(e.__class__.__name__, e)) return None if lost != 0: log.error('Ping unsuccessful, mrtt=%.3f, artt=%.3f, lost=%.3f.', mrtt, artt, lost) return None log.info('Ping max: %.3fms, avg: %3fms.', mrtt, artt) return artt
def testPing(self,ip,timeout): try: max_ttr, min_ttr, avg_ttr,lost_per = quiet_ping(hostname=ip , timeout=timeout*1000, count=30) except Exception as e: logging.error("ping:%s, ip:%s, domain:%s" % (e, ip, name)) return -2 #if lost_per > 5: # print "lost_per",lost_per # return -1 logging.debug("lost_per:%d,max_ttr:%d,avg_ttr:%d,timeout:%d, ip:%s"\ % (lost_per,max_ttr,avg_ttr,timeout,ip)) if avg_ttr == 0: logging.warning("ping return None, ip:%s" % (ip)) return -2 return timeout*10 + avg_ttr + lost_per*1000
def test_ping(config): log = logging.getLogger(__name__) address = config.get('ping.address') log.info('Trying to ping %s', address) try: lost, mrtt, artt = ping.quiet_ping(address) except Exception as e: log.error('Cannot ping: %s', traceback.format_exception_only( e.__class__.__name__, e)) return None if lost != 0: log.error('Ping unsuccessful, mrtt=%.3f, artt=%.3f, lost=%.3f.', mrtt, artt, lost) return None log.info('Ping max: %.3fms, avg: %3fms.', mrtt, artt) return artt
def monitor_exe(domain,ip,port=80,path="/",mtype=1): #data = urllib.urlencode({}) ret = {"status":0,"status_code":"0","reason":"out","restime":0} #根据监控类型来监控 if mtype == 1:#HTTP监控 headers = {"Content-type":"application/x-www-form-urlencoded","Accept":"text/plain","Connection":"close"} headers['Host']=str(domain) try: starttime = time.time() conn = httplib.HTTPConnection(ip,port,timeout=1) conn.request('GET',str(path),headers=headers) http_res = conn.getresponse() conn.close() distime = int((time.time()-starttime)*1000) ret['status'] = 1 ret['status_code'] = http_res.status ret['reason'] = http_res.reason ret['restime'] = distime except: pass elif mtype == 2:#SOCKET 监控 try: #ip = socket.gethostbyname("www2cto.com") sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk.settimeout(1) starttime = time.time() sk.connect((ip,port)) distime = int((time.time()-starttime)*1000) sk.close() ret['status'] = 1 ret['status_code'] = '1' ret['reason'] = 'ok' ret['restime'] = distime except: pass elif mtype == 3:#PING 监控 try: result = ping.quiet_ping(str(ip), timeout=1, count=4, psize=64) if result[0] < 100: ret['status'] = 1 ret['status_code'] = result[0] ret['reason'] = "fail:%s"%str(result[0]) ret['restime'] = int(result[1]) except: pass return ret
def perform_check(self, db): print 'Pinging %s...' % self.ip response = ping.quiet_ping(self.ip, count=8) # put count in config response_time = response[2] # returns (percent_lost, max round trip time, average round trip time) now = time.time() timestamp = datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S') try: db.execute('insert into check%d (timestamp, time) values (\'%s\', %.3f)' % (self.id, timestamp, response_time)) except: db.execute('create table check%d (id integer primary key autoincrement, timestamp text not null, time text not null)' % self.id) db.execute('insert into check%d (timestamp, time) values (\'%s\', %.3f)' % (self.id, timestamp, response_time)) db.commit() db.close() print '%s returned ping in %.3fms' % (self.ip, response_time)
def latency_server(result): if not isinstance(result, list): return False package_loss, max_latency, avg_latency = ping.quiet_ping(ip, timeout=2, count=10, psize=64) result.append( 'storage_client{server="%s",type="loss",host="%s",describe="loss package!"} %d\n' % (ip, host, package_loss)) result.append( 'storage_client{server="%s",type="max_latency",host="%s",describe="unit ms!"} %d\n' % (ip, host, max_latency)) result.append( 'storage_client{server="%s",type="avg_latency",host="%s",describe="unit ms!"} %d\n' % (ip, host, avg_latency)) if package_loss > 50: return False return True
def get_env(): t_ip = os.getenv("Server") if not t_ip: print "必须提供有效的存储服务器ip,例如Server=192.168.0.11" sys.exit(1) result, _, _ = ping.quiet_ping(t_ip, timeout=2, count=1, psize=32) if result == 100 or t_ip == "localhost" or t_ip == "127.0.0.1": print "必须提供有效的存储服务器ip,例如Server=192.168.0.11" sys.exit(1) t_path = os.getenv("Path") if not t_path or not os.path.isdir(t_path): print "必须提供存储介质有效的挂载路径,例如Path=/data" sys.exit(1) t_host = os.getenv("host") if not t_host: print "必须提供有效的物理机标识,以便追踪,例如host=client1" sys.exit(1) return t_ip, t_path, t_host
async def download(self, filename, local_path, loop): ''' Get a file from Napster system ''' #Send a request to meta-data server msg = {} msg['cmd'] = 'DOWNLOAD' msg['file_name'] = filename try: reader, writer = await asyncio.open_connection(self.server_ip, self.server_port, loop=loop) except ConnectionError as e: print("Connection error:", e) print('Send: %r' % msg) writer.write(str(msg).encode()) writer.write_eof() #Get response resp = await reader.read() print('Received: %r' % resp.decode()) locations = literal_eval(resp.decode()) latency = 10 # Maximum latency 10s s_ip = None remote_path = None try: for location in locations: ip = location['ip_addr'] delay = ping.quiet_ping(ip, timeout=1)[1] if (delay is not None): if (float(delay) < latency): latency = float(delay) s_ip = ip remote_path = location['path'] except socket.error as e: print("Ping error:", e) #Download the file from the selected host if (s_ip is not None) & (remote_path is not None): await self._download(s_ip, remote_path, local_path) print("Downloaded file. Check the file at %r" % local_path) else: print("Cannot find the file.")
def get_host(ip_addr): """ test ip is connected to port 443 and get ping message """ try: headers = '' requests.get('https://' + ip_addr, timeout=2) return -2 except SSLError as e: name_list = [] ping_list = [] if platform.system() == 'Linux': ping_list = [0, 0, 0] else: ping_list = ping.quiet_ping(ip_addr) ping_artt = ping_list[2] ping_lost = ping_list[0] ping_value = [ 'delay: %.5sms, lost: %s%%' % (ping_artt, ping_lost), ping_artt, ping_lost ] if "', '" in str(e): name_list = str(e).split("', '") name_list[0] = name_list[0].split("'")[-1] name_list[-1] = name_list[-1].split("'")[0] # print ip_addr + '\n' return [name_list, ip_addr, ping_value] elif 'match' in str(e): temp_list = str(e).split("'") name_list.append(temp_list[-2]) # print ip_addr return [name_list, ip_addr, ping_value] return e except Timeout: # print ip_addr + ' time out' return -3 except Exception as e: # print ip_addr + '\n' + str(e) return -4
def woker(debug, switch, config): addr = switch["addr"] ping_timeout = config["TIME_OUT"] ping_count = config["PACKAGE_COUNT"] ping_size = config["PACKAGE_SIZE"] source = config["IDENTIFY"] print addr, ping_timeout, ping_count, ping_size, source statsd = get_statsd(config) while True: before_timestamp = int(time.time()) result = ping.quiet_ping( dest_addr=addr, timeout=ping_timeout, count=ping_count, psize=ping_size ) if debug: print_result(statsd, switch["name"], source, result) else: send_result(statsd, switch["name"], source, result) after_timestamp = int(time.time()) time.sleep(20 - (after_timestamp - before_timestamp))
def Ping(self): return ping.quiet_ping(self.IP,count=1)
def switch_pkt_lost(host): result = ping.quiet_ping(host,count=10) return result[0]
from ftplib import FTP import ping from socket import * import ports #import paramiko connected_devices = [] for i in range(1, 254): ip = "192.168.0." + str(i) ans = str(ping.quiet_ping(ip, 0.003, 1)) #print(ans(0)) if ans[1] == "0": connected_devices.append(ip) print("connected devices: ") for adress in connected_devices: print(adress) print("\n") def scancommonports(address): common_ports = ports.listofports for p in common_ports: scanport(address, p.port) def scancommonportsfromlist(iplist): for address in iplist: scancommonports(address)
def ping_host(hostname): ping_ret = ping.quiet_ping(hostname, timeout=0.1) return ping_ret[0] == 0 # verify return core is 0
def pingStatus(host): ping_result = quiet_ping(host, timeout=1) return ping_result
def get_table_row(record): ''' Get an array to use with PrettyTable.addrow() ''' # Some records will lack any network information in the JSON object: if record['network_info'] == '[]': _ip = '-' if args.ping: _ping_message = '-' if args.check_dns: _dns_message = '-' _rdns_message = '-' else: _ip = json.loads(record['network_info'])[0]['network']['subnets'][0]['ips'][0]['address'] if args.ping: _results = quiet_ping(_ip, timeout=2, count=10) _ping_message = '' if _results: if _results[0] > 0: if _results[0] == 100: _ping_message = '%sDOWN%s' % (red, end) else: _ping_message = '%s!!%s %s%% loss (%sms, %sms)' % (red, end, _results[0], round(_results[1], 2), round(_results[2], 2)) else: _ping_message = '%sOK%s (%sms, %sms)' % (green, end, round(_results[1], 2), round(_results[2], 2)) else: _ping_message = '%sDOWN%s' % (red, end) if args.check_dns: _name = record['hostname'] + dns_suffix try: _resolved_ip = gethostbyname(_name) except gaierror: _resolved_ip = None except timeout: _resolved_ip = 'timed out' try: _resolved_name = gethostbyaddr(_ip)[0] except herror: _resolved_name = None except timeout: _resolved_name = 'timed out' # DNS: if _resolved_ip == _ip: _dns_message = '%s%s%s' % (green, _resolved_ip, end) elif _resolved_ip is None: _dns_message = '%s!! No DNS record !! %s' % (red, end) else: _dns_message = '%s!! %s !!%s' % (red, _resolved_ip, end) # Reverse DNS: if _resolved_name == _name: _rdns_message = '%s%s%s' % (green, _resolved_name.replace(dns_suffix, ''), end) elif _resolved_name is None: _rdns_message = '%s!! No RDNS record !! %s' % (red, end) else: _rdns_message = '%s!! %s !!%s' % (red, _resolved_name.replace(dns_suffix, ''), end) _row = [ record['hostname'], _ip, record['user_id'], record['created_at'], project_id_mappings[record['project_id']], record['name'], # Is the instance flavor name record['host'].replace(dns_suffix, '') ] if args.ping: _row.insert(2, _ping_message) if args.uuid: _row.insert(4, record['uuid']) if args.check_dns: _row.insert(2, _dns_message) _row.insert(3, _rdns_message) if disabled_hypervisors: _disabled_reason = '' if record['disabled'] == 0: _status = 'Enabled' else: _status = 'Disabled' if not record['disabled_reason']: _disabled_reason = '' _row.extend([_status, _disabled_reason]) return _row
FILE = tempfile.NamedTemporaryFile(delete=False, dir='/tmp') print("Log file {}".format(FILE.name)) if 4!=len(sys.argv): FILE.write("Please enter {} <IP> <start port> <end port>".format(sys.argv[0]) +'\n') print("Please enter {} <IP> <start port> <end port>".format(sys.argv[0])) exit() start_port = 0 end_port = 0 try: start_port = int(sys.argv[2]) end_port = int(sys.argv[3]) percent, lost, maximum = ping.quiet_ping(sys.argv[1]) except: FILE.write("check port numbers,execute the script as root" +'\n') print("check port numbers,execute the script as root") exit() if (start_port > end_port or start_port == 0 or end_port == 0 or start_port > 65535 or end_port > 65535): print("Error: Start port should be lower or eaqual end port, " "ports can`t be 0 or bigger than 65535") exit() if percent == 100: FILE.write("IP {} is unreachable".format(sys.argv[1]) +'\n') print ("IP {} is unreachable".format(sys.argv[1])) exit()
def _ping(self, addr, q, number_of_ping): (_lost, _max, _avg) = ping.quiet_ping(addr, number_of_ping) q.put((_avg, addr))
'irr_as_set'] else: peer[name][asn]['import'] = "AS" + str(asn) peer[name][asn]['export'] = "MDW-MAIN-AS" peer[name][asn]['peerings'] = [] if name_request['data'][0]['info_prefixes4'] is not None: peer[name][asn]['limit_ipv4'] = int( name_request['data'][0]['info_prefixes4']) if name_request['data'][0]['info_prefixes6'] is not None: peer[name][asn]['limit_ipv6'] = int( name_request['data'][0]['info_prefixes6']) delete = True for routeur in result: if routeur['ipaddr4'] is not None: peer[name][asn]['peerings'].append(routeur['ipaddr4']) latency = ping.quiet_ping(routeur['ipaddr4'])[1] if latency is None: latency = 0 base = 190 peer[name][asn]['med'] = int(base + latency * 10) print("Generating configuration at " + name + " for the router " + str(routeur['ipaddr4']) + " of the AS " + str(asn) + " " + peer[name][asn]['description'] + " " + str(latency) + " med " + str(peer[name][asn]['med'])) if routeur['ipaddr6'] is not None: peer[name][asn]['peerings'].append(routeur['ipaddr6']) print("Generating configuration at " + name + " for the router " + str(routeur['ipaddr6']) + " of the AS " + str(asn) + " " + peer[name][asn]['description'])
def ping_thread(args): global g_exit, g_response_time while not g_exit: g_response_time = ping.quiet_ping('google.com', timeout=1000)
if VERBOSE: print "Trying to parse label list from LSR...", LABELS = get_labels(LSR, USER, PASS, PROTO) if TARGETS_FILE is not False: try: TARGETS = [line.strip() for line in open(TARGETS_FILE, 'r')] except IOError as e: print "Error: %s" % e.strerror exit(-1) if VERBOSE: print "done" if VERBOSE: print "Checking if targets is alive by pinging them with size %i..." % PACKETSIZE ALIVE_TARGETS = [] for target in TARGETS: status = ping.quiet_ping(target, psize=PACKETSIZE-20, count=2) if status[0] < 100: if VERBOSE: print "\tTarget %s is alive" % target ALIVE_TARGETS.append(target) else: if VERBOSE: print "\tTarget %s is dead" % target if VERBOSE: print "Totally %i targets alive" % len(ALIVE_TARGETS) # Create all possible variations of targets if VERBOSE: print "Creating permutation list from alive targets list...", for target in itertools.permutations(ALIVE_TARGETS, 2): try: # Search for loopback in LSDB label = int(next(i[0] for i in LABELS if i[1] == target[0]))