• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python socket.gethostbyaddr函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中socket.gethostbyaddr函数的典型用法代码示例。如果您正苦于以下问题:Python gethostbyaddr函数的具体用法?Python gethostbyaddr怎么用?Python gethostbyaddr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了gethostbyaddr函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: connect

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)
开发者ID:vkuznet,项目名称:bapp,代码行数:26,代码来源:pyerl_client.py


示例2: tryToConnect

 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)
开发者ID:champ1,项目名称:proxy-suggester,代码行数:29,代码来源:connection.py


示例3: __init__

    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.")
开发者ID:KurSh,项目名称:peach,代码行数:27,代码来源:websocket.py


示例4: lbvserver

    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)
开发者ID:jimbrowne,项目名称:netscaler-tool,代码行数:26,代码来源:netscalertool.py


示例5: list_connections

 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)
开发者ID:boothead,项目名称:txrabbitmq,代码行数:31,代码来源:rabbitmqctl_service.py


示例6: user_owns_machine

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
开发者ID:anantshri,项目名称:reaper,代码行数:35,代码来源:permissionutils.py


示例7: HandleAuthPacket

        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)
开发者ID:AkankshaGovil,项目名称:Automation,代码行数:28,代码来源:radserver.py


示例8: HandleAcctPacket

        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)
开发者ID:AkankshaGovil,项目名称:Automation,代码行数:33,代码来源:radserver.py


示例9: scan_server

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
开发者ID:MetalBurning,项目名称:CS_Files,代码行数:26,代码来源:Scanner.py


示例10: render_arcus_graph

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
开发者ID:fengshao0907,项目名称:hubblemon,代码行数:60,代码来源:arcus_view.py


示例11: send_email

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
开发者ID:Emory-LCS,项目名称:Alma-Public,代码行数:31,代码来源:finish_spine_labels.py


示例12: __resolve_address

 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))
开发者ID:svetlyak40wt,项目名称:yandex-tank,代码行数:33,代码来源:Phantom.py


示例13: checkSIPFaxNeg

    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')
开发者ID:AkankshaGovil,项目名称:Automation,代码行数:32,代码来源:call.py


示例14: request_processor

    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)   
开发者ID:celiafish,项目名称:data_workflow,代码行数:27,代码来源:view_util.py


示例15: setup

 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 ""))
开发者ID:phillipberndt,项目名称:scripts,代码行数:27,代码来源:on.py


示例16: test_gethostbyaddr

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
开发者ID:ilib0x00000000,项目名称:NULL,代码行数:7,代码来源:py_socket_base.py


示例17: __init__

    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)
开发者ID:constantAmateur,项目名称:sciteit,代码行数:30,代码来源:services.py


示例18: IPscanner

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() 
开发者ID:7base,项目名称:portscan,代码行数:26,代码来源:ipscanner.py


示例19: test_gethostbyaddr

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,))
开发者ID:charred,项目名称:pypy,代码行数:27,代码来源:test_rsocket.py


示例20: nslookup

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)
开发者ID:baranbartu,项目名称:redis-py-cluster,代码行数:7,代码来源:utils.py



注:本文中的socket.gethostbyaddr函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python socket.gethostbyname函数代码示例发布时间:2022-05-27
下一篇:
Python socket.getfqdn函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap