def lbvserver(self): vserver = self.args.vserver attr = self.args.attr services = self.args.services servers = self.args.servers if services: output = self.get_lbvserver_service_binding(vserver) for service in sorted(output.keys()): print service elif servers: output = self.get_lbvserver_service_binding(vserver) for service in sorted(output.keys()): try: # Looking up IPs via DNS instead of asking the Netscaler # for its service-to-server binding, since it is slow. print socket.gethostbyaddr(output[service])[0].split( '.')[0] except socket.herror as e: raise RuntimeError(e) else: output, attrs = self.get_lb() if attrs: utils.print_items_json(output, attr) else: print json.dumps(output)
def HandleAuthPacket(self, pkt): """Authentication packet handler. This method is called when a valid authenticating packet has been received. It is overriden in derived server class to add custom behaviour. @param pkt: packet to process @type pkt: Packet class instance """ self.log.debug("Received an authentication request at %s RADIUS server from\ %s" %(socket.gethostbyaddr(self.addr)[0], socket.gethostbyaddr(pkt.source[0])[0])) for attr in pkt.keys(): self.log.debug("RADIUS server recieved: %s : %s" % (attr, pkt[attr])) #Create the Radius response packet reply=self.CreateReplyPacket(pkt) #Send a Access Reject response if the user name is rejectme if pkt['User-Name'][0] == 'rejectme': self.log.debug("RADIUS Server Access Rejected!") reply.code=packet.AccessReject else: self.log.debug("RADIUS Server Access Accepted") reply.code=packet.AccessAccept self.SendReplyPacket(pkt.fd, reply)
def test_gethostbyaddr(): # 通过IP地址获得主机名 for host in ['119.75.218.70', '121.194.0.239', '216.58.197.100']: try: print socket.gethostbyaddr(host) except socket.error: pass
def request_processor(request, *args, **kws): # Login URL redirect_url = reverse('users.views.perform_login') redirect_url += '?next=%s' % request.path # If we allow guests in, just return the function #if settings.ALLOW_GUESTS: # return fn(request, *args, **kws) # If we don't allow guests but the user is authenticated, return the function if request.user.is_authenticated(): return fn(request, *args, **kws) # If we allow users on a domain, check the user's IP elif len(settings.ALLOWED_DOMAIN)>0: ip_addr = request.META['REMOTE_ADDR'] # If the user is on the allowed domain, return the function if socket.gethostbyaddr(ip_addr)[0].endswith(settings.ALLOWED_DOMAIN): return fn(request, *args, **kws) # If we allow a certain domain and the user is on the server, return the function elif socket.gethostbyaddr(ip_addr)[0] =='localhost': return fn(request, *args, **kws) # If we made it here, we need to authenticate the user return redirect(redirect_url)
def __init__(self, hosts = None, queue_length_max = {}): """ hosts is a list of machine hostnames to be tracked. """ self._hosts = hosts or g.monitored_servers db_info = {} for db in g.databases: dbase, ip = list(g.to_iter(getattr(g, db + "_db")))[:2] try: name = socket.gethostbyaddr(ip)[0] for host in g.monitored_servers: if (name == host or ("." in host and name.endswith("." + host)) or name.startswith(host + ".")): db_info[db] = (dbase, ip, host) except socket.gaierror: print "error resolving host: %s" % ip self._db_info = db_info q_host = g.amqp_host.split(':')[0] if q_host: # list of machines that have amqp queues self._queue_hosts = set([q_host, socket.gethostbyaddr(q_host)[0]]) # dictionary of max lengths for each queue self._queue_length_max = queue_length_max self.hostlogs = [] Templated.__init__(self)
def scan_server(address, port): global counter if port.isdigit(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((address, int(port))) if result == 0: counter+=1 print "Connected to server {%s} on port {%s}." % (socket.gethostbyaddr(address)[0], port) sock.close() return True sock.close() return False else: for port in range(1,1024): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(0.05) result = sock.connect_ex((address, port)) if result == 0: counter+=1 print "Connected to server {%s} on port {%s}." % (socket.gethostbyaddr(address)[0], port) sock.close() if counter > 0: return True else: return False
def test_gethostbyaddr(): try: cpy_socket.gethostbyaddr("::1") except cpy_socket.herror: ipv6 = False else: ipv6 = True for host in ["localhost", "127.0.0.1", "::1"]: if host == "::1" and not ipv6: with py.test.raises(HSocketError): gethostbyaddr(host) continue name, aliases, address_list = gethostbyaddr(host) allnames = [name] + aliases for n in allnames: assert isinstance(n, str) if sys.platform != 'win32': assert 'localhost' in allnames or 'ip6-localhost' in allnames for a in address_list: if isinstance(a, INETAddress) and a.get_host() == "127.0.0.1": break # ok if host != '127.0.0.1': # name lookup might return IPV6 if isinstance(a, INET6Address) and a.get_host() == "::1": break # ok else: py.test.fail("could not find the localhost address in %r" % (address_list,))
def send_email(prog_name,email_list,subject,message): """ it sends an email message via python smtp library. """ import smtplib import socket from email.MIMEText import MIMEText host=socket.gethostbyaddr(socket.gethostname()) hostname=host[0] msg = MIMEText(message) COMMASPACE = ', ' address=email_list.split(',') if len(address) > 1: msg['To'] = COMMASPACE.join(address) else: msg['To'] = email_list msg['Subject'] = subject host=socket.gethostbyaddr(socket.gethostname()) hostname=host[0] sender="sirsi"+"@"+hostname msg['From'] = sender # Establish an SMTP object and connect to your mail server s = smtplib.SMTP() # s.connect("smtp.service.emory.edu") s.connect("localhost") # Send the email - real from, real to, extra headers and content ... s.sendmail(sender,address, msg.as_string()) return
def HandleAcctPacket(self, pkt): """Accouting packet handler. This method is called when a valid accounting packet has been received. It is overriden in derived server class to add custom behaviour. @param pkt: packet to process @type pkt: Packet class instance """ self.log.debug("Received an accounting request at %s RADIUS server from\ %s" %(socket.gethostbyaddr(self.addr)[0], socket.gethostbyaddr(pkt.source[0])[0])) #PR 133009 Code for writing radius accouting packets self.WriteRadiusPacket(pkt) for attr in pkt.keys(): self.log.debug("RADIUS server recieved: %s : %s" % (attr, pkt[attr])) # 32141 - added code for radius accounting packets reply=self.CreateReplyPacket(pkt) if pkt.code==packet.AccountingRequest: time.sleep(self.respTime) reply.code=packet.AccountingResponse self.count += 1 self.acclog = open('/tmp/rad-acc.log','w') self.acclog.write(str(self.count) + '\n') self.acclog.close() else: reply.code=pyrad.packet.AccessAccept self.SendReplyPacket(pkt.fd,reply)
def checkSIPFaxNeg(self,pdmlPkts,txIP,rxIP): """ Verifies whether the transmitter receives an INVITE packet with T38 Fax information and whether the receiver receives 200 OK with T38 information. pdmlPkts - PDML packets captured during the test case run txIP - IP address of the transmitter rxIP - IP address of the receiver """ if txIP: # Check whether a second INVITE with t38 Fax information is received hostname, hostnames, hostaddrs = socket.gethostbyaddr(txIP) invFaxPkt = pdmlPkts.endpoints[hostname].sip.getInvitePacket(2) self.assert_(invFaxPkt,'Second INVITE was not received by transmitter') fax = invFaxPkt.getFieldFirstShowName('sdp.media.format') self.assert_(fax.__contains__('t38'),'INVITE with Fax T38 information was not sent by MSW') cseq = invFaxPkt.getFieldFirstShowName('sip.CSeq').strip('INVITE').strip('CSeq:') ackPkt = pdmlPkts.endpoints[hostname].sip.getPacket('ACK',2) self.assert_(ackPkt,'Second ACK packet was not received') cseqres = ackPkt.getFieldFirstShowName('sip.CSeq').__contains__(cseq) self.assert_(cseqres,'ACK was not received for INVITE with Fax T38 information') if rxIP: hostname, hostnames, hostaddrs = socket.gethostbyaddr(rxIP) # Verify whether 200OK with T38 Fax information is received by the receiver okPkt = pdmlPkts.endpoints[hostname].sip.getPacket('200',2) fax = okPkt.getFieldFirstShowName('sdp.media.format') self.assert_(fax.__contains__('t38'),'200 OK with Fax T38 information was not sent by MSW')
def render_arcus_graph(zoo, param): ts_start = time.time() position = 20 # yaxis pool = graph_pool(position) node_zk = pool.get_node(zoo.address) node_zk.weight = 300 node_zk.color = '0000FF' for code, cache in zoo.arcus_cache_map.items(): node_cache = pool.get_node(code) node_cache.weight = 200 node_cache.color = '00FF00' node_cache.link(node_zk) for code, cache in zoo.arcus_cache_map.items(): node_cache = pool.get_node(code) for node in cache.active_node: try: hostname, aliaslist, ipaddr = socket.gethostbyaddr(node.ip) ret = hostname.split('.') if len(ret) > 2: hostname = '%s.%s' % (ret[0], ret[1]) except socket.herror: hostname = node.ip node_node = pool.get_node(hostname) node_node.weight = 100 node_node.color = '00FFFF' if node.noport: node_node.link(node_cache, node.port, 'FF0000') else: node_node.link(node_cache, node.port, '00FF00') for node in cache.dead_node: try: hostname, aliaslist, ipaddr = socket.gethostbyaddr(node.ip) ret = hostname.split('.') if len(ret) > 2: hostname = '%s.%s' % (ret[0], ret[1]) except socket.herror: hostname = node.ip node_node = pool.get_node(hostname) node_node.weight = 100 node_node.color = '303030' node_node.link(node_cache, node.port, 'EEEEEE') # set meta info pool.description = set_description(zoo, param) result = pool.render() ts_end = time.time() print('## %s elapsed: %f' % (zoo.address, ts_end - ts_start)) return result
def user_owns_machine(request, *args, **kwargs): if request.user.is_staff: return True import subprocess, re, socket what = args[0] if SARIMUI_IP_RE.match(what): #it's an IP address, get it into a hostname try: hostname = socket.gethostbyaddr(what)[0].lower() except: #probably host not found return False elif SARIMUI_SHORT_IP_RE.match(what): #it's a short IP, add 129.57 and turn it into a hostname try: hostname = socket.gethostbyaddr('129.57.' + what)[0].lower() except: return False elif SARIMUI_MAC_RE.match(what): #it's a MAC, turn it into a hostname hostname = Hostname.objects.filter(ip__macip__mac__mac__iexact=what).latest() hostname = hostname.strip().lower() else: #assume it's a hostname hostname = what.lower() print 'testing', hostname, 'against', [i for i in get_hosts_by_user(request.user)] if hostname in [i for i in get_hosts_by_user(request.user)]: return True else: return False
def _check_credentials(request): """ Internal utility method to check whether a user has access to a view """ # If we don't allow guests but the user is authenticated, return the function if request.user.is_authenticated(): return True # If we allow users on a domain, check the user's IP elif len(settings.ALLOWED_DOMAIN)>0: ip_addr = request.META['REMOTE_ADDR'] try: # If the user is on the allowed domain, return the function if socket.gethostbyaddr(ip_addr)[0].endswith(settings.ALLOWED_DOMAIN): return True # If we allow a certain domain and the user is on the server, return the function elif socket.gethostbyaddr(ip_addr)[0] =='localhost': return True except: logging.error("Error processing IP address: %s", str(ip_addr)) elif len(settings.ALLOWED_HOSTS)>0: try: ip_addr = request.META['REMOTE_ADDR'] host_name = socket.gethostbyaddr(ip_addr)[0] for item in settings.ALLOWED_HOSTS: if host_name.endswith(item): return True except: logging.error("Error processing IP address: %s", str(ip_addr)) return False
def setup(self): parameter = self.parameter via = "" if re.match("^[0-9\.:]+$", parameter): self.ip = parameter else: if self.negate_condition: raise ValueError("%s can only be negated if the argument is an IP" % (self.PREFIX,)) try: ips = socket.gethostbyaddr(parameter)[2] except socket.gaierror: ips = [] for ip in ips: if ip in (x[0] for x in SocketConnection.get_connections()): via = "via DNS resolution" self.ip = ip break else: for ip, port in self.get_connections(): host = socket.gethostbyaddr(ip) if parameter in host[0]: via = "reversely via %s:%d" % (host[0], port) self.ip = ip break else: raise ValueError("No open connection to %s found" % parameter) status(0, self.PREFIX, "Waiting for connection(s) to %s to be closed%s" % (self.ip, (" (found %s)" % via) if via else ""))
def connect(host, cookie, cmd, idir, status=''): # set communication channel to our Erlang node, user must specify host, node # name, cookie. addr = socket.gethostbyaddr(host) hostname, aliaslist, addresslist = socket.gethostbyaddr(host) addr = addresslist[0] name = "mynode" node = name + "@" + hostname # initialize the erl_connect module, see http://www.erlang.org/doc/man/erl_connect.html ret = pyerl.connect_xinit(host, name, node, addr, cookie, 1) sock = pyerl.xconnect(addr, name) if sock < 0: # fail to connect print "Fail to connect to Erlang node" sys.exit(0) # print "connect to node=%s, addr=%s, sock=%s" % (node, addr, sock) # call test code server = "bapp_server" if status: eterm = get_status(sock, server, name, status) else: eterm = test_black_box(sock, server, cmd, idir) print "server reply:", eterm # close connection to our server pyerl.close_connection(sock)
def IPscanner(target, IPmin, IPmax, proc, lock): onlineIPs = [] offlineIPs = [] for IP in range(IPmin, IPmax): socket.setdefaulttimeout(1) IPcon = str(target)+"."+str(IP) try: socket.gethostbyaddr(IPcon) #Uncomment the following block to enable direct output when a available IP is found ''' lock.acquire() print "\033[1;32m[+] "+str(IPcon)+" \tis available" lock.release() ''' onlineIPs.append(IPcon) except: offlineIPs.append(IPcon) filename = "/tmp/ip"+str(proc) fileHandle = open ( filename, 'w' ) if len(onlineIPs) > 0: fileHandle.write (str(onlineIPs)+"\n"+str(offlineIPs)) else: fileHandle.write ( "\n"+str(offlineIPs) ) fileHandle.close()
def list_connections(self, connectioninfoitem=None): """list all connections""" if connectioninfoitem is None: infoitems = [Atom(item) for item in CONNECTION_INFO_ITEMS] result = yield self.process.callRemote(self.nodename, "rabbit_networking", "connection_info_all")#, infoitems) info_all = [] for v in result: address = ".".join([str(e) for e in v[1][1]]) peer_address = ".".join([str(e) for e in v[3][1]]) info_all.append({ "pid":v[0][1].nodeName.text, "address":address, "host":socket.gethostbyaddr(address)[0], "port":str(v[2][1]), "peer_address":peer_address, "peer_host":socket.gethostbyaddr(peer_address)[0], "peer_port":str(v[4][1]), "recv_oct":str(v[5][1]), "recv_cnt":str(v[6][1]), "send_oct":str(v[7][1]), "send_cnt":str(v[8][1]), "send_pend":str(v[9][1]), "state":v[10][1].text, "channels":str(v[11][1]), "user":v[12][1].value, "vhost":v[13][1].value, "timeout":str(v[14][1]), "frame_max":str(v[15][1]) }) response = {"command":"list_connections", "result":info_all} returnValue(response)
def __resolve_address(self): ''' Analyse target address setting, resolve it to IP ''' if not self.address: raise RuntimeError("Target address not specified") try: ipaddr.IPv6Address(self.address) self.ipv6 = True self.resolved_ip = self.address try: self.address = socket.gethostbyaddr(self.resolved_ip)[0] except Exception, e: self.log.debug("Failed to get hostname for ip: %s", e) self.address = self.resolved_ip except AddressValueError: self.log.debug("Not ipv6 address: %s", self.address) self.ipv6 = False address_port = self.address.split(":") self.address = address_port[0] if len(address_port) > 1: self.port = address_port[1] try: ipaddr.IPv4Address(self.address) self.resolved_ip = self.address self.address = socket.gethostbyaddr(self.resolved_ip)[0] except AddressValueError: self.log.debug("Not ipv4 address: %s", self.address) ip_addr = socket.gethostbyname(self.address) reverse_name = socket.gethostbyaddr(ip_addr)[0] self.log.debug("Address %s ip_addr: %s, reverse-resolve: %s", self.address, ip_addr, reverse_name) if reverse_name.startswith(self.address): self.resolved_ip = ip_addr else: raise ValueError("Address %s reverse-resolved to %s, but must match" % (self.address, reverse_name))
def __init__(self, host, port, template, publish, storage=None): Publisher.__init__(self) self._host = host self._template = template self._publish = publish self._storagePath = storage self._server = None self._initialStart = True self._possiblePeerCrash = False self._client = None self._clientAddr = None self._contentTemplate = None try: socket.gethostbyaddr(self._host) except socket.error as msg: raise PeachException("Websocket publisher host not reachable: %s" % msg) try: self._port = int(port) except ValueError: raise PeachException("WebSocket publisher port is not a valid number: %s" % port) if self._publish != "base64" and not self._storagePath: raise PeachException( "Publisher's storage parameter needs to be set if not using Base64.")
def tryToConnect(self,host,port,username,password): try: socket.gethostbyaddr(host) except Exception: #print("Proxy "+host+" is not valid") return(404) try: self.s.connect((host,port)) message = "GET http://www.google.co.in/ HTTP/1.1\r\n" auth_phrase = str(base64.b64encode(str(username)+":"+str(password))) message += "Proxy-Authorization: Basic " + auth_phrase + "\r\n\r\n" self.s.sendall(message) data = str(self.s.recv(13)) data = data.split() if data[-1] == '407': #print("Your credentials of "+host+" are incorrect") return(407) #print("Proxy Server at "+host+" is accepting connections at "+str(self.delay)+" seconds delay") return(200) except socket.timeout: #print("Proxy Server at "+host+" is not responding at "+str(self.delay)+" seconds delay") return(408) except socket.error: #print("Proxy Server at "+host+" is refusing connections") return(504)
def nslookup(node_ip): if ':' not in node_ip: return gethostbyaddr(node_ip)[0] ip, port = node_ip.split(':') return '%s:%s' % (gethostbyaddr(ip)[0], port)
def __check_url(self, check_all_subPages, xnet_login): for url in self.test_list: try: if self.run_proxy: self._info('GETTING PROXY...') proxies = get_PROXY.get_proxy_from_pac(pacfile, url) self._opener.set_proxies(proxies) self._get_url_host(url) self._info('URL_HOST:',self.url_host) response = self._opener.open(url) #print 'HEADERS: \n',b.response().info(), '\nEND HEADERS' #print self.xnet_opener.response().code #or alternatively: print r.code if xnet_login: #LOGIN: self._opener.select_form(nr=0) self._opener["ctl00$BodyContent$login$UserName"]=username self._opener["ctl00$BodyContent$login$Password"]=passwd self._opener.submit(name='ctl00$BodyContent$login$LoginButton') #print 'HEADERS: \n',b.response().info(), '\nEND HEADERS' self._check_url_for_error(url) #get status: r_code = response.code if self.run_proxy: ip_addr = proxies['http'] self._info("(proxy):",proxies['http']) else: ip_addr = socket.gethostbyaddr(urlparse.urlparse(response.geturl()).netloc) ip_addr = str(ip_addr[0])+" / "+str(ip_addr[2][0]) self._info("(hostname/aliases/IPlist):",ip_addr) #url = r.geturl() error = None self.write_to_report(self.format, url, ip_addr, r_code, error) if check_all_subPages: self.__check_all_subPages() except mechanize.ControlNotFoundError,error: """ ControlNotFoundError occurs when no Login/Pass forms are located on the page -> it might be that the user is already logged in, so that is why the return code (200) is checked. """ try: assert response.code == 200 self._info('Return Code is 200') #check for error self._check_url_for_error(url) ip_addr = socket.gethostbyaddr(urlparse.urlparse(response.geturl()).netloc) ip_addr = str(ip_addr[0])+" / "+str(ip_addr[2][0]) r_code = response.code error = None self.write_to_report(self.format, response.geturl(), ip_addr, r_code, error) if check_all_subPages: self.__check_all_subPages() except AssertionError,e: self._warn('Return code is not 200! It is: ',error) self.write_to_report(self.format, url, '', '', str(error)) self.error_list.append([url,error])
def main(): project = "haproxy" tablename = "http_host" datalogger = DataLoggerWeb("https://datalogger-api.tirol-kliniken.cc/DataLogger") # datestring = datalogger.get_last_business_day_datestring() # two days back for haproxy logs datestring = (datetime.date.today() - datetime.timedelta(int(2))).isoformat() caches = datalogger.get_caches(project, tablename, datestring) vhosts = [eval(key)[0].split(":")[0] for key in caches["ts"]["keys"].keys()] index = 1 out_data = [] out_data.append(("index", "vhost", "domain", "fqdn", "ip", "ip_reverse_hostname", "status_code", "x_backend_server", "duration")) filter_vhost = generate_filter_vhost() for vhost in vhosts: if filter_vhost(vhost) is True: logging.info("vhost %s filtered out", vhost) continue ip = "unknown" hostname = "unknown" duration = -1.0 status_code = 0 x_backend_server = None domain = ".".join(vhost.split(".")[1:]) try: fqdn = socket.getfqdn(vhost) ip = socket.gethostbyname(vhost) hostname = socket.gethostbyaddr(ip)[0] except (socket.herror, socket.gaierror): pass if (ip == "unknown") or (not ip.startswith("10.")): logging.info("could not resolv hostname %s , probably fake", vhost) continue # could be obsolete elif (not ip.startswith("10.")): logging.info("%s is external, skipping", vhost) continue try: starttime = time.time() res = requests.request("GET", "http://%s/" % vhost, timeout=10, stream=False) duration = time.time()-starttime status_code = res.status_code except (requests.exceptions.ConnectionError, requests.exceptions.InvalidURL): logging.info("ConnectionError or InvalidURL occured %s", vhost) except requests.exceptions.ReadTimeout: logging.info("RequestTimeout occured %s", vhost) try: x_backend_server = res.headers['x-backend-server'] if len(x_backend_server) == 8: # TODO not exact, hack ip_backend_server = decode_ip(x_backend_server) x_backend_server = socket.gethostbyaddr(ip_backend_server)[0] # only hostname part else: x_backend_server = socket.getfqdn(x_backend_server) except KeyError: pass logging.debug("%40s : %20s : %40s : %15s : %40s : %d : %s : %02f", vhost, domain, fqdn, ip, hostname, status_code, x_backend_server, duration) out_data.append((index, vhost, domain, fqdn, ip, hostname, status_code, x_backend_server, duration)) index += 1 json.dump({"last_update_ts" : str(datetime.date.today()), "data" : out_data}, open("/var/www/webapps/webmap/webmap.json", "w"))
def install_args(self, guest): """Construct kernel cmdline args for the installer, consisting of: the pathname of the kernel (32/64) to load, kernel options and args, and '-B' boot properties.""" # XXX: ignoring smfargs for the time being (kopts, kargs, ignore_smfargs, kbargs) = \ self.process_extra_args(guest.extraargs) args = [ '' ] if kopts: args += [ '-%s' % kopts ] if kbargs: args += [ '-B', kbargs ] netmask = '' # Yuck. Non-default netmasks require this option to be passed. # It's distinctly not-trivial to work out the netmask to be used # automatically. if kargs: for karg in kargs.split(): if karg.startswith('subnet-mask'): netmask = karg.split('=')[1] else: args += [ kargs ] iargs = '' if not guest.graphics['enabled']: iargs += 'nowin ' if guest.location.startswith('nfs:'): try: guestIP = socket.gethostbyaddr(guest.name)[2][0] except: iargs += ' dhcp' else: iserver = guest.location.split(':')[1] ipath = guest.location.split(':')[2] iserverIP = socket.gethostbyaddr(iserver)[2][0] iargs += ' -B install_media=' + iserverIP + ':' + ipath iargs += ',host-ip=' + guestIP if netmask: iargs += ',subnet-mask=%s' % netmask droute = _util.default_route(guest.nics[0].bridge) if droute: iargs += ',router-ip=' + droute if guest.nics[0].macaddr: en = guest.nics[0].macaddr.split(':') for i in range(len(en)): # remove leading '0' from mac address element if len(en[i]) > 1 and en[i][0] == '0': en[i] = en[i][1] boot_mac = ':'.join(en) iargs += ',boot-mac=' + boot_mac else: iargs += '-B install_media=cdrom' args += [ '-', iargs ] return ' '.join(args)
def main(): for i in range(1,256): ip = "192.168.1.%d"%(i) cmd = "ping %s -c 1 1>/dev/null 2>1"%(ip) ret = os.system(cmd); if ret == 0: print ip print socket.gethostbyaddr(ip)
def test(): try: print 'connect to BANK NOW!' socket.gethostbyaddr('www.asb.by') print 'successful connection' except socket.gaierror: return 'error socket' return 'PASS'
def is_this_system(system_name): """ :returns: Whether the given *system_name* matches the hostname of currently running system. :rtype: boolean """ return (socket.gethostbyaddr(system_name)[0] == socket.gethostbyaddr(socket.gethostname())[0])
def get_multiple_backends( services: Optional[Collection[str]], envoy_host: str, envoy_admin_port: int, ): """Fetches JSON from Envoy admin's /clusters endpoint and returns a list of backends. :param services: If None, return backends for all services, otherwise only return backends for these particular services. :param envoy_host: The host that this check should contact for replication information. :param envoy_admin_port: The port that Envoy's admin interface is listening on :returns backends: A list of dicts representing the backends of all services or the requested service """ clusters_info = retrieve_envoy_clusters( envoy_host=envoy_host, envoy_admin_port=envoy_admin_port, system_paasta_config=settings.system_paasta_config, ) casper_endpoints = get_casper_endpoints(clusters_info) backends: List[Tuple[EnvoyBackend, bool]] = [] for cluster_status in clusters_info["cluster_statuses"]: if "host_statuses" in cluster_status: if cluster_status["name"].endswith(".egress_cluster"): service_name = cluster_status["name"][:-len(".egress_cluster")] if services is None or service_name in services: cluster_backends = [] casper_endpoint_found = False for host_status in cluster_status["host_statuses"]: address = host_status["address"]["socket_address"][ "address"] port_value = host_status["address"]["socket_address"][ "port_value"] # Check if this endpoint is actually a casper backend # If so, omit from the service's list of backends if not service_name.startswith("spectre."): if (address, port_value) in casper_endpoints: casper_endpoint_found = True continue try: hostname = socket.gethostbyaddr(address)[0].split( ".")[0] except socket.herror: # Default to the raw IP address if we can't lookup the hostname hostname = address cluster_backends.append(( EnvoyBackend( address=address, port_value=port_value, hostname=hostname, eds_health_status=host_status["health_status"] ["eds_health_status"], weight=host_status["weight"], ), casper_endpoint_found, )) backends += cluster_backends return backends
def checkDNS(IP): try: dns = socket.gethostbyaddr(ip) return dns[0] except: return "No DNS entry found"
error(_("--key2 argument required for database LrfDB")) sys.exit(1) if (not key3): error(_("--key3 argument required for database LrfDB")) sys.exit(1) # Init log if needed #################### if (_log): # Get user informations import os, pwd uid = os.getuid() username = pwd.getpwuid(uid)[0] # Get host informations import socket (host, null, ip) = socket.gethostbyaddr(socket.gethostname()) # Fill log file info( _("=== Start sending | %s user: %s (%s) | host: %s (%s) ") % (logArgs, username, uid, host, ip)) # Launch main ########################## main(files, upper(mode), \ {'datatype':datatype, 'region':region, \ 'header': header, 'center': center, 'database':database, 'prddb':{'date':date,'key1':key1,'key2':key2,'key3':key3}, 'lrfdb':{'date':date,'key1':key1,'key2':key2,'key3':key3} })
def _ip_to_dnsname(ip: HostAddress) -> Optional[HostName]: try: return HostName(socket.gethostbyaddr(ip)[0]) except Exception: return None
def smbCheck(pkt): #pkt.show() # debug statement global interface global localIP if TCP in pkt: #if str(pkt[IP].dst) == "10.8.4.53": outstring = "" #print("******************************************************************") #print(dir(pkt)) #print(pkt.show()) #try: #print(pkt[IP].dst) #print(pkt[IP].proto) #print("HEXY TIME") pktPayload = str(pkt[TCP].payload).lower().split("\\") if len(pktPayload) > 4: if smb23 in pktPayload[4]: #********************************************************************* srcName = "<unknown>" try: srcName = str(socket.gethostbyaddr(pkt[IP].src)[0]) except: pass dstName = "<unknown>" try: dstName = str(socket.gethostbyaddr(pkt[IP].dst)[0]) except: pass #********************************************************************* if pkt[IP].src == localIP: outstring = "SMB 2/3 --> " + pkt[ IP].src + " (" + srcName + ") --> " + pkt[ IP].dst + " (" + dstName + ")" else: outstring = "SMB 2/3 --> " + pkt[ IP].dst + " (" + dstName + ") <-- " + pkt[ IP].src + " (" + srcName + ")" #outstring = pkt[IP].src + " (" + srcName + ") --> " + pkt[IP].dst + " (" + dstName + ") : SMB 2/3" connectionSet.add(outstring) os.system("cls") print(interface) print(localIP) print( "SMB Ver. --> Source (HostName) --> Destination (Host Name)" ) for i in sorted(connectionSet): print(i) #print(outstring) elif smb1 in pktPayload[4]: #********************************************************************* srcName = "<unknown>" try: srcName = str(socket.gethostbyaddr(pkt[IP].src)[0]) except: pass dstName = "<unknown>" try: dstName = str(socket.gethostbyaddr(pkt[IP].dst)[0]) except: pass #********************************************************************* if pkt[IP].src == localIP: outstring = "SMB 1 --> " + pkt[ IP].src + " (" + srcName + ") --> " + pkt[ IP].dst + " (" + dstName + ")" else: outstring = "SMB 1 --> " + pkt[ IP].dst + " (" + dstName + ") <-- " + pkt[ IP].src + " (" + srcName + ")" connectionSet.add(outstring) #print(outstring) os.system("cls") print(interface) print(localIP) print("Source --> Destination : SMB Ver.") for i in connectionSet: print(i) else: pass
def get_host_by_addr(self): if self.host is not None: try: return gethostbyaddr(self.host)[0] except socket.error: pass
def hostname_from_ip(ip): try: reversed_dns = socket.gethostbyaddr(ip) return reversed_dns[0] except socket.herror: return None
def analyze(self, packets_test, device_list): #own_ip = get('https://api.ipify.org').text scan_duration = int(getDatabase().get_config("scan_duration")) self.ana_res = {} for device in device_list: if (device["ip"] not in self.ana_res): self.ana_res[device["ip"]] = {} default_gateway = getNetworkScanner().get_default_gateway() cidr = getDatabase().get_config("home_cidr") logging.info("[*] Start traffic analysis") logging.info(" |--> IP traffic analysis") logging.info("packets: " + str(len(packets_test))) bytestotal = 0 # acclumerate IP packet information self.tot_p_count += len(packets_test) for pkt in packets_test: """if HTTP in pkt: http_layer = pkt.getlayer(HTTP) pkt.show()""" if IP in pkt: send = True ip_src = pkt[IP].src ip_dst = pkt[IP].dst foreign_ip = None local_ip = None hport = None pport = None bytestotal += len(pkt) if (ip_src in self.ana_res): foreign_ip = ip_dst local_ip = ip_src if TCP in pkt: hport = pkt[TCP].sport pport = pkt[TCP].dport send = True if (ip_dst in self.ana_res): foreign_ip = ip_src local_ip = ip_dst if TCP in pkt: hport = pkt[TCP].dport pport = pkt[TCP].sport send = False if (local_ip != None and foreign_ip != None): if (foreign_ip not in self.ana_res[local_ip]): if (send): self.ana_res[local_ip][foreign_ip] = { "snd": 1 / scan_duration, "rcv": 0, "bsnd": len(pkt), "brcv": 0, "domains": [], "threats": [], "hports": {hport}, "pports": {pport} } else: self.ana_res[local_ip][foreign_ip] = { "snd": 0, "rcv": 1 / scan_duration, "bsnd": len(pkt), "brcv": 0, "domains": [], "threats": [], "hports": {hport}, "pports": {pport} } else: self.ana_res[local_ip][foreign_ip][ "hports"] = self.ana_res[local_ip][foreign_ip][ "hports"] | {hport} self.ana_res[local_ip][foreign_ip][ "pports"] = self.ana_res[local_ip][foreign_ip][ "pports"] | {pport} if (send): self.ana_res[local_ip][foreign_ip][ "snd"] += 1 / scan_duration self.ana_res[local_ip][foreign_ip]["bsnd"] += len( pkt) / scan_duration else: self.ana_res[local_ip][foreign_ip][ "rcv"] += 1 / scan_duration self.ana_res[local_ip][foreign_ip]["brcv"] += len( pkt) / scan_duration # perform IP check #collect all ips all_ips = set() for key in self.ana_res.keys(): for ip in self.ana_res[key]: all_ips.add(ip) ip_threats = getIPThreatDatabase().check_IPs(all_ips) for key in self.ana_res.keys(): for ip in self.ana_res[key]: # Check for malicious ips if (ip in ip_threats): self.ana_res[key][ip]["threats"].append(ip_threats[ip]) # Perform reverse dns lookup if (len(self.ana_res[key][ip]["domains"]) == 0): try: reversed_dns = socket.gethostbyaddr(ip) if (len(reversed_dns) > 0): getDatabase().submit_ip_domain(ip, reversed_dns[0]) self.ana_res[key][ip]["domains"].append( reversed_dns[0]) except Exception: logging.exception("no reverse dns for " + ip) logging.info(" |--> DNS traffic analysis") if (int(getDatabase().get_config("DNS_inspect")) > 0): logging.info(" DNS traffic analysis enabled") try: for pkt in packets_test: if pkt.haslayer(DNSRR): # If the answer is a DNSRR, print the name it replied with. if isinstance(pkt.an, DNSRR): for key in self.ana_res.keys(): if (pkt.an.rdata in self.ana_res[key]): getDatabase().submit_ip_domain( pkt.an.rdata, pkt.an.rrname.decode("utf-8")) if (pkt.an.rrname.decode("utf-8") in ';;;'.join(self.ana_res[key][ pkt.an.rdata]["domains"])): self.ana_res[key][ pkt.an.rdata]["domains"].append( pkt.an.rrname.decode("utf-8")) # TODO: perform malicious dns lookup except Exception: logging.exception("Exception during DNS traffic analysis", Exception) else: logging.info(" DNS traffic analysis disabled") getDatabase().insert_or_replace_config( "num_pack_scan", int(getDatabase().get_config("num_pack_scan")) + len(packets_test)) getDatabase().insert_or_replace_config( "num_bytes_scan", int(getDatabase().get_config("num_bytes_scan")) + bytestotal) logging.info("[*] Traffic analysis completed") for device in device_list: for rip in list(self.ana_res[device["ip"]].keys()): self.ana_res[device["ip"]][rip]["hports"] = list( self.ana_res[device["ip"]][rip]["hports"]) self.ana_res[device["ip"]][rip]["pports"] = list( self.ana_res[device["ip"]][rip]["pports"]) device["connections"] = self.ana_res[device["ip"]] getNetworkScanner().add_locations_to_device(device) return { "devices": copy.deepcopy(device_list), "cidr": cidr, "time": time.time() } #if __name__ == "__main__": # test = getTrafficAnalyzer() # packets = rdpcap('full_capture.pcap') # print(test.analyze(packets, [{"ip":"192.168.8.113"},{"ip":"192.168.8.101"},{"ip":"192.168.8.1"}]))
def prompt_for_ssh(options): """Prompt the user to ssh to the installation environment on the s390. :param options: Anaconda command line/boot options :return: True if the prompt is printed, otherwise False """ if not blivet.arch.is_s390(): return False if not conf.target.is_hardware: return False if 'TMUX' in os.environ: return False if options.ksfile: return False if options.vnc: return False # Do some work here to get the ip addr / hostname to pass # to the user. import socket ip = network.get_first_ip_address() if not ip: stdout_log.error( "No IP addresses found, cannot continue installation.") util.ipmi_report(constants.IPMI_ABORTED) sys.exit(1) ipstr = ip name = None try: hinfo = socket.gethostbyaddr(ipstr) except socket.herror as e: stdout_log.debug("Exception caught trying to get host name of %s: %s", ipstr, e) name = socket.gethostname() else: if len(hinfo) == 3: name = hinfo[0] if ip.find(':') != -1: ipstr = "[%s]" % (ip, ) if (name is not None) and (not name.startswith('localhost')) and ( ipstr is not None): connxinfo = "%s (%s)" % ( socket.getfqdn(name=name), ipstr, ) elif ipstr is not None: connxinfo = "%s" % (ipstr, ) else: connxinfo = None if connxinfo: stdout_log.info(_("Please ssh install@%s to begin the install."), connxinfo) else: stdout_log.info( _("Please ssh install@HOSTNAME to continue installation.")) return True
def reverseLookup(address): try: return socket.gethostbyaddr(address)[0] except: return None
import binascii s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800)) print "Starting Sniff" while True: pkt = s.recvfrom(2048) ethhead = pkt[0][0:14] eth = struct.unpack("!6s6s2s", ethhead) print "--------Ethernet Frame--------" print "desination mac", binascii.hexlify(eth[0]) print "Source mac", binascii.hexlify(eth[1]) binascii.hexlify(eth[2]) print "---------TCP----------" tcpheader = pkt[0][34:54] #tcp_hdr = struct.unpack("!HH16s",tcpheader) tcp_hdr = struct.unpack("!HH9ss6s", tcpheader) print "Source Port ", tcp_hdr[0] print "Destination port ", tcp_hdr[1] print "Flag ", binascii.hexlify(tcp_hdr[3]) ipheader = pkt[0][14:34] ip_hdr = struct.unpack("!8sB3s4s4s", ipheader) print "-----------IP------------------" print "TTL :", ip_hdr[1] print "Source IP", socket.inet_ntoa(ip_hdr[3]) x = socket.inet_ntoa(ip_hdr[4]) print "Destination IP", x try: print "Host Address ", socket.gethostbyaddr(x) except: print "No Host Address"
def send_email(config, entry, comment, comment_dir, comment_filename): """Send an email to the blog owner on a new comment @param config: configuration as parsed by Pyblosxom @type config: dictionary @param entry: a file entry @type config: dictionary @param comment: comment as generated by read_comments @type comment: dictionary @param comment_dir: the comment directory @type comment_dir: string @param comment_filename: file name of current comment @type comment_filename: string """ import smtplib # import the formatdate function which is in a different # place in Python 2.3 and up. try: from email.Utils import formatdate except ImportError: from rfc822 import formatdate from socket import gethostbyaddr author = escape_smtp_commands(clean_author(comment['author'])) description = escape_smtp_commands(comment['description']) ipaddress = escape_smtp_commands(comment.get('ipaddress', '?')) if 'comment_smtp_from' in config: email = config['comment_smtp_from'] else: email = escape_smtp_commands(clean_author(comment['email'])) try: curl = "%s/%s" % (config['base_url'], tools.urlencode_text(entry['file_path'])) comment_dir = os.path.join(config['comment_dir'], entry['absolute_path']) # create the message message = [] message.append("Name: %s" % author) if 'email' in comment: message.append("Email: %s" % comment['email']) if 'link' in comment: message.append("URL: %s" % comment['link']) try: host_name = gethostbyaddr(ipaddress)[0] message.append("Hostname: %s (%s)" % (host_name, ipaddress)) # FIXME - bare except here--bad! except: message.append("IP: %s" % ipaddress) message.append("Entry URL: %s" % curl) message.append("Comment location: %s" % comment_filename) message.append("\n\n%s" % description) if 'comment_mta_cmd' in config: # set the message headers message.insert(0, "") message.insert(0, "Subject: comment on %s" % curl) message.insert(0, "Date: %s" % formatdate(float(comment['pubDate']))) message.insert(0, "To: %s" % config["comment_smtp_to"]) message.insert(0, "From: %s" % email) body = '\n'.join(message).encode('utf-8') argv = [ config['comment_mta_cmd'], '-s', '"comment on %s"' % curl, config['comment_smtp_to'] ] process = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) process.stdin.write(body) process.stdin.close() process.wait() stdout = process.stdout.read() stderr = process.stderr.read() tools.get_logger().debug('Ran MTA command: ' + ' '.join(argv)) tools.get_logger().debug('Received stdout: ' + stdout) tools.get_logger().debug('Received stderr: ' + stderr) # the except clause below will catch this assert stderr == '', stderr else: assert 'comment_smtp_server' in config server = smtplib.SMTP(config['comment_smtp_server']) mimemsg = MIMEText("\n".join(message).encode("utf-8"), 'plain', 'utf-8') # set the message headers mimemsg["From"] = email mimemsg["To"] = config["comment_smtp_to"] mimemsg["Date"] = formatdate(float(comment["pubDate"])) mimemsg["Subject"] = ("comment on %s" % curl) # send the message via smtp server.sendmail(from_addr=email, to_addrs=config['comment_smtp_to'], msg=mimemsg.as_string()) server.quit() except Exception, e: tools.get_logger().error("error sending email: %s" % traceback.format_exception(*sys.exc_info()))
def __init__ (self, ip, port, resolver=None, logger_object=None): self.ip = ip self.port = port asyncore.dispatcher.__init__ (self) if ':' in ip: socket_type = socket.AF_INET6 else: socket_type = socket.AF_INET self.create_socket (socket_type, socket.SOCK_STREAM) self.handlers = [] if not logger_object: logger_object = logger.file_logger (sys.stdout) self.set_reuse_addr() self.bind ((ip, port)) # lower this to 5 if your OS complains self.listen (1024) name = self.socket.getsockname() host = name[0] port = name[1] if not ip: self.log_info('Computing default hostname', 'warning') try: ip = socket.gethostbyname(socket.gethostname()) except socket.error: ip = socket.gethostbyname('localhost') try: self.server_name = socket.gethostbyaddr (ip)[0] except socket.error: self.log_info('Cannot do reverse lookup', 'warning') self.server_name = ip # use the IP address as the "hostname" self.server_port = port self.total_clients = counter() self.total_requests = counter() self.exceptions = counter() self.bytes_out = counter() self.bytes_in = counter() if not logger_object: logger_object = logger.file_logger (sys.stdout) if resolver: self.logger = logger.resolving_logger (resolver, logger_object) else: self.logger = logger.unresolving_logger (logger_object) self.log_info ( 'Medusa (V%s) started at %s' '\n\tHostname: %s' '\n\tPort:%d' '\n' % ( VERSION_STRING, time.ctime(time.time()), self.server_name, port, ) )
def main(): print_banner() parser = ArgumentParser() parser.add_argument( "-t", dest="target_hosts", required=True, help="Set a target range of addresses to target. Ex 10.11.1.1-255") parser.add_argument( "-w", dest="wordlists", required=False, type=str, help= "Set the wordlists to use (default ./wordlists/virtual-host-scanning.txt)", default=False) parser.add_argument( "-b", dest="base_host", required=False, help= "Set host to be used during substitution in wordlist (default to TARGET).", default=False) parser.add_argument("-p", dest="port", required=False, help="Set the port to use (default 80).", default=80) parser.add_argument( "-r", dest="real_port", required=False, help= "The real port of the webserver to use in headers when not 80 (see RFC2616 14.23), useful when pivoting through ssh/nc etc (default to PORT).", default=False) parser.add_argument( '--ignore-http-codes', dest='ignore_http_codes', type=str, help= 'Comma separated list of http codes to ignore with virtual host scans (default 404).', default='404') parser.add_argument( '--ignore-content-length', dest='ignore_content_length', type=int, help='Ignore content lengths of specificed amount (default 0).', default=0) parser.add_argument( '--unique-depth', dest='unique_depth', type=int, help= 'Show likely matches of page content that is found x times (default 1).', default=1) parser.add_argument( "--ssl", dest="ssl", action="store_true", help= "If set then connections will be made over HTTPS instead of HTTP (default http).", default=False) parser.add_argument( "--fuzzy-logic", dest="fuzzy_logic", action="store_true", help= "If set then fuzzy match will be performed against unique hosts (default off).", default=False) parser.add_argument( "--no-lookups", dest="no_lookup", action="store_true", help= "Disable reverse lookups (identifies new targets and appends to wordlist, on by default).", default=False) parser.add_argument( "--rate-limit", dest="rate_limit", type=int, help= 'Amount of time in seconds to delay between each scan (default 0).', default=0) parser.add_argument( '--random-agent', dest='random_agent', action='store_true', help= 'If set, then each scan will use random user-agent from predefined list.', default=False) parser.add_argument('--user-agent', dest='user_agent', type=str, help='Specify a user-agent to use for scans') parser.add_argument( "--waf", dest="add_waf_bypass_headers", action="store_true", help="If set then simple WAF bypass headers will be sent.", default=False) parser.add_argument( "-oN", dest="output_normal", help= "Normal output printed to a file when the -oN option is specified with a filename argument." ) parser.add_argument( "-", dest="stdin", action="store_true", help= "By passing a blank '-' you tell VHostScan to expect input from stdin (pipe).", default=False) arguments = parser.parse_args() wordlist = [] word_list_types = [] default_wordlist = "./wordlists/virtual-host-scanning.txt" if not arguments.stdin else None if arguments.stdin: word_list_types.append('stdin') wordlist.extend(list(line for line in sys.stdin.read().splitlines())) combined = get_combined_word_lists(arguments.wordlists or default_wordlist) word_list_types.append('wordlists: {}'.format( ', '.join(combined['file_paths']), )) wordlist.extend(combined['words']) if len(wordlist) == 0: print("[!] No words found in provided wordlists, unable to scan.") sys.exit(1) print( "[+] Starting virtual host scan for {host} using port {port} and {inputs}" .format( host=arguments.target_hosts, port=arguments.port, inputs=', '.join(word_list_types), )) user_agents = [] if arguments.user_agent: print('[>] User-Agent specified, using it') user_agents = [arguments.user_agent] elif arguments.random_agent: print('[>] Random User-Agent flag set') user_agents = load_random_user_agents() if (arguments.ssl): print("[>] SSL flag set, sending all results over HTTPS") if (arguments.add_waf_bypass_headers): print("[>] WAF flag set, sending simple WAF bypass headers") print("[>] Ignoring HTTP codes: %s" % (arguments.ignore_http_codes)) if (arguments.ignore_content_length > 0): print("[>] Ignoring Content length: %s" % (arguments.ignore_content_length)) if not arguments.no_lookup: for ip in Resolver().query(arguments.target_hosts, 'A'): host, aliases, ips = gethostbyaddr(str(ip)) wordlist.append(str(ip)) wordlist.append(host) wordlist.extend(aliases) scanner_args = vars(arguments) scanner_args.update({ 'target': arguments.target_hosts, 'wordlist': wordlist, 'user_agents': user_agents }) scanner = virtual_host_scanner(**scanner_args) scanner.scan() output = output_helper(scanner, arguments) print(output.output_normal_likely()) if (arguments.fuzzy_logic): print(output.output_fuzzy()) if (arguments.output_normal): output.write_normal(arguments.output_normal) print("\n[+] Writing normal ouptut to %s" % arguments.output_normal)
def trigger(): if arguments['gateway']: gateway, interface = default_gateway() print('Gateway: ' + gateway) print('Interface: ' + interface) if arguments['ip_local']: gateway, interface = default_gateway() print(netifaces.ifaddresses(interface)[netifaces.AF_INET][-1]['addr']) if arguments['ip_external']: try: print(request('https://ipv4.icanhazip.com')) print(request('https://ipv6.icanhazip.com')) except: pass if arguments['ip_tor']: proxy_host = arguments['<proxy_ip>'] proxy_port = 9050 scheme = 'socks5' url = 'https://icanhazip.com' try: print( proxy_request( url, scheme, 'localhost' if proxy_host is None else proxy_host, proxy_port)) except requests.exceptions.ConnectionError: print('Proxy connection error.') except ValueError: print('Not a valid proxy.') if arguments['dns_reverse']: print(request('https://icanhazptr.com')) if arguments['hostname']: ip = arguments['<ip_address>'] if ip is None: print(socket.gethostname()) exit(0) try: ipaddress.ip_address(str(ip)) name, alias, addresslist = socket.gethostbyaddr(ip) print(name) except socket.error: print('Unknown host.') except ValueError: print('Not a valid IP address.') if arguments['ip_of']: hostname = arguments['<hostname>'] try: list = socket.getaddrinfo(hostname, 80, 0, 0, socket.IPPROTO_TCP) for i in list: print(i[-1][0]) except socket.error: print('Unknown host.') if arguments['external_scan']: port = arguments['<port>'] error = 'Invalid port number.' try: port = int(port) except ValueError: print(error) if not 0 <= int(port) <= 65535: raise ValueError(error) try: r = requests.post('http://canyouseeme.org', data={'port': port}) if len(r.text) != 0: print('Not open.' if not re.search('Success', r.text) else 'Open.') except requests.ConnectionError or requests.ConnectTimeout: print('CanYouSeemMe.org is down...') if arguments['traceroute']: print( re.sub('.* \*' + chr(0x0a), '', request('https://icanhaztraceroute.com'))) if arguments['geoip']: ip = arguments['<ip_address>'] ip = ip if ip is not None else request('https://icanhazip.com') try: ipaddress.ip_address(str(ip)) except ValueError: print('Not a valid IP address.') exit(0) obj = json.loads(request('https://ip.pentestit.ru/json?ip=' + ip)) if 'error' in obj: print(obj['error']) exit(0) print('City: ' + obj['city']) print('Country: ' + obj['country'] + ' (' + obj['timezone'] + ')') print('ISP: ' + obj['isp'] + ' (' + obj['org'] + ')') print('IP: ' + obj['ipaddress'])
import socket import sys try: print("gethostbyname") print(socket.gethostbyname_ex('www.google.com')) print("\ngethostbyaddr") print(socket.gethostbyaddr('216.58.211.228')) print("\ngetfqdn") print(socket.getfqdn('www.google.com')) except socket.error as error: print(str(error)) print("Error de conexión") sys.exit()
def hostname(self): try: return gethostbyaddr(self.ip)[0] except Exception: # socket.gaierror, socket.herror, etc return self.ip
def watch_ci(): HOST = '' PORT = 49494 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "CI Socket Created" try: s.bind((HOST, PORT)) except socket.error as msg: print 'Bind Failed. Error code: ' + str(msg[0]) return s.listen(10) print 'listening for CI changes' while 1: conn, addr = s.accept() addr_host = socket.gethostbyaddr(addr[0])[0] is_circleci = True if re.compile( r"ec2-\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}.compute-1.amazonaws.com" ).search(addr_host) else False print 'Received request from ' + addr[ 0] + " ; " + "verified as CircleCI" if is_circleci else "NOT verified as CircleCI!" if not is_circleci: conn.close() continue conn.send('HTTP/1.1 200 OK\n' + 'Content-Type: text/plain\n' 'Content-Length: 2\n' + '\nOK\n') conn.close() r = requests.get( 'https://api.github.com/repos/Charcoal-SE/SmokeDetector/git/refs/heads/master' ) latest_sha = r.json()["object"]["sha"] print latest_sha r = requests.get( 'https://api.github.com/repos/Charcoal-SE/SmokeDetector/commits/' + latest_sha + '/statuses') for status in r.json(): state = status["state"] target_url = status["target_url"] ci_platform = "" if status["context"] == "ci/circleci": ci_platform = "Circle" elif status["context"] == "continuous-integration/travis-ci/push": ci_platform = "Travis" else: ci_platform = "some unrecognized test service" print state if state == "success": if datetime.datetime.strptime( status["updated_at"], '%Y-%m-%dT%H:%M:%SZ' ) > datetime.datetime.now() - datetime.timedelta(seconds=60): r = requests.get( 'https://api.github.com/repos/Charcoal-SE/SmokeDetector/commits/' + latest_sha) commit_message = r.json()["commit"]["message"] print commit_message if "autopull" in commit_message: GlobalVars.charcoal_hq.send_message( "[CI build passed]({}) on {}. Commit message contains 'autopull', pulling..." .format(target_url, ci_platform)) time.sleep(2) os._exit(3) else: GlobalVars.charcoal_hq.send_message( "[CI build passed]({}) on {}. Ready to pull!". format(target_url, ci_platform)) continue elif state == "error" or state == "failure": if datetime.datetime.strptime( status["updated_at"], '%Y-%m-%dT%H:%M:%SZ' ) > datetime.datetime.now() - datetime.timedelta(seconds=10): GlobalVars.charcoal_hq.send_message( "[CI build failed]({}), *someone* (prolly Undo) borked something!" .format(target_url)) continue s.close()
# AMI to use for the Ingest Tier # AMI to use for the Storage/Analysis Tier #### End parameter block #### # Proxy check for the S3 VLAN1 network proxyHost = None proxyPort = None # Local proxy setting determination myAddress = socket.gethostbyaddr(socket.gethostname()) if string.find(myAddress[0], "s3group") > 0: if string.find(myAddress[-1][0], "193.120") == 0: proxyHost = 'w3proxy.s3group.com' proxyPort = 3128 # Turn on verbose output: debugging aid boto.set_stream_logger('mylog') ########################################################################### # Stage #1: Load balancer ########################################################################### # Takes credentials from the environment : assumes they are defined in shell variables in one of the supported ways
import scraperwiki # Blank Python #!/usr/bin/env python import pprint import json import socket import csv data = scraperwiki.scrape("http://fieldventures.org/IT.txt") f = csv.reader(data.splitlines()) #f = open('http://fieldventures.org/IT_ipranges.txt', 'r') try: domain = socket.gethostbyaddr("2.16.71.255") print domain[0] except: print "balls" def loopOverRange(startAddress, endAddress): "iterates over a given ip range" starts = startAddress.split(".") ends = endAddress.split(".") start1 = int(starts[0]) start2 = int(starts[1]) start3 = int(starts[2]) start4 = int(starts[3])
def sasl_gssapi(connection, controls): """ Performs a bind using the Kerberos v5 ("GSSAPI") SASL mechanism from RFC 4752. Does not support any security layers, only authentication! sasl_credentials can be empty or a tuple with one or two elements. The first element determines which service principal to request a ticket for and can be one of the following: - None or False, to use the hostname from the Server object - True to perform a reverse DNS lookup to retrieve the canonical hostname for the hosts IP address - A string containing the hostname The optional second element is what authorization ID to request. - If omitted or None, the authentication ID is used as the authorization ID - If a string, the authorization ID to use. Should start with "dn:" or "user:"******""" target_name = None authz_id = b"" if connection.sasl_credentials: if len(connection.sasl_credentials) >= 1 and connection.sasl_credentials[0]: if connection.sasl_credentials[0] is True: hostname = socket.gethostbyaddr(connection.socket.getpeername()[0])[0] target_name = gssapi.Name('ldap@' + hostname, gssapi.NameType.hostbased_service) else: target_name = gssapi.Name('ldap@' + connection.sasl_credentials[0], gssapi.NameType.hostbased_service) if len(connection.sasl_credentials) >= 2 and connection.sasl_credentials[1]: authz_id = connection.sasl_credentials[1].encode("utf-8") if target_name is None: target_name = gssapi.Name('ldap@' + connection.server.host, gssapi.NameType.hostbased_service) creds = gssapi.Credentials(name=gssapi.Name(connection.user), usage='initiate') if connection.user else None ctx = gssapi.SecurityContext(name=target_name, mech=gssapi.MechType.kerberos, creds=creds) in_token = None try: while True: out_token = ctx.step(in_token) if out_token is None: out_token = '' result = send_sasl_negotiation(connection, controls, out_token) in_token = result['saslCreds'] try: # This raised an exception in gssapi<1.1.2 if the context was # incomplete, but was fixed in # https://github.com/pythongssapi/python-gssapi/pull/70 if ctx.complete: break except gssapi.exceptions.MissingContextError: pass unwrapped_token = ctx.unwrap(in_token) if len(unwrapped_token.message) != 4: raise LDAPCommunicationError("Incorrect response from server") server_security_layers = unwrapped_token.message[0] if not isinstance(server_security_layers, int): server_security_layers = ord(server_security_layers) if server_security_layers in (0, NO_SECURITY_LAYER): if unwrapped_token.message[1:] != '\x00\x00\x00': raise LDAPCommunicationError("Server max buffer size must be 0 if no security layer") if not (server_security_layers & NO_SECURITY_LAYER): raise LDAPCommunicationError("Server requires a security layer, but this is not implemented") client_security_layers = bytearray([NO_SECURITY_LAYER, 0, 0, 0]) out_token = ctx.wrap(bytes(client_security_layers)+authz_id, False) return send_sasl_negotiation(connection, controls, out_token.message) except (gssapi.exceptions.GSSError, LDAPCommunicationError): abort_sasl_negotiation(connection, controls) raise
def main(): d_url = sys.argv[1] ttl = 1 d_addr = socket.gethostbyname(d_url) port = 33434 max_h = 35 sys.stdout.write("Tracerouting to: %s (%s) [%d hops max] [Port: %d]\n\n" % (d_addr, d_url, max_h, port)) while ttl < max_h: recv = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp')) send = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.getprotobyname('udp')) #Set the value of the given socket option send.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl) #socket.setsockopt(level, optname, value) recv.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack("ll", 5, 0)) recv.bind(("", port)) t = (time.time()) sys.stdout.write(" %d \t" % ttl) send.sendto("", (d_url, port)) flag = False recv_addr = None recv_name = None i = 0 flag1 = False rt = [] while not flag and i < 3: try: _, c_addr = recv.recvfrom(512) roundt = ((time.time()) - t) * 1000 rt.append(roundt) #sys.stdout.write("Teste: %s\n" % c_addr[0]) c_addr = c_addr[0] try: c_name = socket.gethostbyaddr(c_addr)[0] except: c_name = c_addr flag = True except socket.error: i = i + 1 sys.stdout.write("* ") flag1 = True if flag1: sys.stdout.write("\n") send.close() recv.close() if c_addr is not None and flag is not False: sys.stdout.write("(%s) %s " % (c_addr, c_name)) for x in range(len(rt)): sys.stdout.write("%.3f ms " % rt[x]) sys.stdout.write("\n") ttl = ttl + 1 if (c_addr == d_addr): break
def AFPUsers(): mac = {} MAIN_PID = None if platform.system() in ("FreeBSD"): rx = re.compile( "^\S+\s+\S+\s+(\d+)\s+\d+\s+[\w\d]+\s+[\d\.:]+\s+([\d\.]+)") try: p = subprocess.Popen(["/usr/bin/sockstat", "-4"], stdout=subprocess.PIPE, encoding="utf8") except: print("Cannot popen sockstat: %s " % sys.exc_info()[0], file=sys.stderr) sys.exit(1) for line in p.stdout: line = line.rstrip() if AFPD_PROCESS in line: m = rx.match(line) if m is not None: pid = int(m.group(1)) host = socket.gethostbyaddr(m.group(2))[0] mac[pid] = host p.wait() try: p = subprocess.Popen(["/bin/ps", PS_STR], stdout=subprocess.PIPE, encoding="utf8") except: print("Cannot popen ps the first time: %s" % sys.exc_info()[0], file=sys.stderr) sys.exit(1) for line in p.stdout: line = line.rstrip() if NETATALK_PROCESS in line: m = match_rx.match(line) if m is not None: MAIN_PID = int(m.group(2)) p.wait() try: p = subprocess.Popen(["/bin/ps", PS_STR], stdout=subprocess.PIPE, encoding="utf8") except: print("Cannot popen ps: %s" % sys.exc_info()[0], file=sys.stderr) sys.exit(1) for line in p.stdout: line = line.rstrip() if AFPD_PROCESS in line: m = match_rx.match(line) if m is not None: user = m.group(1) pid = int(m.group(2)) ppid = int(m.group(3)) time = m.group(4) if MAIN_PID and ppid != MAIN_PID: uid = 0 fname = "" temp = pwd.getpwnam(user) if temp is not None: uid = temp.pw_uid fname = temp.pw_gecos yield (pid, uid, user, fname, time, mac[pid]) p.wait()
def verify_fqdn(host_name, no_host_dns=False, local_hostname=True): """ Run fqdn checks for given host: - test hostname format - test that hostname is fully qualified - test forward and reverse hostname DNS lookup Raises `BadHostError` or derived Exceptions if there is an error :param host_name: The host name to verify. :param no_host_dns: If true, skip DNS resolution tests of the host name. :param local_hostname: If true, run additional checks for local hostnames """ if len(host_name.split(".")) < 2 or host_name == "localhost.localdomain": raise BadHostError("Invalid hostname '%s', must be fully-qualified." % host_name) if host_name != host_name.lower(): raise BadHostError("Invalid hostname '%s', must be lower-case." % host_name) if ipautil.valid_ip(host_name): raise BadHostError("IP address not allowed as a hostname") try: # make sure that the host name meets the requirements in ipalib validate_hostname(host_name, maxlen=MAXHOSTNAMELEN) except ValueError as e: raise BadHostError("Invalid hostname '%s', %s" % (host_name, unicode(e))) if local_hostname: try: logger.debug('Check if %s is a primary hostname for localhost', host_name) ex_name = socket.gethostbyaddr(host_name) logger.debug('Primary hostname for localhost: %s', ex_name[0]) if host_name != ex_name[0]: raise HostLookupError("The host name %s does not match the primary host name %s. "\ "Please check /etc/hosts or DNS name resolution" % (host_name, ex_name[0])) except socket.gaierror: pass except socket.error as e: logger.debug('socket.gethostbyaddr() error: %d: %s', e.errno, e.strerror) # pylint: disable=no-member if no_host_dns: print("Warning: skipping DNS resolution of host", host_name) return try: logger.debug('Search DNS for %s', host_name) hostaddr = socket.getaddrinfo(host_name, None) except Exception as e: logger.debug('Search failed: %s', e) raise HostForwardLookupError( "Unable to resolve host name, check /etc/hosts or DNS name resolution" ) if len(hostaddr) == 0: raise HostForwardLookupError( "Unable to resolve host name, check /etc/hosts or DNS name resolution" ) # Verify this is NOT a CNAME try: logger.debug('Check if %s is not a CNAME', host_name) resolver.query(host_name, rdatatype.CNAME) raise HostReverseLookupError( "The IPA Server Hostname cannot be a CNAME, only A and AAAA names are allowed." ) except DNSException: pass # list of verified addresses to prevent multiple searches for the same address verified = set() for a in hostaddr: address = a[4][0] if address in verified: continue if address in ('127.0.0.1', '::1'): raise HostForwardLookupError( "The IPA Server hostname must not resolve to localhost (%s). A routable IP address must be used. Check /etc/hosts to see if %s is an alias for %s" % (address, host_name, address)) try: logger.debug('Check reverse address of %s', address) revname = socket.gethostbyaddr(address)[0] except Exception as e: logger.debug('Check failed: %s', e) logger.error( "Unable to resolve the IP address %s to a host name, " "check /etc/hosts and DNS name resolution", address) else: logger.debug('Found reverse name: %s', revname) if revname != host_name: logger.error( "The host name %s does not match the value %s obtained " "by reverse lookup on IP address %s", host_name, revname, address) verified.add(address)
def testIp(host): try: socket.gethostbyaddr(host) except: return False return True
def main(dest_name): dest_addr = socket.gethostbyname(dest_name) port = 33434 max_hops = 30 icmp = socket.getprotobyname('icmp') udp = socket.getprotobyname('udp') ttl = 1 host2 = False while True: recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp) send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl) # Build the GNU timeval struct (seconds, microseconds) timeout = struct.pack("ll", 5, 0) # Set the receive timeout so we behave more like regular traceroute recv_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeout) recv_socket.bind(("", port)) sys.stdout.write(" %d " % ttl) payload = "a" * int(sys.argv[2]) #tamano pasado por parametro en bytes send_socket.sendto(payload, (dest_name, port)) curr_addr = None curr_name = None finished = False tries = 3 while not finished and tries > 0: try: _, curr_addr = recv_socket.recvfrom(512) finished = True curr_addr = curr_addr[0] try: curr_name = socket.gethostbyaddr(curr_addr)[0] except socket.error: curr_name = curr_addr except socket.error as (errno, errmsg): tries = tries - 1 sys.stdout.write("* ") send_socket.close() recv_socket.close() if not finished: pass if curr_addr is not None: curr_host = "%s (%s)" % (curr_name, curr_addr) if curr_addr == sys.argv[4] or curr_name == sys.argv[4]: host2 = True else: curr_host = "" if sys.argv[3] == "V": #CASE FLAG = "V" OUTPUT SHOW ONLY IPADRESS sys.stdout.write("%s\n" % (curr_addr)) else: sys.stdout.write("%s\n" % (curr_host)) ttl += 1 if curr_addr == dest_addr or ttl > max_hops: if host2 == True: sys.stdout.write("Uno de los hops coincide con la direccion pasada por parametro\n ") break
def __init__(self, ipaddr="0"): try: name = socket.gethostbyaddr(ipaddr) #print name except socket.herror, e: junk = "me"
def get_hostname(host): return socket.gethostbyaddr(host)[0]
def remote_hostname(self): try: return socket.gethostbyaddr(self.remote_addr)[0] except socket.error: return self.remote_addr
import time import json #------------------------------------------------------------------------------ server_url = 'http://*****:*****@type': 'FunfEvent', 'appId': 'foobar1234', 'actor': 'TestMobileLogger', 'origin': socket.gethostbyaddr(socket.gethostname())[0], 'start': time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime()), 'probeName': 'WifiProbe', 'funfValue': '{"some": "json", "here": "ok"}' } print('Uploading: ', json.dumps(payload, indent=2)) r = requests.post(server_url + '/data/event', data=json.dumps(payload), headers={'content-type': 'application/json'}, auth=(server_username, server_password), timeout=10) print('DiMe returns:', json.dumps(r.json(), indent=2))