def F5_scan(): print "Opening F5 IP range file" with open("F5_Networks", 'r') as f: address = f.readlines() address = [x.strip('\n') for x in address] print "Opening F5 Gateway file" with open("F5_Gateways", 'r') as f: gateway_ips = f.readlines() gateway_ips = [x.strip('\n') for x in gateway_ips] IP_list = [] print "Generating list of IPs based off file" for i in xrange(0, len(address)): for ip in IPNetwork(address[i]): IP_list.append(ip) print "Scanning" for num in xrange(0, len(IP_list)): try: # bash equivalent: ping -c 1 > /dev/null sh.ping(IP_list[num], "-c 1 -i 0.2", _out="/dev/null") except sh.ErrorReturnCode_1: if IP_list[num] in gateway_ips: pass else: print "no response from", IP_list[num] sys.exit()
def get_rasps_from_csv(): global_settings.rasps = {} print("-----------------------------------------------------------") print("Generating the global variable dict_rasps_csv from the csv file") print("-----------------------------------------------------------") try: with open(global_settings.dict_rasps_csv, 'r') as ofile: mcsv = csv.reader(ofile, delimiter=',') for row in mcsv: print(row[0]) global_settings.rasps[row[0]] = Rasp.Rasp() global_settings.rasps[row[0]]._id = row[0] global_settings.rasps[row[0]]._mac = row[1] global_settings.rasps[row[0]]._ip = row[3] global_settings.rasps[row[0]]._stack = row[2] global_settings.rasps[row[0]]._power = 'On' global_settings.rasps[row[0]]._cpu = '--' global_settings.rasps[row[0]]._temperature = '--' global_settings.rasps[row[0]]._Lping = '--' try: #bash ping command from master to pis sh.ping(row[3], "-c 2", _out="/dev/null") print("ping to ", row[3], " OK") global_settings.rasps[row[0]]._Rstatus = 'okStatus' except sh.ErrorReturnCode_1: print("no response from", row[3]) global_settings.rasps[row[0]]._Rstatus = 'koStatus' print(global_settings.rasps[row[0]]._id + ' ' + global_settings.rasps[row[0]]._ip + ' ' + global_settings.rasps[row[0]]._mac + ' ' + global_settings.rasps[row[0]]._stack) print(" Rasps generated from csv file\n") except: print("Installation needed")
def is_ip_free(ip): try: sh.ping(str(ip), c=1) except sh.ErrorReturnCode: return True return False
def connect(): global opc global list opc = None list = None if debug: print "Connecting..." r.set("connected", "BAD") while list is None: try: if debug: print "Connection Attempt {" opc = OpenOPC.open_client(opc_server) opc.connect(opc_server_name, opc_server) list = opc.list('Brave.calendar.opc_group') if debug: print "}" r.set("connected", "OK") r.set("opc_server", plc) r.set("opc_server_name", opc_server_name) r.set("plc", plc) r.set("redis_server", redis_server) except Exception as e: if debug: print e try: ping(opc_server, c=1) print {'error': 'Cannot connect to ' + opc_server_name, 'val': 0} except Exception as e: if debug: print e print {'error': 'Cannot connect to network', 'val': 0} pass pass finally: time.sleep(poll_rate)
def ping_rasps_in_stack(nstack): print('------------------------------------') print("---- Ping command in process... ----") print('------------------------------------') tmp = 0 for key in global_settings.rasps: if global_settings.rasps[key]._stack == nstack: ip = global_settings.rasps[key]._ip id = global_settings.rasps[key]._id print("ip, id rasp:", ip, id) try: #bash ping command from master to pis sh.ping(ip, "-c 2", _out="/dev/null") global_settings.rasps[id]._Rstatus = "okStatus" print(ip, " is up") date = datetime.datetime.now() date = date.strftime('%d/%m/%Y') rasps_handler.update_rasp_by_id(id, "ping", date, 200) tmp = tmp + 1 except sh.ErrorReturnCode_1: print("no response from", ip) global_settings.rasps[id]._Rstatus = "koStatus" if tmp == 0: global_settings.stacks[nstack]._Sstatus = "koStatus" else: if tmp < int(configRack['rack']['pi_stack']): print("Warning") global_settings.stacks[nstack]._Sstatus = "warningStatus" else: global_settings.stacks[nstack]._Sstatus = "okStatus" return
def ping_rasps_in_stack(nstack): print("------------------------------------") print("---- Ping command in process... ----") print("------------------------------------") tmp = 0 for key in global_settings.rasps: if global_settings.rasps[key]._stack == nstack: ip = global_settings.rasps[key]._ip id = global_settings.rasps[key]._id print("ip, id rasp:", ip, id) try: # bash ping command from master to pis sh.ping(ip, "-c 2", _out="/dev/null") global_settings.rasps[id]._Rstatus = "okStatus" print(ip, " is up") date = datetime.datetime.now() date = date.strftime("%d/%m/%Y") rasps_handler.update_rasp_by_id(id, "ping", date, 200) tmp = tmp + 1 except sh.ErrorReturnCode_1: print("no response from", ip) global_settings.rasps[id]._Rstatus = "koStatus" if tmp == 0: global_settings.stacks[nstack]._Sstatus = "koStatus" else: if tmp < int(configRack["rack"]["pi_stack"]): print("Warning") global_settings.stacks[nstack]._Sstatus = "warningStatus" else: global_settings.stacks[nstack]._Sstatus = "okStatus" return
def F5_scan(): print "Opening F5 IP range file" with open("F5_Networks", 'r') as f: address=f.readlines() address=[x.strip('\n') for x in address] print "Opening F5 Gateway file" with open("F5_Gateways", 'r') as f: gateway_ips=f.readlines() gateway_ips=[x.strip('\n') for x in gateway_ips] IP_list=[] print "Generating list of IPs based off file" for i in xrange(0,len(address)): for ip in IPNetwork(address[i]): IP_list.append(ip) print "Scanning" for num in xrange(0,len(IP_list)): try: # bash equivalent: ping -c 1 > /dev/null sh.ping(IP_list[num], "-c 1 -i 0.2", _out="/dev/null") except sh.ErrorReturnCode_1: if IP_list[num] in gateway_ips: pass else: print "no response from", IP_list[num] sys.exit()
def is_ip_free(ip): try: sh.ping(str(ip), c=1) except sh.ErrorReturnCode: if is_ctid_free(str(ip)): return True else: return False
def checker(reminder, target, method='icmp'): global info, recipient if method == 'icmp': try: ping(target, c=3) except ErrorReturnCode: message = 'server {0}: {1} is down'.format(info[target], target) reminder(message, recipient)
def checkInternetConnectivity(): x = 1 try: sh.ping("www.google.com", "-c 1", _out="/dev/null") #socket.create_connection( ("www.google.com", 80) ) except sh.ErrorReturnCode_1: x = 0 finally: return x
def checkConn(ip): logging.debug("Checking ip...") for i in range(5): try: ping('-c', '1', ip, _fg=True) return True except: sleep('5') return False
def scan_ips(self,ip): try: sh.ping(ip, "-c 1",_out="/dev/null") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.avalibles_ips[ip]=0 except sh.ErrorReturnCode_1: exit()
def ensure_network(_server): networks = dict((k, v) for k, v in _server['meta']['network'].items() if 'ip' in v) for name, net in networks.items(): if_name = name if net['type'] != 'symlink' else net['interfaces'][0] cmd = '-I {0} -c 3 {1}'.format(if_name, net['gw']) try: sh.ping(cmd.split()) except sh.ErrorReturnCode as exc: send_error(exc.message)
def pinghost(hosts): while True: for host in hosts: try: sh.ping('-c', '2', host) except: print(host + ' is DOWN!') else: print(host + ' is UP!') return None
def ensure_network(_server): networks = dict( (k, v) for k, v in _server['meta']['network'].items() if 'ip' in v) for name, net in networks.items(): if_name = name if net['type'] != 'symlink' else net['interfaces'][0] cmd = '-I {0} -c 3 {1}'.format(if_name, net['gw']) try: sh.ping(cmd.split()) except sh.ErrorReturnCode as exc: send_error(exc.message)
def my_menu(): your_resp = 0 while your_resp != 3: try: print("""\033[1;31m [===========[\033[1;37mMENU\033[1;31m]===========] \033[1;31m||\033[1;34m |1|\033[1;37m Check icmp reply\033[1;31m || \033[1;31m||\033[1;34m |2|\033[1;37m Show good/bad addr\033[1;31m || \033[1;31m||\033[1;34m |3|\033[1;37m Exit \033[1;31m || [============================]\033[1;m""") your_resp = int( input( "\n\n\033[1;34m ==> \033[1;37m Enter your choice: \033[1;m" )) break except (ValueError): print( "\n\n\n\033[1;31m Oops! You didn't enter a valid choice. Try again.\n\n\n\033[1;m" ) if your_resp == 1: print("\033[1;37m \n\nHey, wassup breh...\n\n\033[1;m") for num in range(5, 10): address = "8.8.8." + str(num) try: sh.ping(address, "-c 1", _out="/dev/null") print("Success:", address, "is up") with open('gaddresses.txt', 'a') as out: out.write(address + '\n') with open('baddresses.txt', 'a') as out: out.write('\n') except sh.ErrorReturnCode_1: print("Error:", address, "not responding") with open('baddresses.txt', 'a') as out: out.write(address + '\n') with open('gaddresses.txt', 'a') as out: out.write('\n') my_menu() elif your_resp == 2: print("\033[1;34m \n\nGood Addresses...\n\n\033[1;m") print(sh.cat('gaddresses.txt')) print("\033[1;31m \n\nBad Addresses...\n\n\033[1;m") print(sh.cat('baddresses.txt')) my_menu() elif your_resp == 3: print("\033[1;34m\n\n See you later!\033[1;m") sh.rm('gaddresses.txt') sh.rm('baddresses.txt') else: print( "\033[1;41m\n\n\n Sorry, I didn't understand your choice...\n\n\n\033[1;m" ) print("\033[1;41m\n\n Please try again.\n\n\n\033[1;m") my_menu() print()
def update_connection(): global connection global connection_checked connection_checked = time.time() try: sh.ping('8.8.8.8', c=1, W=1) except sh.ErrorReturnCode: connection = "Disconnected" else: connection = "Connected" s.enter(15, 1, update_connection)
def scan_ip(ip_range): start, end = [int(num) for num in ip_range.split(':')] for i in range(start, end): ip = f'192.168.1.{i + 1}' try: sh.ping(ip, '-c', 1, _out='/dev/null') # ping current ip click.echo('{}\t{}'.format(ip, click.style('OK', fg='blue'))) except sh.ErrorReturnCode: click.echo('{}\t{}'.format(ip, click.style('FAIL', fg='red')))
def single_ip(Display_alive): print "Scanning IP Range" IP_list=[] address=sys.argv[2] for ip in IPNetwork(address): IP_list.append(ip) for num in xrange(0,len(IP_list)): try: #bash equivalent: ping -c 1 > /dev/null sh.ping(IP_list[num], "-c 1 -i 0.2", _out="/dev/null") if Display_alive.lower()== "y": print "ping to", IP_list[num], "OK" except sh.ErrorReturnCode_1: print "no response from", IP_list[num] sys.exit()
def single_ip(Display_alive): print "Scanning IP Range" IP_list = [] address = sys.argv[2] for ip in IPNetwork(address): IP_list.append(ip) for num in xrange(0, len(IP_list)): try: #bash equivalent: ping -c 1 > /dev/null sh.ping(IP_list[num], "-c 1 -i 0.2", _out="/dev/null") if Display_alive.lower() == "y": print "ping to", IP_list[num], "OK" except sh.ErrorReturnCode_1: print "no response from", IP_list[num] sys.exit()
def ping_st(ip, old_ping, id, manual_check=False, ping_type=2): # for subprocess usage if ping_type==2: p = subprocess.Popen(["ping", "-c", "3", "-i", "0.2", ip], stdout=subprocess.PIPE) result = p.communicate() result = result[0].decode() # for sh.py usage if ping_type==1: try: result = str(sh.ping("-c 3", "-i 0.2", ip, _bg=True)) except sh.ErrorReturnCode_1: result = None if manual_check: return result PING_DIC[id] = {'old_ping': old_ping} if result: m2 = re.search('rtt min/avg/max/mdev = (.*) ms', result) if m2: avgtime = m2.group(1).split('/')[1] PING_DIC[id]['ping'] = float(avgtime) else: PING_DIC[id]['ping'] = None else: PING_DIC[id]['ping'] = None
def ping(): """Ping the Observation Simulator to make sure it is alive""" from sh import ping out = ping('-c', '1', '-t', '1', '192.168.100.1') return ('1 packets transmitted, 1 packets received' in str(out) or # MacOSX '1 packets transmitted, 1 received' in str(out)) # Centos
def is_alive4(target): res = -1 try: res = ping(target, c=2, _out=None) except: pass return res.exit_code == 0
def __init__(self, number, debug=False, sanity_checks=True, auto_load=True): from fpesocketconnection import FPESocketConnection # First sanity check: ping the observatory simulator if not ping(): raise Exception("Cannot ping 192.168.100.1") self._debug = debug self._dir = os.path.dirname(os.path.realpath(__file__)) self._reset_in_progress = False self._loading_wrapper = False self.fpe_number = number self.connection = FPESocketConnection(5554 + number, self._debug) # self.ops implemented with lazy getter self._ops = None frames_status = None if sanity_checks is True: from unit_tests import check_house_keeping_voltages from unit_tests import UnexpectedHousekeeping from fpesocketconnection import TimeOutError try: try: frames_status = self.frames_running_status assert frames_status is True or frames_status is False except Exception as e: raise type( e )("Could not read if frames are running on the Observatory Simulator... {0}\n" .format(str(e)) + "Are you sure the firmware for the Observatory Simulator is properly installed?" ) try: version = self.version if self._debug: print version except Exception as e: raise type( e )("Could not read Observatory Simulator version... {0}\n". format(str(e)) + "Are you sure you firmware for the Observatory Simulator is properly installed?" ) if frames_status is not True: try: check_house_keeping_voltages(self) except (UnexpectedHousekeeping, TimeOutError) as e: if auto_load is True: self.load_wrapper() else: raise e finally: if frames_status is not None: self.frames_running_status = frames_status
def do_ping(self, host="8.8.8.8", interval=0.5): """Get ping information and publish it.""" for data in ping(host, "-i", str(interval), _iter=True, _err=self.publish_ping_err): if rospy.is_shutdown(): return # Exit thread when node closes delay = data.split()[-2].split("=")[-1] self.publish_delay(delay)
def ping_test(host): ping = sh.ping('-q', '-c', 10, host, _ok_code=[0, 1]) packet_loss = re.findall(r'(\d+)% packet loss', ping.stdout)[0] if int(packet_loss) > 60: syslog.syslog(syslog.LOG_ERR, 'Unable to ping gateway.') return False else: return True
def file_scan(Display_alive): print "Opening File and beging scan" with open(sys.argv[2], 'r') as f: address=f.readlines() address=[x.strip('\n') for x in address] IP_list=[] for i in xrange(0,len(address)): for ip in IPNetwork(address[i]): IP_list.append(ip) for num in xrange(0,len(IP_list)): try: # bash equivalent: ping -c 1 > /dev/null sh.ping(IP_list[num], "-c 1 -i 0.2", _out="/dev/null") if Display_alive.lower()== "y": print "ping to", IP_list[num], "OK" except sh.ErrorReturnCode_1: print "no response from", IP_list[num] sys.exit()
def ping(ip='4.2.2.2'): output.itemize('Pinging {}...'.format(ip)) try: packets = sh.ping('-c4', ip).stdout except sh.ErrorReturnCode: raise NetworkError('Could not reach {}'.format(ip)) else: print(packets)
def file_scan(Display_alive): print "Opening File and beging scan" with open(sys.argv[2], 'r') as f: address = f.readlines() address = [x.strip('\n') for x in address] IP_list = [] for i in xrange(0, len(address)): for ip in IPNetwork(address[i]): IP_list.append(ip) for num in xrange(0, len(IP_list)): try: # bash equivalent: ping -c 1 > /dev/null sh.ping(IP_list[num], "-c 1 -i 0.2", _out="/dev/null") if Display_alive.lower() == "y": print "ping to", IP_list[num], "OK" except sh.ErrorReturnCode_1: print "no response from", IP_list[num] sys.exit()
def scan(ext, lst, a, b, add, dork, conf): while True: for b in range(0, len(ext)): try: address = baseN(a, len(lst), lst) + ext[b] sh.ping(address, "-c 1", _out="/dev/null") page = urllib2.urlopen("http://" + address + dork).read() if conf in page: open("index.html", "a").write(address + "<br>\n") open("targets.txt", "a").write(address + "\n") print(address + " - Found one!") except sh.ErrorReturnCode_1: print(address + " - Failed No Responce") except sh.ErrorReturnCode_2: print(address + " - Failed No Responce") except Exception: print(address + " - Failed WP Check") a += add
def __init__(self, number, debug=False, sanity_checks=True, auto_load=True): from fpesocketconnection import FPESocketConnection import os self.FPE_HOSTNAME = os.environ["FPE_HOSTNAME"] if "FPE_HOSTNAME" in os.environ else DEFAULT_FPE_HOSTNAME # First sanity check: ping the observatory simulator if not ping(DEFAULT_FPE_HOSTNAME): raise Exception("Cannot ping " + DEFAULT_FPE_HOSTNAME) self._debug = debug self._dir = os.path.dirname(os.path.realpath(__file__)) self._reset_in_progress = False self._loading_wrapper = False self.fpe_number = number assert self.fpe_number in [1, 2], "FPE number must be either 1 or 2, was {}".format(self.fpe_number) self.connection = FPESocketConnection(5554 + number, self.FPE_HOSTNAME, self._debug) # self.ops implemented with lazy getter self._ops = None frames_status = None if sanity_checks is True: from unit_tests import check_house_keeping_voltages from unit_tests import UnexpectedHousekeeping from fpesocketconnection import TimeOutError try: try: frames_status = self.frames_running_status assert frames_status is True or frames_status is False except Exception as e: raise type(e)( "Could not read if frames are running on the Observatory Simulator... {0}\n".format(str(e)) + "Are you sure the firmware for the Observatory Simulator is properly installed?") try: version = self.version if self._debug: print version except Exception as e: raise type(e)("Could not read Observatory Simulator version... {0}\n".format(str(e)) + "Are you sure you firmware for the Observatory Simulator is properly installed?") if frames_status is not True: try: check_house_keeping_voltages(self) except (UnexpectedHousekeeping, TimeOutError) as e: if auto_load is True: self.load_wrapper() else: raise e finally: if frames_status is not None: self.frames_running_status = frames_status
def _checkalive_ping(self): """Return True on ping success, False on failure.""" for _ in xrange(0, self.PING_REQUEST_COUNT): try: sh.ping( "-c", "1", "-I", self._dev_name, "-W", str(self.PING_TIMEOUT_SEC), self._keepalive_host, _timeout=self.PING_TIMEOUT_SEC + 5 ) return True except (ErrorReturnCode, TimeoutException): _logger.warning(format_exc()) continue return False
def run(self): while True: query = self.queue.get() if query.type == "ping": out = ping(query.query) elif query.type == "ping6": out = ping6(query.query) elif query.type == "trace": out = traceroute(query.query) send_response(query, out) print "Processed query",str(query.id)
def ping_sweep_IP(IP): for i in (IP): var = str(i) var = var.strip('[]') var = var.replace('\'', '') print(sh.ping('-c', '5', var))
def test_access(): try: res = sh.ping("-c", "4", "114.114.114.114") result = re.findall(r"(\d) packets received", str(res))[0] if int(result[0]) > 0: return True except: print(traceback.format_exc()) return False else: return False
def ping_proc(hosts, s): for host in hosts: status = Runstatus.objects.get(id=1) if not status.status: return None try: ping('-c', NUMBER_OF_PINGS, '-w', DEADLINE, host.ipaddr) except: if host.up_status: host.up_status = False host.host_down_time = datetime.now() host.save() data = host.name + ' is down! ' + time.strftime("%H:%M:%S") send_data(data, s) else: if not host.up_status: host.up_status = True host.host_down_time = None host.save() data = host.name + ' is up!' + time.strftime("%H:%M:%S") send_data(data, s)
def ping(self, param): if not cloud.valid_ip_range(param): utils.error('Invalid IP Address Range') return utils.colour_print('(colour_clear)Now scanning:(colour_prompt) ' + param) try: ipset = netaddr.IPSet([param]) except (netaddr.AddrFormatError, netaddr.AddrConversionError): utils.error('Invalid IP Address Range') return for ip in ipset: try: sh.ping(ip, '-w1 -c1') utils.colour_print('(colour_clear)Ping to ' + str(ip) + ' (colour_success)OK(colour_clear)') except sh.ErrorReturnCode_1: utils.error('No response from ' + str(ip)) except sh.ErrorReturnCode_2 as e: utils.error('Error from ping command: ' + e.stderr.decode())
def ping_rasps_in_stack(nstack): print('------------------------------------') print("---- Ping command in process... ----") print('------------------------------------') tmp = 0 for key in global_settings.dict_rasps: if global_settings.dict_rasps[key]._stack == nstack: ip = global_settings.dict_rasps[key]._ip try: #bash ping command from master to pis sh.ping(ip, "-c 2", _out="/dev/null") tmp = tmp + 1 except sh.ErrorReturnCode_1: print("no response from", ip) if tmp == 0: global_settings.stacks[nstack]._Sstatus = "koStatus" else: if tmp < int(configRack['rack']['pi_stack']): global_settings.stacks[nstack]._Sstatus = "warningStatus" else: global_settings.stacks[nstack]._Sstatus = "okStatus" return
def ping(host, count, timeout): """IPv4 version of ping.""" c_arg = '-c {0}'.format(count) p = platform.system() if p == 'Darwin': t_arg = '-t {0}'.format(timeout) elif p == 'Linux': t_arg = '-w {0}'.format(timeout) else: logging.error('Unsupported platform for ping: {0}'.format(p)) return None try: if p == 'Linux': result = sh.ping('-4', c_arg, t_arg, host) else: result = sh.ping(c_arg, t_arg, host) data = _parse_ping_statistic(result.stdout) data['type'] = message_pb2.PingReply.OK except sh.ErrorReturnCode as e: if e.exit_code in [ EXIT_CODE_NOT_RESPONDING_LINUX, EXIT_CODE_NOT_RESPONDING_OSX, ]: # Not responding host data = {'type': message_pb2.PingReply.NOT_RESPONDING} elif e.exit_code == EXIT_CODE_INVALID_ARGS: # Invalid arguments data = {'type': message_pb2.PingReply.INVALID_ARGS} elif e.exit_code == EXIT_CODE_UNRESOLVABLE: # Unresolvable host data = {'type': message_pb2.PingReply.UNRESOLVABLE} else: logging.error('Unexpected error: {0}'.format(e.exit_code)) data = {'type': message_pb2.PingReply.UNKNOWN} except Exception as e: logging.error('Unexpected error: {0}'.format(e)) data = {'type': message_pb2.PingReply.UNKNOWN} return data
def ping(): stdout = None current_time = strftime("%Y-%m-%d %H:%M:%S", gmtime()) try: stdout = sh.ping("-c 4", "ex.ua") except Exception: log = current_time + " : ERROR NO INTERNET CONNECTION" finally: if stdout is not None: if "0% packet loss" in str(stdout): log = current_time + " : OK" else: log = current_time + " : unstable internet connection" logwriter(log) print(log)
def run(): tags = None while tags is None: time.sleep(poll_rate) try: tags = opc.read(list) except Exception as e: if debug: print e try: ping(opc_server, c=1) print {'error': 'Cannot connect to ' + opc_server_name, 'val': 0} connect() except Exception as e: if debug: print e print {'error': 'Cannot connect to network', 'val': 0} connect() pass pass finally: pass for item in tags: r.set(item[0], item[1]) if debug: print r.get(item[0]) if debug: print r.get("registry")
def get_host_latency(target, timeout_sec): """Pings the target server and returns the response time, in seconds. Returns None if there's no response within the timeout.""" try: ping_result = sh.ping(target, c=1, W=timeout_sec) except: # Ignore exceptions. ping_result = "" parse_regex = r"^[0-9]+ bytes from .*: icmp_seq=[0-9]+ ttl=[0-9]+ time=([0-9.]+) ms$" for line in ping_result.split("\n"): match = re.match(parse_regex, line) if match: latency_msec = float(match.group(1)) latency_sec = latency_msec / 1000.0 return latency_sec return None
def ping_gateway(self, gateway): # TODO: Discuss how much packet loss (%) is acceptable. # XXX -- validate gateway # -- is it a valid ip? (there's something in util) # -- is it a domain? # -- can we resolve? -- raise NoDNSError if not. # XXX -- sh.ping implemtation needs review! try: output = sh.ping("-c", "10", gateway).stdout except sh.ErrorReturnCode_1 as e: output = e.message finally: packet_loss = int(re.findall("(\d+)% packet loss", output)[0]) logger.debug('packet loss %s%%' % packet_loss) if packet_loss > constants.MAX_ICMP_PACKET_LOSS: raise exceptions.NoConnectionToGateway
def do_GET(self, *args, **kwargs): url = urlparse(self.path) qs = parse_qs(url.query) host = qs.get("ping") if host: ct = "text/plain" try: res = str(sh.ping("-c", "1", host)) except Exception: res = "Couldn't ping " + host else: ct = "text/html" with open(join(dirname(__file__), "pages", "index.html")) as f: res = f.read() self.send_response(200) self.send_header("Content-type", ct) self.send_header("Content-length", len(res)) self.end_headers() self.wfile.write(bytearray(res, "utf8"))
def check_node(self, node, pos_x): waiting = ["⬘", "⬙", "⬖", "⬗"] wait = 0 for line in ping(node, '-c', '4', _iter=True, _ok_code=[0, 1, 2]): if '100% packet loss' in line: return 1 elif '0% packet loss' in line: return 0 elif 'packet loss' in line: return 3 elif 'error' in line.lower(): return 2 self.addstr(pos_x, 0, waiting[wait] + " " + node, self.color.cyan_on_black) self.updatescr() wait += 1 if wait >= len(waiting): wait = 0 return 3
def check_internet_connection(self): if _platform == "Linux": try: output = sh.ping("-c", "5", "-w", "5", ICMP_TARGET) # XXX should redirect this to netcheck logger. # and don't clutter main log. logger.debug('Network appears to be up.') except sh.ErrorReturnCode_1 as e: packet_loss = re.findall("\d+% packet loss", e.message)[0] logger.debug("Unidentified Connection Error: " + packet_loss) if not self.is_internet_up(): error = "No valid internet connection found." else: error = "Provider server appears to be down." logger.error(error) raise exceptions.NoInternetConnection(error) else: raise NotImplementedError
def __init__(self, number, debug=False, sanity_checks=True): from fpesocketconnection import FPESocketConnection from unit_tests import check_house_keeping_voltages # First sanity check: ping the observatory simulator if not ping(): raise Exception("Cannot ping 192.168.100.1") self._debug = debug self._dir = os.path.dirname(os.path.realpath(__file__)) self._reset_in_progress = False self.fpe_number = number self.connection = FPESocketConnection(5554 + number, self._debug) # self.ops implemented with lazy getter self._ops = None # Second sanity check: check if frames are running, get the observatory simulator version original_frames_running_status = None if sanity_checks: try: original_frames_running_status = self.frames_running_status except Exception as e: raise type(e)( "Could not read if frames are running on the Observatory Simulator... {0}\n".format(str(e)) + "Are you sure the firmware for the Observatory Simulator is properly installed?") try: version = self.version if self._debug: print version except Exception as e: raise type(e)("Could not read Observatory Simulator version... {0}\n".format(str(e)) + "Are you sure you firmware for the Observatory Simulator is properly installed?") # Run sanity checks on the FPE to make sure basic functions are working (if specified) if sanity_checks: check_house_keeping_voltages(self) if original_frames_running_status is not None: self.frames_running_status = original_frames_running_status
def run(self): while True: query = self.queue.get() out = None if query.type == "ping": out = ping(query.query) elif query.type == "ping6": out = ping6(query.query) elif query.type == "trace": out = traceroute4(query.query) elif query.type == "trace6": out = traceroute6(query.query) elif query.type == "mtr": out = mtr4(query.query) elif query.type == "mtr6": out = mtr6(query.query) if out: print "Processed query",str(query.id) send_response(query, out) else: print "Unable to process query",str(query.id),"- invalid type",type
def run(self): while True: query = self.queue.get() out = None if query.type == "ping": out = ping(query.query) elif query.type == "ping6": out = ping6(query.query) elif query.type == "trace": out = traceroute4(query.query) elif query.type == "trace6": out = traceroute6(query.query) elif query.type == "mtr": out = mtr4(query.query) elif query.type == "mtr6": out = mtr6(query.query) if out: print "Processed query", str(query.id) send_response(query, out) else: print "Unable to process query", str( query.id), "- invalid type", type
def can_talk(local, remote, printer): printer("Pinging {} -> {}".format(remote, local)) with Indent(printer): printer('''adb shell 'ping -c 4 {} && echo SUCCESS || echo FAIL' '''.format(local)) with Indent(printer): remote2local = str(adb(['shell', 'ping -c 4 {} && echo SUCCESS || echo FAIL'.format(local)])) printer(remote2local) if 'SUCCESS' in remote2local: printer("Pinging {} -> {}".format(local, remote)) with Indent(printer): printer('ping -c 4 {}'.format(local)) with Indent(printer): try: local2remote = ping(['-c', '4', remote]) except sh.ErrorReturnCode as err: local2remote = err printer(local2remote) if local2remote.exit_code == 0: return True return False
def ping(host): '''ping the specified host. :param host: the name or ip of the host ''' try: result = sh.ping("-o", "-c", "1", host).strip().split("\n") except: pass try: (attributes, values) = result[-1].replace("round-trip", "")\ .strip().split("=") attributes = attributes.strip().split("/") values = values.strip().split("/") data = dict(zip(attributes, values)) data['loss'] = result[-2].split(",")[2].split("%")[0].strip() + "%" except: data = {} data['host'] = host return data
def setup_networking(ob_num: int): """Sets up networking. Installs some debs manually that are required for configuring networking, since we don't yet have networking and can't apt install them. Then configures DNS and network interfaces, then bounces the network interfaces. """ print(" === Setting up networking === ") # Install network management packages manually via dpkg, since we can't apt # install them without networking already setup. print("Installing dependencies for setting up networking...") dpkg("-i", *glob("./*.deb")) print("Configuring resolved...") # Default to the Mikrotik router for DNS, with a fallback of Google's DNS sed("-i", "s/^#DNS=$/DNS=172.27.31.254 8.8.8.8/g", "/etc/systemd/resolved.conf") sed("-i", "s/^#FallbackDNS=$/FallbackDNS=8.8.8.8 8.8.4.4/g", "/etc/systemd/resolved.conf") systemctl("restart", "systemd-resolved") # Not sure if still used, but some things might be expecting orange boxen to # have this configuration file. with open("/etc/orange-box.conf", "w") as f: f.writelines([f"orangebox_number={ob_num}"]) # Disable the external ethernet port (en*) and use both of the internal # ones (enx*). The enx* interfaces map to vlan1 and vlan2, which in turn # get mapped to `172.27.{orange box #}.X` and `172.27.{orange box # + 2}.X`, # respectively. They are both bridged to the wireless network that the # orange box is connected to, hence not needing en* connected. print("Writing network configuration...") interfaces = list( sorted( Path(iface).name for iface in glob("/sys/class/net/*") if Path(iface).name.startswith("en"))) internal_ips = [f"172.27.{ob_num}.1", f"172.27.{ob_num + 2}.1"] gateway_ips = [f"172.27.{ob_num + 1}.254", f"172.27.{ob_num + 3}.254"] sh.ip("addr", "flush", "dev", interfaces[1]) sh.ifconfig(interfaces[1], f"{internal_ips[1]}/23") systemctl("stop", "NetworkManager") systemctl("disable", "NetworkManager") with open("/etc/network/interfaces", "w") as f: f.write( textwrap.dedent(f""" # These are generated by orange-box build scripts auto lo iface lo inet loopback auto {interfaces[0]} iface {interfaces[0]} inet manual auto {interfaces[1]} iface {interfaces[1]} inet manual auto {interfaces[2]} iface {interfaces[2]} inet manual auto br0 iface br0 inet static address {internal_ips[0]} netmask 255.255.254.0 gateway {gateway_ips[0]} dns-nameservers {internal_ips[0]} {gateway_ips[0]} bridge_ports {interfaces[1]} bridge_stp off bridge_fd 0 bridge_maxwait 0 auto br1 iface br1 inet static address {internal_ips[1]} netmask 255.255.254.0 bridge_ports {interfaces[2]} bridge_stp off bridge_fd 0 bridge_maxwait 0""")) print("Restarting network interfaces...") bridges = ["br0", "br1"] # Take down all of the interfaces for iface in interfaces + bridges: sh.ifdown("--force", iface) # Bring up all interfaces except enp* for iface in interfaces[1:] + bridges: sh.ifup("--force", iface) print("Waiting for network to come up...") for _ in range(60): try: ping("-c1", "8.8.8.8") break except sh.ErrorReturnCode_1: print(" - Still waiting for 8.8.8.8...") else: print("Waited too long for network to come up.") print("Please fix the network.") sys.exit(1) print("Waiting for DNS to come up...") for _ in range(60): try: ping("-c1", "launchpad.net") break except (sh.ErrorReturnCode_1, sh.ErrorReturnCode_2): print(" - Still waiting for launchpad.net...") else: print("Waited too long for DNS to come up.") print("Please fix the DNS.") sys.exit(1)
#Script to change the packet data or information from subprocess import check_output import subprocess import pcap,dpkt from scapy.all import * import sh #below is to check all ips that are active in the network ip = check_output(['hostname', '--all-ip-addresses']) ip= ip.rsplit('.',1)[0] strs="" for num in range(1,40): ips=ip+"."+str(num) try: sh.ping(ips,"-c 1",_out="/dev/null") print(ips) strs=strs+ips except sh.ErrorReturnCode_1: pass print("Press ctrl+c") a=sniff() a.nsummary() pc = pcap.pcap() # construct pcap object #Here, instead of tcp you can add any protocol. #It will capture the packet in the network pc.setfilter('tcp') # filter out unwanted packets for timestamp, packet in pc: print (dpkt.ethernet.Ethernet(packet)) for ptime,pdata in pc: ptime = int(ptime) p=dpkt.ethernet.Ethernet(pdata)
#!/usr/bin/python import ipaddress import sh user_input = raw_input("Enter subnet x.x.x.0/24: ") network = ipaddress.ip_network(unicode(user_input)) for i in network.hosts(): try: sh.ping(i, "-c 1") print i, "is online" except sh.ErrorReturnCode_1: print i, "is offline"