def find_service_name(): protocolname = 'tcp' for port in [25, 80]: print "Port:%s => service name:%s" % \ (port, socket.getservbyport(port, protocolname)) print "Port:%s => service name:%s" % \ (53, socket.getservbyport(53, 'udp'))
def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6', 'freebsd7', 'darwin'): # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except socket.error: pass else: raise socket.error # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf it it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except socket.error: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service)
def find_serv_name(): protocolname = 'tcp' print('\n') for port in [80,8000,8080,25,22,21,20,7]: print ("Port: {!s} => service.name {!s}".format( port, socket.getservbyport(port,protocolname))) print ("Port: {!s} => service.name {!s}".format( 53, socket.getservbyport(53, 'udp')))
def find_service_name(): protocol = 'tcp' for port in [25, 80]: service = socket.getservbyport(port, protocol) print "Port: %d ==> Service name: %s" %(port, service) port = 53 print "Port: %d ==> Service name: %s" %(port, socket.getservbyport(port, 'udp'))
def find_service_name (): protocolname = 'tcp' for port in [80,25]: print "Port : %s => service name: %s" %(port, socket.getservbyport(port, protocolname)) port = 53 protocolname = 'udp' print "Port: %s => service name : %s" %(port, socket.getservbyport(port, protocolname))
def find_service_name(): print("--- Finding a service name, given the port and protocol ---") protocolname = 'tcp' for port in [80, 25, 443]: # iterates over an array print "Port: %s => service name: %s" %(port, socket.getservbyport(port, protocolname)) # A UDP protocol port test print "Port: %s => service name: %s" %(53, socket.getservbyport(53, 'udp'))
def _get_network_connections(): try: netstat = subprocess.Popen(["/bin/netstat","-atn"], stdout=subprocess.PIPE, close_fds=True).communicate()[0] except: netstat = subprocess.Popen(["/usr/sbin/netstat","-atn"], stdout=subprocess.PIPE, close_fds=True).communicate()[0] connections = {} listen_connections = [] established_connections = [] for line in netstat.split('\n'): if("tcp" in line or "udp" in line): line = re.split(" +", line) proto = line[0] recvq = line[1] sendq = line[2] local_address = line[3] foreign_address = line[4] state = line[5] local_address_port = local_address.split(':')[-1:][0] foreign_address_port = foreign_address.split(':')[-1:][0] local_address_port_resolved = "" foreign_address_port_resolved = "" if(local_address_port!="*"): try: local_address_port_resolved = socket.getservbyport(int(local_address_port)) except: pass if(foreign_address_port!="*"): try: foreign_address_port_resolved = socket.getservbyport(int(foreign_address_port)) except: pass if(state=="LISTEN"): listen_connections.append([state, proto, recvq, sendq, local_address, local_address_port, local_address_port_resolved, foreign_address, foreign_address_port, foreign_address_port_resolved] ) #print state, proto, recvq, sendq, local_address, local_address_port, local_address_port_resolved, foreign_address, foreign_address_port, foreign_address_port_resolved if(state=="ESTABLISHED"): established_connections.append([state, proto, recvq, sendq, local_address, local_address_port, local_address_port_resolved, foreign_address, foreign_address_port, foreign_address_port_resolved] ) #print state, proto, recvq, sendq, local_address, local_address_port, local_address_port_resolved, foreign_address, foreign_address_port, foreign_address_port_resolved connections['listen'] = listen_connections connections['established'] = established_connections connections['description'] = "Active Internet Connections (including servers)" return connections
def find_service_name(): protocolname = "tcp" # try: # except : # print "ERROR" for port in range(1, 65535): try: print "port: %s => service name: %s" % (port, socket.getservbyport(port, protocolname)) except: # print "ERROR" pass print "port: %s => service name: %s" % (53, socket.getservbyport(53, "udp"))
def service(self): # Resolve ports to their services, if known service = "unknown" try: # Try service of sending peer first service = socket.getservbyport(self.src_port) except OSError: # Resolving the sport did not work, trying dport try: service = socket.getservbyport(self.dest_port) except OSError: pass return service
def getServiceNameByPort(_port = None): if _port != None: if isinstance(_port, int): #通过端口号获得服务名 print "Port: %s => Service name: %s" % (_port, socket.getservbyport(_port)) if isinstance(_port, str): #通过服务名获得端口号 print "Service name: %s => Port: %s" % (_port, socket.getservbyname(_port)) else: for _port in range(100): try: print "Port: %s => Service name: %s" % (_port, socket.getservbyport(_port)) except: pass
def scan(daemon, host, port): s = socket.socket() protocolname = 'tcp' s.settimeout(0.1) if s.connect_ex((host, port)) == 0: try: print "%4d open => tcp service name: %s" %(port,socket.getservbyport(port,protocolname)) daemon.trigger.emit("%4d open => tcp service name: %s" %(port,socket.getservbyport(port,protocolname))) except: print port, 'open => tcp service name: No Found' daemon.trigger.emit('%4d open => tcp service name: No Found'%port) else: pass s.close()
def url_is_local(arg): """ Returns True if the given url points to localhost. We consider all URLs which explicitly define a port as non-local, because it looks like someone wants to explicitly use some protocol -- `ssh://localost:2222/` is likely to point at an ssh tunnel. If, however, the port matches the default port for the given protocol, we consider it local again -- `ssh://localhost:22/` is most likely a real local activity. Note that the schema set operates on substring level, so that we will accept port 22 for `ssh` and also for `sge+ssh` -- this may break in corner cases (altough I can't think of any right now). """ u = saga.Url(arg) if not host_is_local(u.host): return False # host is local, but what does the port indicate? if u.port and u.port > 0: try: if socket.getservbyport(u.port) in u.schema: # some non-default port is used -- consider remote return False except: # unknown service port --assume this is non-standard... return False # port is not set or points to default port for service return True
def sendToFaraday(self, url): api = xmlrpc.client.ServerProxy(url) for host in self.result['vulnerables']: h_id = api.createAndAddHost(host['address'],"") i_id = api.createAndAddInterface( h_id, host['address'], "00:00:00:00:00:00", host['address'], "0.0.0.0", "0.0.0.0", [], "0000:0000:0000:0000:0000:0000:0000:0000", "00", "0000:0000:0000:0000:0000:0000:0000:0000", [], "", socket.gethostbyaddr(host['address'])[0] ) for port in self.ports: s_id = api.createAndAddServiceToInterface( h_id, i_id, socket.getservbyport(int(port)), self.getPortType(), port, "open", "", host['evidence'] )
def probe_ports(target, min_port_num, max_port_num, evasive): #iterates through ports on a target and tries to establish a socket connection #records the ports to which a connection could be established open_ports = [] #typically, will iterate from port 0 to port 65535 #if evasive mode is enabled, will iterate from port 65535 down to port 0 #to avoid detection by psdetect.py if not evasive: port_nums_rng = range(min_port_num, max_port_num + 1) else: port_nums_rng = range(max_port_num, min_port_num - 1, -1) for curr_port_num in port_nums_rng: try: #record if a connection to curr_port_num can be successfully established s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect( (target, curr_port_num) ) open_ports.append( (curr_port_num, socket.getservbyport(curr_port_num, 'tcp')) ) s.close() except socket.error: #if a connection could not be established, do nothing pass #return ports in sorted order if evasive: open_ports.sort() return open_ports
def scan(self,ip): # socket.setdefaulttimeout(0.5) try: for port in range(1,1024): sock = self.openPort(ip,port) if sock: service = self.bgrabber(sock) if service: print "[+] Open: {}: {}".format(port,service.strip()) else: try: svc = socket.getservbyport(port) print "[+] Open: {}: {}".format(port,svc.strip()) except: print "[+] Open: {}: unknown".format(port) sock.close() # else: # print "[-] Closed: {}".format(port) # except: # print 'unknown error ... f**k' # pass # except KeyboardInterrupt: print "You pressed Ctrl+C" sys.exit()
def check_apache_running(self, apache_service): """Checks if Apache service is running on port 80.""" print "Checking Apache service......", serv_err_msg = health_check_utils.check_service_running(self.NAME, apache_service) if not serv_err_msg == "": self._set_status(0, serv_err_msg) if 'http' != socket.getservbyport(80): self._set_status( 0, "[%s]Error: Apache is not listening on port 80." % self.NAME) try: html = urllib2.urlopen('http://localhost') content = html.geturl() if "http://localhost/ods/ods.html" != content: self._set_status( 0, "[%s]Error: Compass web is not redirected by Apache.") except Exception: self._set_status( 0, "[%s]Error: Apache is not listening on port 80." % self.NAME) return True
def addport( csvline, domain=defaultdomain ): """ Adds a network port to the FMC """ proto,port,name,description = csvline.split(",") post_data = { "type": "ProtocolPortObject" } try: #Checks if proto is a string and a known protocol socket.getprotobyname( proto ) except: try: #Check if protocol is a number int( protocol ) + 1 except: raise ValueError( "addport", "ERROR", "Unknown value: {value} for {field} in csv line: {line}".format( value=repr( proto ), field="protocol", line=repr( csvline ) ) ) post_data[ "protocol" ] = proto try: portname = socket.getservbyname( port ) except: try: portname = socket.getservbyport( port ) except: raise ValueError( "addport", "ERROR", "Unknown value: {value} for {field} in csv line: {line}".format( value=repr( port ), field="port", line=repr( csvline ) ) ) post_data[ "port" ] = port post_data[ "overridable" ] = "true" post_data[ "description" ] = description post_data[ "name" ] = name api_path = "/api/fmc_config/v1/domain/" + domain + "/object/protocolportobjects" json_resp = requesttofmc( api_path, post_data ) objectadded( json_resp [ "name" ], json_resp [ "type" ], json_resp [ "id" ] ) return True
def find_service_name(): protocolname = "tcp" for port in range(20, 40): try: print "Port: %s => service name: %s" % (port, socket.getservbyport(port, protocolname)) except socket.error, err_msg: print "%s: %s" % (port, err_msg)
def __tcp_callback(self, pkt): port = pkt.getlayer("TCP").dport if pkt.getlayer("IP"): dst = pkt.getlayer("IP").dst else: dst = pkt.getlayer("IPv6").dst if pkt.getlayer("Raw"): payload = pkt.getlayer("Raw").load else : payload = None if int(port) in self.dissectors.keys() and payload: for name, regex in self.dissectors[int(port)]: p = re.compile(regex) m = p.match(payload) if m: item = m.group(1).rstrip('\r\n') try: s_name = getservbyport(port) except socket.error: s_name = "unknown" self.cc.ok("found %s login: %s = %s [ %s:%s ]\n" % (s_name, name, self.cc.cc_text('red', item), dst, str(port))) self.save_to_file(self.filename, "found %s login: %s = %s [ %s:%s ]\n" % (s_name, name, item, dst, str(port)))
def find_service_name_tcp(): protocol_name = 'tcp' for port in [80, 25]: print('Port: {} => service name: {} Protocal: {}'.format( port, socket.getservbyport(port, protocol_name), protocol_name))
def print_results(): if open_ports is not None: ports_sorted = sorted(open_ports) print "PORT STATE SERVICE" for port in ports_sorted: intend = " " * (8 - len(str(port))) try: service = socket.getservbyport(port) except: service = "unknown" print str(port) + intend + "open" + (" "*5) + service max_counter = max(windows, linux, mac) if [windows, linux, mac].count(max_counter) != 1: print "\nNot enough data to guess the os" else: if max_counter == windows: print "\nThe OS might be Windows" if max_counter == linux: print "\nThe OS might be Linux" if max_counter == mac: print "\nThe OS might be iOS/MAC" else: print "No open ports found"
def __str__(self, numeric=True, color=False, real=None, port=None): """provide an easy way to print this object""" proto = self.proto.upper().ljust(4) host = self.ip service = self.port logger.debug("Virtual:__str__ proto=%s,host=%s,service=%s" % (proto, host, service)) if self.proto.upper() == 'FWM': pass elif not numeric: try: try: host, aliaslist, addrlist = socket.gethostbyaddr(self.ip) except socket.herror: pass service = socket.getservbyport(int(self.port)) except socket.error: pass if self.proto.upper() == 'FWM': ipport = host.ljust(40) else: ipport = (host + ":" + service).ljust(40) sched = self.sched.ljust(7) if self.persistence: line = "%s %s %s persistence %s" % (proto, ipport, sched, self.persistence) else: line = "%s %s %s" % (proto, ipport, sched) if color: line = termcolor.colored(line, attrs=['bold']) output = [line] for r in self.realServers: if real: if r.ip == real: if port: if int(r.port) == port: output = [line] output.append(r.__str__(numeric,color)) else: output = [line] output.append(r.__str__(numeric,color)) else: output.append(r.__str__(numeric, color)) # If a real server is provided, don't return empty VIPs if real: if len(output) == 1: return '' # Add space between each VIP in the final output if output: output.append('') return '\n'.join(output)
def find_service_name(): protocolname = 'tcp' for port in range(1,1024): try: print "Port: %s => service name %s" %(port, socket.getservbyport(port, protocolname)) except: # print "Port: %s => service NULL" %port continue
def __init__(self, src_ip, src_port, dst_ip, dst_port, time): self.src_ip = src_ip self.src_port = int(src_port) self.dst_ip = dst_ip self.dst_port = int(dst_port) self.time = time try: self.proto = getservbyport(self.dst_port) significant_port = self.dst_port except OSError: try: self.proto = getservbyport(self.src_port) significant_port = self.src_port except OSError: self.proto = 'unknown' significant_port = min([self.src_port, self.dst_port]) self.protocols.update({significant_port: self.proto})
def port_scan(self,ip_to_scan,start_port_range,end_port_range): open_port=[] for port in range(int(start_port_range),int(end_port_range) + 1): sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.settimeout(0.2) try: sock.connect((ip_to_scan,port)) open_port.append(port) try: if port == 80: sock.send('GET HTTP/1.1 \r\n') received = sock.recv(1024) print "\nConnection to Port 80 Succeeded!\n" print "Recived Information: \n" print str(received) if port < 1023: try: service_name = socket.getservbyport(port, 'tcp') except Exception as error: print error print "\nAvailable Exploits:\n" os.system("searchsploit" + " " + service_name) else: sock.send('Hello, is it me you\'re looking for? \r\n') received = sock.recv(1024) print "\nConnection to Port " + str(port) + " Succeeded \n" print "Received Information: \n" print str(received) if port < 1023: try: service_name = socket.getservbyport(port, 'tcp') except Exception as error: print error print "\nAvailable Exploits:\n" os.system("searchsploit" + " " + service_name) except Exception as error: continue except Exception as error: continue return open_port
def find_service_name(): protocolname = 'tcp' port_range = range(1024) for port in port_range: try: print ("Port: %s => service name: %s" %(port, socket.getservbyport(port,protocolname))) except Exception as err: pass
def _get_label(self, proto=None): """ Show service associed of this port number. @arg proto [string] Only used if you want to call this function yourself """ try: if proto: return socket.getservbyport(int(self.label), proto) #elif self.args.has_key('proto'): # return socket.getservbyport(int(self.label), self.args['proto']) else: return socket.getservbyport(int(self.label)) except (TypeError, ValueError): return self.label except socket.error: return self.label
def getservbyport(port): """Like socket.getservbyport() but return a descriptive string if the service is not found.""" try: name = socket.getservbyport(port) except socket.error: name = "port-{0}".format(port) return name
def _get_service(self, portnum): """Returns the service name for a given port.""" try: service = socket.getservbyport(portnum) except Exception: service = "unknown" return service
def test(self): self.testProto("tcp") self.testProto("udp") try: self.serv_name = socket.getservbyport(self.port_number) self.testProto(self.serv_name) except socket.error: self.serv_name = "undef" pass
def convert_game(data): game = models.Game() game.name = data['game_name'] game.save() # red = models.PlayerTeam() red.name = 'Redcell' red.offensive = True red.color = 16711686 red.game = game red.save() # for blue in data['blueteams']: # blue_dns = models.DNS() blue_dns.ip = blue['dns'] blue_dns.save() # blue_team = models.PlayerTeam() blue_team.game = game blue_team.name = blue['name'] blue_team.save() # blue_range = models.Range() blue_range.subnet = '%s.0/24' % blue['nets'][0] blue_range.domain = '%s.com' % blue_team.name.lower().replace(' ', '-') blue_range.save() blue_range.dns.add(blue_dns) blue_range.save() # del blue_dns blue_team.assets = blue_range blue_team.save() # for host in blue['hosts']: blue_host = models.Host() blue_host.fqdn = host['hostname'] blue_host.ip = '127.0.0.1' blue_host.range = blue_range blue_host.save() # for service in host['services']: blue_service = models.Service() try: blue_service.port = int(service['port']) except ValueError: blue_service.port = 80 for protocol in SERVICE_PROTOCOLS: if protocol[1].lower() == service['protocol'].lower(): blue_service.protocol = protocol[0] break try: blue_service.value = int(service['value']) except ValueError: pass try: blue_service.name = getservbyport(blue_service.port) except OSError: blue_service.name = 'http' blue_service.application = blue_service.name blue_service.host = blue_host blue_service.save() # if 'content' in service: blue_content = models.Content() blue_content.format = 'imported' blue_content.data = json.dumps(service['content']) blue_content.save() blue_content.service = blue_service blue_content.save() if 'flags' in blue: for name, value in blue['flags'].items(): blue_flag = models.Flag() blue_flag.name = slugify(name) blue_flag.flag = '%s-%d' % (value['value'], randint( 0, 255)) blue_flag.description = value['answer'] blue_flag.host = choice(blue_range.hosts.all()) blue_flag.save() return game
def find_service_name(): protocolname = 'tcp' for port in [80, 25, 53, 8080, 22]: print("Port: {} => Service name: {}".format( port, socket.getservbyport(port, protocolname)))
# ----------------------------------------------------------- # demonstrates identifying services by its port name # # (C) 2016 Frank Hofmann, Berlin, Germany # Released under GNU Public License (GPL) # email [email protected] # # based on: A Simple TCP Client and Server described in the # book from Brandon Rhodes and John Goerzen: # Foundations of Python Network Programming # apress, 2010, ISBN 978-1-4302-3003-8 # ----------------------------------------------------------- import socket # define list of network protocols portList = [22, 80, 443] for port in portList: protocol = socket.getservbyport(port) # print port and protocol as well-formatted output print('%4i: %s' % (port, protocol))
def test_getservbyport(): assert getservbyport(80) == cpy_socket.getservbyport(80) assert getservbyport(80, 'tcp') == cpy_socket.getservbyport(80)
def find_service_name(): protocolname = 'tcp' for port in [80, 25]: print("Port: %s => service name: %s" % (port, socket.getservbyport(port, protocolname)))
def findServiceName(protocolName, ports): for port in ports: service = socket.getservbyport(port, protocolName) print 'Port: %s => service name: %s' % (port, service)
def process_host(host_element): global hosts status = "down" for status_element in host_element.getElementsByTagName("status"): status = status_element.getAttribute("state") if status != "up": return for address_element in host_element.getElementsByTagName("address"): if not address_element.getAttribute("addrtype") in [ "ipv4", "ipv6" ]: continue address = address_element.getAttribute("addr") break name = address for hostname_element in host_element.getElementsByTagName("hostname"): name = hostname_element.getAttribute("name") try: services = hosts[name]["services"] except: services = {} for port_element in host_element.getElementsByTagName("port"): state = "closed" for state_element in port_element.getElementsByTagName("state"): state = state_element.getAttribute("state") if state != "open": continue port = int(port_element.getAttribute("portid")) protocol = port_element.getAttribute("protocol") try: serv = socket.getservbyport(port, protocol) except: serv = str(port) try: if protocol == "tcp": command = tcp_service_commands[serv] elif protocol == "udp": command = udp_service_commands[serv] else: raise "Unknown protocol." except: command = protocol if command == "udp": continue services[serv] = { "command": command, "port": port } hosts[name] = { "name": name, "address": address, "services": services }
freq = 0 for j in xrange(3): udpsock.sendto("", (host, port)) try: data, addr = udpsock.recvfrom(1024) except socket.timeout: freq += 1 except Exception, e: if e.errno == 10054: pass else: print tuple(e) if freq == 3: try: print "%s:%4d open => udp service name: %s" % ( host, port, socket.getservbyport(port, protocolname)) except: print "%s:%4d open => udp service name: %s" % (host, port, "No Found") elif show: print port, 'Close' udpsock.close() def writeQ(queue, host_start, host_end, port_start, port_end): for host in xrange(ip2num(host_start), ip2num(host_end)): for port in xrange(port_start, port_end): queue.put((num2ip(host), port)) def readQ(queue, show, udp):
def find_service_name(port=input("Enter the service port: "), protocol=input("Enter the service protocol: ")): try: port = int(port) serv_name = socket.getservbyport(port, protocol) print("Port: %s => Service Name: %s" % (port, serv_name))
def find_server_name(): protocolname = 'tcp' for port in [80, 25]: print "Port: %s => service name: %s" % (port, socket.getservbyport(port, protocolname)) print "Port: %s => service name: %s" % (53,socket.getservbyport(53, 'udp'))
start = time.clock() totalOpen = 0 for i in range(0, 65535): #for each port check the connection #obtain service type and store port no and service type in a file #serv = socket(targetIP, [protocolname]) try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = s.connect_ex((targetIP, i)) try: serv = socket.getservbyport(i, "tcp") except: serv = 'NA' if (result == 0): print ('%d' % (i,) + ' (' + serv + ') was open') f = open("scanner.txt", "w+") f.write('%d' % (i,) + ' (' + serv + ') was open') totalOpen+=1 #close the file and the socket object when finished #then compute time elapsed and scan rate except: continue end = time.clock()
def checkListenersProc(): terminalWidth = run(TERMINAL_WIDTH) procListeners() addProcessNamesToInodes() tried = inodes try: cols = readOutput(terminalWidth)[0] cols = int(cols) except BaseException: cols = 80 # Print our own custom output header... proto = "Proto" addr = "Listening" pid = "PID" process = "Process" print(f"{COLOR_HEADER}{proto:^5} {addr:^25} {pid:>5} {process:^30}") # Could sort by anything: ip, port, proto, pid, command name # (or even the fd integer if that provided any insight whatsoever) def compareByPidOrPort(what): k, v = what # v = [ip, port, proto, pid, cmd] # - OR - # v = [ip, port, proto] # If we're not running as root we can't pid and command mappings for # the processes of other users, so sort the pids we did find at end # of list and show UNKNOWN entries first # (because the lines will be shorter most likely so the bigger visual # weight should be lower in the display table) try: # Pid available! Sort by first pid, subsort by IP then port. return (1, v[3], v[0], v[1]) except BaseException: # No pid available! Sort by port number then IP then... port again. return (0, v[1], v[0], v[1]) # Sort results by pid... for name, vals in sorted(tried.items(), key=compareByPidOrPort): attachedPids = vals[3:] if attachedPids: desc = [f"{pid:5} {' '.join(cmd)}" for pid, cmd in vals[3:]] else: # If not running as root, we won't have pid or process, so use # defaults desc = ["UNKNOWN (must be root for global pid mappings)"] port = vals[1] try: # Convert port integer to service name if possible port = socket.getservbyport(port) except BaseException: # If no match, just use port number directly. pass addr = f"{vals[0]}:{port}" proto = vals[2] # If IP address looks like it could be visible to the world, # throw up a color. # Note: due to port forwarding and NAT and other issues, # this clearly isn't exhaustive. if re.match(likelyLocalOnly, addr): colorNotice = COLOR_OKAY else: colorNotice = COLOR_WARNING isFirstLine = True for line in desc: if isFirstLine: output = f"{colorNotice}{proto:5} {addr:25} {line}" isFirstLine = False else: output = f"{' ':31} {line}" # Be a polite terminal citizen by limiting our width to user's width # (colors take up non-visible space, so add it to our col count) print(output[:cols + (len(colorNotice) if isFirstLine else 0)]) if ONLY_LOWEST_PID: break print(COLOR_END)
print("-" * 50) print("Scanning Target: " + ip) print("Scanning started at:" + str(datetime.now())) print("-" * 50) try: for port in ports: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(0.05) # returns an error indicator result = s.connect_ex((ip, port)) if result == 0: try: service = '/' + socket.getservbyport(port) except: service = "" print(f"Port {port}{service} is OPEN") s.close() except KeyboardInterrupt: print("\n Exitting Program !!!!") sys.exit() except: print("\n Fail.. !!!!") sys.exit() print(f"Scanning of {len(ports)} ports finished at:" + str(datetime.now()))
#!/bin/python import socket def findservicename(): protocolname = 'tcp' protocolName = socket.getservbyport(protocolname) for port in range(7004): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('eu-middleware-sb1', port)) if result == 0: print "Port {}: Open".format(port), 'server is runing' print("Port: %s => service name: %s" % (port, socket.getservbyport(protocolName))) #except socket.gaierror: # print 'Hostname could not be resolved. Exiting' # sys.exit() findservicename()
def add_commands(want): commandset = [] protocol_name = { "51": "ahp", "47": "gre", "1": "icmp", "2": "igmp", "4": "ip", "89": "ospf", "103": "pim", "6": "tcp", "17": "udp", "112": "vrrp", } if not want: return commandset command = "" afi = "ip" if want["afi"] == "ipv4" else "ipv6" for acl in want["acls"]: if "standard" in acl.keys() and acl["standard"]: command = afi + " access-list standard " + acl["name"] else: command = afi + " access-list " + acl["name"] commandset.append(command) if "aces" not in acl.keys(): continue for ace in acl["aces"]: command = "" if "sequence" in ace.keys(): command = str(ace["sequence"]) if "remark" in ace.keys(): command = command + " remark " + ace["remark"] if "fragment_rules" in ace.keys() and ace["fragment_rules"]: command = command + " fragment-rules" if "grant" in ace.keys(): command = command + " " + ace["grant"] if "vlan" in ace.keys(): command = command + " vlan " + ace["vlan"] if "protocol" in ace.keys(): protocol = ace["protocol"] if protocol.isdigit(): if protocol in protocol_name.keys(): protocol = protocol_name[protocol] command = command + " " + protocol if "source" in ace.keys(): if "any" in ace["source"].keys(): command = command + " any" elif "subnet_address" in ace["source"].keys(): command = command + " " + ace["source"]["subnet_address"] elif "host" in ace["source"].keys(): command = command + " host " + ace["source"]["host"] elif "address" in ace["source"].keys(): command = ( command + " " + ace["source"]["address"] + " " + ace["source"]["wildcard_bits"] ) if "port_protocol" in ace["source"].keys(): for op, val in ace["source"]["port_protocol"].items(): if val.isdigit(): val = socket.getservbyport(int(val)) command = ( command + " " + op + " " + val.replace("_", "-") ) if "destination" in ace.keys(): if "any" in ace["destination"].keys(): command = command + " any" elif "subnet_address" in ace["destination"].keys(): command = ( command + " " + ace["destination"]["subnet_address"] ) elif "host" in ace["destination"].keys(): command = command + " host " + ace["destination"]["host"] elif "address" in ace["destination"].keys(): command = ( command + " " + ace["destination"]["address"] + " " + ace["destination"]["wildcard_bits"] ) if "port_protocol" in ace["destination"].keys(): for op in ace["destination"]["port_protocol"].keys(): command = ( command + " " + op + " " + ace["destination"]["port_protocol"][op].replace( "_", "-" ) ) if "protocol_options" in ace.keys(): for proto in ace["protocol_options"].keys(): if proto == "icmp" or proto == "icmpv6": for icmp_msg in ace["protocol_options"][proto].keys(): command = ( command + " " + icmp_msg.replace("_", "-") ) elif proto == "ip" or proto == "ipv6": command = ( command + " nexthop-group " + ace["protocol_options"][proto]["nexthop_group"] ) elif proto == "tcp": for flag, val in ace["protocol_options"][proto][ "flags" ].items(): if val: command = command + " " + flag if "hop_limit" in ace.keys(): for op, val in ace["hop_limit"].items(): command = command + " hop-limit " + op + " " + val if "tracked" in ace.keys() and ace["tracked"]: command = command + " tracked" if "ttl" in ace.keys(): for op, val in ace["ttl"].items(): command = command + " ttl " + op + " " + str(val) if "fragments" in ace.keys(): command = command + " fragments" if "log" in ace.keys(): command = command + " log" commandset.append(command.strip()) return commandset
def findservicename(): protocolname = 'tcp' protocolName = socket.getservbyport(protocolname)
def ServerOnPort(Number_Port, Protocol): ServiceName = socket.getservbyport(Number_Port, Protocol) print("[+] port number %d : %s" % (Number_Port, ServiceName))
#!usr/bin/python """by:Abdallah""" import socket url = input('Enter url site: ') print('\n+' + '-' * 78 + '+') print('Scan Ports'.center(75)) print('+' + '-' * 78 + '+') print('\nPlease wait.!\n') for Port in range(0, 100): Scan = socket.socket(socket.AF_INET, socket.SOCK_STREAM) Search = Scan.connect_ex((url, Port)) if Search == 0: print('Open Port: %s -> %s '.center(30) % (Port, socket.getservbyport(Port))) Scan.close() print('\nFinish Scan\n'.center(30))
def show_virtual(self, host, port, protocol, numeric, color): result = list() args = [self.iptables, '-L', 'INPUT'] if port: portnum = utils.getportnum(port) try: portname = socket.getservbyport(int(portnum)) except socket.error: portname = portnum except OverflowError as e: logger.error("%s" % e) return list() if numeric: args.append('-n') hostnames = utils.gethostbyname_ex(host) else: # Turn this into a list so it behaves like the above case # And we only perform a list membership check hostnames = [socket.getfqdn(host)] # Nested try/except needed to catch exceptions in the "Except" try: try: logger.info("Running: %s" % " ".join(args)) output = subprocess.check_output(args) # python 2.6 compatibility code except AttributeError as e: output, stderr = subprocess.Popen( args, stdout=subprocess.PIPE).communicate() except OSError as e: logger.error("Problem with iptables - %s : %s" % (e.strerror, args[0])) return list() if output: lines = output.split('\n') for line in lines: # break the iptables output into tokens # assumptions: # 2nd item is the protocol - tokens[1] # 5th item is the hostname - tokens[4] # 7th item is the portname - tokens[6] tokens = line.split() if len(tokens) >= 7: if ((tokens[1] == protocol or tokens[2] == "all") and tokens[4] in hostnames and (not port or (tokens[6] == "dpt:" + str(portname) or tokens[6] == "dpt:" + str(portnum)))): if color: if line.startswith('ACCEPT'): result.append(termcolor.colored(line, 'green')) elif (line.startswith('REJECT') or line.startswith('DROP')): result.append(termcolor.colored(line, 'red')) else: result.append(line) else: result.append(line) # If we have any output, let's also display some headers if result: result.insert(0, '') result.insert(1, 'IP Packet filter rules') result.insert(2, '======================') return result
import socket target = str(input('IP address : ')) ports = [19, 20, 21, 22, 23, 24, 25, 80, 443] for p in ports: #ipV4 #TCP s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) r = s.connect_ex((target, p)) if r == 0: service = socket.getservbyport(p) print('the port {}:{} is open'.format(p, service)) #coded by chou@ibcher+
print("===============Questão 1===============") print("Item A) " + my_IP) print("Item B) " + my_host_name) print("Item C) ") for porta in range(10000): #Para 'porta' variando de 0 a 9999 #A função "getserverbyport('porta', 'protocolo') retorna o serviço usado pela #'porta' através do 'protocolo' especificado. # #Porém, é possível que nenhum serviço esteja sendo utilizado na porta #especificada. Se isso ocorrer, a função levanta o erro "OSError". Então #tratamos esse erro através do "try" e "except". Se OSError acontecer, a #variável que guarda o nome do serviço recebe "None". try: servico_tcp = socket.getservbyport(porta, 'tcp') except OSError: servico_tcp = None try: servico_udp = socket.getservbyport(porta, 'udp') except OSError: servico_udp = None print(porta, servico_tcp, servico_udp) #===============Questão 2=============== print("===============Questão 2===============") print("Item A) ") lista_de_sites = [ 'www.oci.org.br', 'olimpiada.ic.unicamp.br', 'www.wacom.com',
def portscanner(): print("[i] Syntax : Function") print( " 23,80,120 : Scans Specific Ports, e.g, Scans Port 23,80 and 120" ) print( " 23-80 : Scans a Range of Ports, e.g, Scans Port from 23 to 80" ) print(" 23 : Scans a single port, e.g, Scans Port 23") print(" all : Scans all ports from 20 to 5000") print(" ") portoption = raw_input("[+] Enter Range or Port:\n > ") wasmultiple = 0 wasrange = 0 wasone = 0 if ',' in portoption: wasmultiple = 1 multipleport = portoption.split(',') notexpected = 0 for i in multipleport: if not str(i).isdigit(): print("[!] Incorrect Syntax!") notexpected = 1 if notexpected == 1: again() totallength = multipleport elif '-' in portoption: wasrange = 1 rangeport = portoption.split('-') totalrange = range(int(rangeport[0]), int(rangeport[1]) + 1) if len(rangeport) != 2: print("[!] Incorrect Syntax!") again() totallength = totalrange elif portoption == 'all': totallength = range(20, 5000) elif portoption.isdigit(): wasone = 1 oneport = int(portoption) totallength = range(1) else: print("[+] Incorrect Syntax!") again() print("[+] Scanning %s Port/s on Target: %s") % (len(totallength), ip) ports = 5000 found = 1 protocolname = 'tcp' progress = 20 loopcondition = range(20, 5000) if portoption == 'all': loopcondition = range(20, 5000) ports = 5000 progress = 20 elif wasmultiple == 1: loopcondition = multipleport ports = int(len(multipleport)) progress = 0 #int(min(multipleport)) elif wasrange == 1: loopcondition = totalrange ports = int(rangeport[1]) progress = int(rangeport[0]) - 1 elif wasone == 1: onlyport = [] onlyport.append(portoption) loopcondition = onlyport progress = 0 ports = 1 else: loopcondition = range(20, 5000) for i in loopcondition: i = int(i) progress += 1 sys.stdout.write("\r[+] Progress %i / %s ..." % (progress, ports)) sys.stdout.flush() portconnect = socket.socket(socket.AF_INET, socket.SOCK_STREAM) response = portconnect.connect_ex((ip, i)) if (response == 0): print('\n | Port: ' + boldwhite + '%d' + reset + ' \n | Status: ' + green + 'OPEN' + reset + '\n | Service: ' + boldwhite + '%s' + reset + '\n') % (i, socket.getservbyport(i, protocolname)) found += 1 portconnect.close() if found == 1: print("\n | " + red + "No Open Ports Found!" + reset)
def clickrun(self): try: urllist = ["http","www."] filterlink = "{0}.".format(str(self.lineEdit.text())[:3]) filterurl = str(self.lineEdit.text())[:4] if (filterlink[:3].isdigit() == True and filterlink == filterurl) or filterurl in urllist: if (self.radioButton.isChecked() and str(self.lineEdit_2.text()).isdigit() == True and str(self.lineEdit_4.text()).isdigit() == True) or (self.radioButton_2.isChecked() and str(self.lineEdit_3.text()).isdigit() == True): if self.radioButton.isChecked(): if int(self.lineEdit_2.text()) < int(self.lineEdit_4.text()): self.lineEdit.setDisabled(True) self.lineEdit.setStyleSheet(disablestyle) self.pushButton.setDisabled(True) self.pushButton.setStyleSheet(disablebuttonstyle) self.pushButton_2.setEnabled(True) self.pushButton_2.setStyleSheet(enablebuttonstyle) self.radioButton.setDisabled(True) self.radioButton_2.setDisabled(True) self.lineEdit_2.setDisabled(True) self.lineEdit_4.setDisabled(True) self.lineEdit_2.setStyleSheet(disablestyle) self.lineEdit_4.setStyleSheet(disablestyle) progressBarvalue1 = (float(self.lineEdit_4.text()) - float(self.lineEdit_2.text()))+1 progressBarvalue = 100 / float(progressBarvalue1) progressBarvalue2 = 0 for iii in range(int(self.lineEdit_2.text()), int(self.lineEdit_4.text())+1): self.repaint() soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ipv4 = socket.gethostbyname(str(self.lineEdit.text())) check = soc.connect_ex((ipv4, iii)) if check == 0: portname = socket.getservbyport(iii) mssg = "Port {0}, Port_Name {1}, IP: {2} / State Open-{3} is Found <<<<".format(iii,portname,ipv4,check) saveinglist.append(mssg) self.listWidget.addItem(mssg) else: mssg = "Port {0}, IP: {1} / State Close-{2}, Not Found".format(iii, ipv4, check) saveinglist.append(mssg) self.listWidget.addItem(mssg) progressBarvalue2 += progressBarvalue self.progressBar.setValue(progressBarvalue2) else: self.listWidget.addItem("We must Port from hight of Port to") elif self.radioButton_2.isChecked(): self.lineEdit.setDisabled(True) self.lineEdit.setStyleSheet(disablestyle) self.pushButton.setDisabled(True) self.pushButton.setStyleSheet(disablebuttonstyle) self.pushButton_2.setEnabled(True) self.pushButton_2.setStyleSheet(enablebuttonstyle) self.radioButton.setDisabled(True) self.radioButton_2.setDisabled(True) self.lineEdit_3.setDisabled(True) self.lineEdit_3.setStyleSheet(disablestyle) soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ipv4 = socket.gethostbyname(str(self.lineEdit.text())) check = soc.connect_ex((ipv4, int(self.lineEdit_3.text()))) self.progressBar.setValue(100) if check == 0: portname = socket.getservbyport(int(self.lineEdit_3.text())) mssg = "Port {0}, Port_Name {1}, IP: {2} / State Open-{3} is Found <<<<".format(self.lineEdit_3.text(),portname,ipv4, check) saveinglist.append(mssg) self.listWidget.addItem(mssg) else: mssg = "Port {0}, IP: {1} / State Close-{2}, Not Found".format(self.lineEdit_3.text(), ipv4, check) saveinglist.append(mssg) self.listWidget.addItem(mssg) else: self.listWidget.addItem("Please write Port number and not write letters") else: self.listWidget.addItem("Enter Website or URL NOTE : We are must link at start www. / http") except: self.listWidget.addItem("Error...")
import socket from urllib.parse import urlunparse for port in [80, 443, 21, 70, 25, 143, 993, 110, 995]: url = '{}://example.com'.format(socket.getservbyport(port)) print(url)
################ print('\033[0;91m\ _____ _ _ _ ') print('/ ___/ | | | | / / ') print('| |___ | | | |/ / ') print('\___ \ _ | | | |\ \ ') print(' ___| | | |_| | | | \ \ ') print('/_____/ \_____/ |_| \_') print('\033[1;34m make with sajad.JK') ip = input("\===> ENTER YOUR IP TO START: ") t1 = datetime.now() print("Scanning Start.. %s Please Wait.. " % ip) sleep(1) #################### try: for port in range(1, 6553): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if (s.connect_ex((ip, port)) == 0): try: serv = socket.getservbyport(port) except socket.error: serv = "Unknown Service" print("Port %s Open Service:%s " % (port, serv)) t2 = datetime.now() t3 = t2 - t1 print("\033[0;31m\Scanning Completed On %s" % t3) except KeyboardInterrupt: print("\033[0;31m\See You Soon....!") ###############################
import socket port_numbers = input("Enter the port number: ") service = socket.getservbyport(int(port_numbers)) print("Port number", port_numbers, "runs service:", service.upper())
def test_getservbyport(): AreEqual(socket.getservbyport(80), "http")
#/python3 import socket def find_service_name(): protocolname = 'tcp' for port in [80, 25]: print("Port: %s => service name: %s" % (port, socket.getservbyport(port, protocolname))) print("Port: %s => service name: %s" % (53, socket.getservbyport(53, 'udp'))) if __name__ == '__main__': find_service_name()
def draw(self, graph, resolve_dns=False): if self.is_on_graph: return if self.cluster and self.cluster.lb_node is not None: # We already drew the LB cluster node return gnode = pd.Node(self.nodename) gnode.set('shape', 'record') subnet = get_subnet_by_ip(self.ip) if not subnet: color = 'gray' else: color = subnet.color gnode.set('color', color) # make the ports label # we need to add <p_foo> endpoint parts for each port pary = [] for portnum in sorted(self.ports.keys()): try: service = socket.getservbyport(portnum) except OSError: service = 'unknown' if portnum in self.prodvers and len(self.prodvers[portnum]): pary.append( '<p_%s>%s/%s\n[%s]' % (portnum, portnum, service, self.prodvers[portnum])) else: pary.append('<p_%s>%s/%s' % (portnum, portnum, service)) plabel = '%s' % '|'.join(pary) hlabel = str(self.ip) if not self.hostname and resolve_dns: try: hostname = socket.gethostbyaddr(str(self.ip))[0] logger.debug('%s -> %s' % (str(self.ip), hostname)) self.hostname = hostname except socket.herror: pass hostname = self.hostname if self.hostname and self.subnet and len(self.subnet.trimdomain): hostname = re.sub('\.%s$' % self.subnet.trimdomain, '', self.hostname) if hostname: hlabel = '%s\n\%s' % (self.ip, hostname) if self.cluster and self.cluster.has_vip(self.ip): hlabel = '%s\n%s' % ('VIP', hlabel) if self.cluster and self.cluster.type == 'lb': # LB clusters replace all nodes with a single one # to avoid drawing a bajillion lines. # Did we already make a node for this? if not self.cluster.lb_node: hlabel = '|'.join(self.cluster.rips) label = '{{%s}|{cluster ips:|%s}}' % (plabel, hlabel) gnode.set('label', label) self.cluster.lb_node = self.nodename else: # on the src node, the ports are on the right if self.is_src_node: label = '{%s|{%s}}' % (hlabel, plabel) gnode.set('label', label) self.draw_proxies(graph, resolve_dns) else: label = '{{%s}|%s}' % (plabel, hlabel) gnode.set('label', label) # if we're in a cluster, we'll be adding ourselves to a subgraph instead if self.cluster is not None: self.cluster.subgraph.add_node(gnode) else: graph.add_node(gnode) self.is_on_graph = True
def find_service_name(): protocol_name = 'tcp' # pass the port numbers here for port in [80,25]: print ("Port : ",port," Service : ", socket.getservbyport(port,protocol_name))