def repeat(): for ip in server_list: response = os.popen(f"ping {ip}").read() if "Received = 0" in response: print("-" * 50) print(f"Status: Down {ip} Ping Unsuccessful") print(str(datetime.now())) print("") traceroute(f'{ip}', maxttl=15) try: server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login(sender_email, password) subject = f"[IP UNREACHABLE] : IP {ip}" body = f"Ping Status Monitor Unreachable for IP : {ip} " message = f"Subject: {subject}\n\n{body}" server.sendmail(sender_email, rec_email, message) print("-" * 50) except: print("Login Error to Mail Server") else: print("-" * 50) print(f"Status: Up {ip} Ping Successful") print("Date: " + str(datetime.now())) print("-" * 50)
def netGraph(): index = 0 if len(sys.argv) > 1: pgm = sys.argv[0] csvFile = sys.argv[1] logger.info(u"%s - %s" % (pgm, csvFile)) index = 0 else: csvFile = u".%stop500.csv" % os.sep index = 1 NUM_SITES = 500 logger.info(u"Start...") logger.debug(u"IP : %s" % IP) logger.info(u"%sroute : %s" % (os.linesep, conf.route)) n = 0 r = u = None # # This MUST be a string. not unicode! # site = "www.disney.com" logger.info(u"Traceroute for %s" % site) rt, ut = traceroute(site, maxttl=20) # rt.show() with open(csvFile, 'rb') as csvfile: # Skip first line csvfile.readline() siteRow = csv.reader(csvfile, delimiter=',', quotechar='"') for row in siteRow: if index == 0: site = row[index] else: site = row[index][:-1] if n > NUM_SITES: break else: logger.info(u"%s%d - %s ->%s" % (os.linesep, n, site[-3:], site)) if True or site[-3:] in (u"com", u"gov", u"org"): try: r, u = traceroute(site, maxttl=20) rt = rt + r n += 1 except Exception, msg: logger.info(u"%s" % msg)
def traceroute_core(): print("\n_____Traceroute Parameters_____") # user inputs target to traceroute target=[] numberOfTargets=int(input("Number of Targets: ")) x=0 for x in range(numberOfTargets): target.append(input("Target "+str(x+1)+": ")) # user inputs maximum time to live maxTimeToLive=int(input("Maximum Time To Live: ")) # Tracerout the target with respect to the maxttl traceroute(target,maxttl=maxTimeToLive)
def trace_route(target, verbose=0, show=True, store=True): ans, uans = traceroute(target=target, dport=80, minttl=1, maxttl=30, sport=RandShort(), timeout=5, verbose=verbose) route_dict = ans.get_trace() dst = list(route_dict.keys())[0] src = route_dict[dst][1][0] log.info("trace route from " + src + " to " + dst) if show: log.debug(route_dict[dst]) # pp = pprint.PrettyPrinter(indent=4) # pp.pprint(route_dict) if store: file_name = src + "-" + dst with open("./RawTopoData/" + file_name + ".txt", 'w') as f: for iter in route_dict[dst]: f.write(route_dict[dst][iter][0] + "\n") log.info("route info " + file_name + " stored.")
def trace_route(self): edges = set() try: network = list(ipaddress.IPv4Network(self.IPEntry.get() + '/' + self.MaskEntry.get())) res, _ = traceroute(list(map(lambda x: str(x), network))) if not hasattr(self, 'res'): self.res = res else: self.res = self.res + res tr_dict = dict() help_dict = dict() for r in self.res: if r[0].dst in tr_dict: if r[1].src in help_dict[r[0].dst]: continue tr_dict[r[0].dst][r[0].ttl] = r[1].src help_dict[r[0].dst].add(r[1].src) else: tr_dict[r[0].dst] = {r[0].ttl: r[1].src} help_dict[r[0].dst] = {r[1].src} for ttl_dict in tr_dict.values(): last_src = 'localhost' for ttl in sorted(ttl_dict.keys()): edges.add((last_src, ttl_dict[ttl])) last_src = ttl_dict[ttl] except Exception as e: print(e) edges.add(('localhost', 'localhost')) return edges
def run(self): print(f"TracerouteThread: starting traceroute: target = {self.target}") try: traceroute_output = traceroute(self.target, verbose=0) self.process_traceroute(traceroute_output[0]) except BaseException as e: print(f"!!! Caught error attempting to do traceroute: {e}") print(f"\n\n-----> TracerouteThread: competed traceroute")
def trace_route(self, graph_type, file_out=None): self.result, unans = traceroute(self.targets) if graph_type == "graphviz": if file_out: self.result.graph() else: self.result.graph(target=file_out) elif graph_type == "3d": self.result.trace3D() else: print("Unsupported graph type. Options include: graphviz and 3d.")
def netGraph(): index = 0 domainFile = u"data/disney_20160521.csv" index = 1 n = 0 NUM_SITES = 200 logger.info(u"Start...") logger.debug(u"IP : %s" % IP) logger.info(u"%sroute : %s" % (os.linesep, conf.route)) # # This MUST be a string. not unicode! # site = "www.disney.com" logger.info(u"Traceroute for %s" % site) rt, ut = traceroute(site, maxttl=20) # rt.show() with open(domainFile, "rb") as dfile: # Skip first line urls = dfile.readlines() for url in urls: n += 1 url = url.strip() logger.info(u"%s%d - %s" % (os.linesep, n, url)) try: r, u = traceroute(url, maxttl=20) rt = rt + r n += 1 except Exception, msg: logger.info(u"%s" % msg)
def check_traceroute(ip, ipv6=False): response = None unanswered = None if ipv6: response, unanswered = traceroute6(ip, maxttl=30) else: response, unanswered = traceroute(ip, maxttl=30) result = [] for send, receive in response: result.append( dict({ 'ttl': send.ttl, 'src': receive.src, 'time_sent': send.sent_time, 'time_received': receive.time })) return result
def tracecrt(type): global host_list if type == 'dns': for host in host_list: ans, unans = traceroute(host, l4=UDP(sport=random.randint(1025, 65534)) / DNS(qd=DNSQR(qname=host))) if type == 'tcp': for host in host_list: ans, unans = sr(IP(dst=host, ttl=(1, 10)) / TCP(dport=53, flags="S"), verbose=0) ans.summary(lambda s, r: r.sprintf( "%IP.src%\t{ICMP:%ICMP.type%}\t{TCP:%TCP.flags%}")) if type == 'udp': for host in host_list: res, unans = sr(IP(dst=host, ttl=(1, 20)) / UDP() / DNS(qd=DNSQR(qname=host)), verbose=0) res.make_table(lambda s, r: (s.dst, s.ttl, r.src))
def traceroute_graph(self): all_ips = [] for network, network_nodes in self.live_network_hosts.items(): for network_node in network_nodes: all_ips.append(str(network_node.ip)) if all_ips: res, unans = traceroute(all_ips, dport=[80, 443], maxttl=20, retry=-2) if res: import matplotlib.pyplot as plt import datetime import networkx as nx # res.conversations(draw=True, getsrcdst=lambda x:(x['IP'].src + "\n" + resolve_ip(x['IP'].src), x['IP'].dst + "\n" + resolve_ip(x['IP'].dst))) # res.conversations(draw=True, # edge_color='blue', # # NetworkX stuff # node_size=1600, # node_color='blue', # font_size=12, # alpha=0.3, # font_family='sans-serif') gr = res.conversations(draw=False) nx.draw(gr, with_labels=True, edge_color='blue', node_size=1600, node_color='blue', font_size=12, alpha=0.3, font_family='sans-serif') # filename = get_next_file_path(folder=os.path.abspath(os.path.join("graphs")), # base_filename="network_graph.png") filename = "network_graph_" + datetime.datetime.now().strftime("%Y_%m_%d__%H%M%S") + ".png" fullpath = os.path.abspath(os.path.join("graphs", filename)) plt.savefig(fullpath) logger.info("Created network graph at path: {0:s}".format(fullpath))
def trace_route(domain): """Performs a trace route and returns the SVG graph.""" # http://scapy.readthedocs.io/en/latest/usage.html#tcp-traceroute-2 # Return the cached domain if it exists. if domain in cached_trace_routes: return cached_trace_routes[domain] # Run trace route. result, _ = traceroute([domain], dport=[80,443], maxttl=20, retry=-2) # Convert to a dot graph. dot = result.graph(string=True) # Project simple details of the routes taken. routes = [(tcp.dst, ip.sprintf("%dst%:%sport%")) for tcp, ip in result] # Cache and return the result. result = json.dumps({ "graph": dot, "routes": routes }) cached_trace_routes[domain] = result return result
def get_user_input(): global final_report_string final_report_string += "<h1>Summary of Port Scan</h1>\n" # Use a try-catch loop to allow the user to CTRL+C and exit try: valid_ip = False # Just using gateway as default: this will be overwritten ip_addresses = ["192.168.1.1"] while not valid_ip: ip_addresses = input( "Enter comma-separated list of IPv4 Addresses that you want to scan, or a .txt file separated by " "newlines. Feel free to specify a subnet in CIDR notation: ") if ".txt" in ip_addresses: new_ips = [] print("Reading from file" + ip_addresses + "...") try: file = open(ip_addresses, "r") for line in file: # Ignore whitespace if line.strip(): new_ips.append(line) ip_addresses = new_ips valid_ip = check_valid_ip(ip_addresses) except FileNotFoundError: print("Oops! File not found! Please try again!") else: ip_addresses = ip_addresses.split(",") valid_ip = check_valid_ip(ip_addresses) # Traceroute option traceroute_option_selected = False while not traceroute_option_selected: should_traceroute = input("Would you like to run traceroute on all IPs? Y/N ") if should_traceroute.lower() == "y" or should_traceroute.lower() == "yes" or should_traceroute.lower() == "oui oui": traceroute_option_selected = True for ip_address in ip_addresses: traceroute(ip_address) elif should_traceroute.lower() == "n" or should_traceroute.lower() == "no": traceroute_option_selected = True else: print("Invalid option selected. Please try again!") valid_option = False port_option = "Default" # Single port, port range, multiple ports while not valid_option: port_option = input("Enter S for single port, M for multiple ports, P for port range: ") port_option = port_option.lower() if port_option == "s": valid_option = True elif port_option == "m": valid_option = True elif port_option == "p": valid_option = True else: print("Invalid option; please try again!") # Next, make sure their formatting is correct for S/M/P options ok_port_entered = False while not ok_port_entered: if port_option == "Default": print("Error with port selection. Aborting.") sys.exit(1) if port_option == "s": port_entered = input("Enter port number: ") # Check for valid ports if is_valid_port(port_entered): ok_port_entered = True for ip_address in ip_addresses: ip_address = ip_address.strip() scan_single_port(port_entered, ip_address) elif port_option == "m": ports_entered = input("Enter ports separated by a comma: ") ports_list = ports_entered.split(",") # Set it to true unless one of our ports is invalid ok_port_entered = True for port in ports_list: if not is_valid_port(port): ok_port_entered = False if ok_port_entered: for ip_address in ip_addresses: ip_address = ip_address.strip() scan_ports_list(ports_list, ip_address) elif port_option == "p": min_port = input("Enter minimum port number: ") max_port = input("Enter maximum port number: ") if min_port.isdigit() and max_port.isdigit() and is_valid_port(min_port) and is_valid_port( max_port) and int(min_port) < int(max_port): ok_port_entered = True for ip_address in ip_addresses: ip_address = ip_address.strip() scan_range_of_ports(min_port, max_port, ip_address) if not ok_port_entered: print("Invalid port(s)! Please try again.") except KeyboardInterrupt: print("\nInterrupt detected. Exiting...") sys.exit(1)
""" Perform a traceroute using scapy and create a graph from it. """ from scapy.layers.inet import traceroute # List of websites to trace site_list = ["google.com", "youtube.com", "wikipedia.org"] # Max number of hops to trace time_to_live = 30 # This creates the trace using TCP packets # and outputs the text result to the screen res, unans = traceroute(site_list, maxttl=time_to_live) # Alternatively, if TCP doesn't work well, try # using ICMP packets. # res, unans = traceroute(site_list, maxttl=time_to_live, l4=ICMP()) # Create a graph in SVG format res.graph(target="> traceroute_scapy.svg", type="svg") # Create a graph in PNG format res.graph(target="> traceroute_scapy.png", type="png")
from scapy.all import * from scapy.layers.inet import IP from scapy.layers.inet import traceroute from Logger import * logger = setupLogging(__name__) logger.setLevel(DEBUG) if __name__ == u"__main__": logger = setupLogging(__name__) logger.setLevel(INFO) logger.info(u"IP : %s" % IP) logger.info(u"%sconf.route : %s" % (os.linesep, conf.route)) n = 0 r = None u = None listSites = list() listSites.append("google-public-dns-b.google.com") listSites.append("google-public-dns-a.google.com") for site in listSites: logger.info("%sTraceroute for %s" % (os.linesep, site)) r, u = traceroute(site, maxttl=20)
# This displays the longitude and lattitude data to the user. print(data) #calls function to plot the lats and longs plot_lat_long(latCords, longCords) sys.argv inp = str(sys.argv[1]) print(inp) #will need to slow down the request frequency from 'dazzlepod.com' to find latitude and longitude SLEEP_SECONDS = 2 #hostname to traceroute to, hardcoded for in-class example hostname = inp # converting request hostname into IP address ip = socket.gethostbyname(hostname) # a good explanation of how traceroute works: https://www.youtube.com/watch?v=G05y9UKT69s # add maxttl=100 or more if you want to traceroute even deeper. #'res' -- results from traceroute res, _ = traceroute(ip, maxttl=64, verbose=0) # will store retrieved IPs here. ips = [] # find the latitude and longitude # going through the traceroute results and extracting IP addresses into the array for item in res.get_trace()[ip]: ips.append(res.get_trace()[ip][item][0]) find_and_plot_coordinates()
#!/usr/bin/python3 ## ## ## _this_is_actually_pretty_uh_pretty_nice__ ## _make_a_simple_networking_traceroute_chart__ ## ############################# from scapy.layers.inet import traceroute res4,unans=traceroute(["feanor.net", "4.2.2.2", "192.168.110.105"]) res4.show( ) res4.graph() ############################# ## ##
from scapy.layers.inet import traceroute res,unans = traceroute("8.8.8.8", dport=443, maxttl=5)
def run_traceroute(target_address): trace_output = traceroute(target_address)[0] return trace_output
def trace(self, ip: str, hits: int, byte_count: int, timeout: int, display_name: bool) -> go.Scattergeo: if isinstance(ipaddress.ip_address(ip), ipaddress.IPv6Address): ans, err = traceroute6(ip, maxttl=max_ttl_traceroute, dport=53, verbose=False, timeout=timeout) else: ans, err = traceroute(ip, maxttl=max_ttl_traceroute, dport=53, verbose=False, timeout=timeout) lats, lons, text, received = [], [], [], set() msg = f'Route to {ip}: ' count = 1 for sent_ip, received_ip in ans.res: res = self.get_lat_lon(received_ip.src) if res is not None: lat, lon = res[0], res[1] lats += [lat] lons += [lon] text += [ f'hop {count}: {received_ip.src if display_name else ""}' ] msg += f'{sent_ip.dst} [{lat}, {lon}], ' received.add(received_ip.src) count += 1 if ip not in received: res = self.get_lat_lon(ip) if res is not None: lat, lon = res[0], res[1] lats += [lat] lons += [lon] text += [f'hop {count}: {ip}'] logging.info(msg) mode = 'markers' if len(lats) == 1 else 'markers+lines' if display_name: try: name, _, _ = socket.gethostbyaddr(ip) host_addr = f'{name} | ' except Exception as e: logging.warning(f'Failed to get hostname of {ip}: {e}') host_addr = '' name = f'{host_addr} {ip}<br>' else: name = '' return go.Scattergeo(mode=mode, lon=lons, lat=lats, text=text, name=f'{name}{hits} packets, {byte_count} bytes', line={'width': int(math.log(byte_count)) / 2}, marker={ 'size': marker_size, 'symbol': 'square' })
# asn = db.asn(target).autonomous_system_organization #except geoip2.errors.AddressNotFoundError: # asn = "N.A." #print(result) return result['city'],result['country'] # TCP Traceroute from scapy.layers.inet import traceroute from scapy.layers.inet import traceroute_map # ans,unans = answered,unanswered packets list # They are of type TracerouteResult defined in scapy/inet.py # each entry in ans is a 2-entry tuple = send,recv packet ans,unans = traceroute(target, maxttl=60, verbose=0) index = len(ans) for i,v in enumerate(ans): if v[0].dst == v[1].src: index = i break # scapy parallelly sends requests for all TTL's and stores results from them. # Removing redundant entries after the packet reaches destination ans = ans[0:index+1] print("List of answered packets:") print() print("Target: {}:".format(ans[0][0].dst))
from scapy.layers.inet import traceroute res4,unans=traceroute(["127.0.0.1", "10.0.2.1", "192.168.0.1"]) res4.show( ) res4.graph()
import os import sys import time import subprocess import logging import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.layers.inet import traceroute domains = input('Please input one or more IP/domain: ') # 接受输入的域名或IP target = domains.strip() dport = [80] # 扫面的端口列表 if len(target) >= 1 and all([target]): res, unans = traceroute(target, dport=dport, retry=-2) # 启动路由跟踪 res.graph(target="> test.svg") time.sleep(1) subprocess.Popen("/usr/bin/convert test.svg test.png", shell=True) # SVG转PNG格式 else: print("IP/domain number of errors, exit")
def gui_input(): global final_report_string final_report_string += "<h1>Summary of Port Scan</h1>\n" print("GUI option selected! Launching GUI!") layout = [[sg.Text("Enter the IP address and port(s)! Can also add subnet in CIDR notation")], [sg.Text("IPs (Comma-Separated List)", size=(25, 1)), sg.InputText()], [sg.Text("Ports (Comma-Separated List)", size=(25, 1)), sg.InputText()], [sg.Checkbox("Run traceroute", default=True)], [sg.Text("Optional: choose a .txt file with newline-separated list of IPs", key="BROWSE"), sg.FileBrowse(key="-IN-")], [sg.Button("SCAN")]] window = sg.Window("Port Scanner", layout) while True: event, values = window.read() # Scan logic if event == "BROWSE": print("Browsing event") if event == "SCAN": ip_addresses = values[0] ports_list = values[1] should_run_traceroute = values[2] ip_addresses = ip_addresses.split(", ") specified_file = values["-IN-"] if specified_file != "": print("Scanning the following file for IP addresses: ") print(specified_file) try: f = open(specified_file, "r") for line in f: if line.strip(): ip_addresses.append(line) except FileNotFoundError: sg.Popup("Invalid file! Exiting...") break are_ips_valid = check_valid_ip(ip_addresses) if not are_ips_valid: sg.Popup("Oops! Invalid IPs! Please try again!") else: if should_run_traceroute: for ip in ip_addresses: traceroute(ip) valid_ports = True ports_list = ports_list.split(", ") for port in ports_list: try: port = int(port) except ValueError: sg.Popup("Oops! Ports should be a number! Please try again!") valid_ports = False break if not is_valid_port(port): sg.Popup("Oops! Invalid port found! Please try again!") valid_ports = False break if not valid_ports: break else: for ip in ip_addresses: scan_ports_list(ports_list, ip) break elif event == sg.WIN_CLOSED: break window.close()
# To print the attributes of ICMP: ICMP().show() packets: tuple = sr(IP(dst="192.168.1.254") / ICMP(code=(0, 3))) print(f'Number of packets tuple (request, response): {len(list(packets)):d}') req_resp_list: SndRcvList for req_resp_list in packets: req_resp_list.show() # Only send and receive one packet. packet: Packet = sr1(IP(dst="www.slashdot.org") / ICMP() / "XXXXXXXXXXX") packet.show() print("\n--------------------------------------------------\n") # Using traceroute results: Tuple[TracerouteResult] = traceroute(["google.fr", "yahoo.fr"]) packets: PacketList for packets in results: print("\n--------------------------------------------------\n") packets.summary() # sudo apt-get install net-tools # sudo ifconfig | grep -i mask result: Tuple[ARPingResult, PacketList] = arping("10.0.0.0/24") print("ARPing result:") print(result[0]) print(f"List of packets ({len(list(result[1])):d})") packet: Packet for packet in result[1]: packet.show()
import socket from scapy.layers.inet import traceroute addr = socket.gethostbyname('www.baidu.com') target = [addr] result, unans = traceroute(target, maxttl=10)
from scapy.layers.inet import traceroute res4, unans = traceroute( ["www.google.com", "www.facebook.com", "www.yahoo.com"]) res4.show()