本文整理汇总了Python中socket.gethostbyaddr函数的典型用法代码示例。如果您正苦于以下问题:Python gethostbyaddr函数的具体用法?Python gethostbyaddr怎么用?Python gethostbyaddr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了gethostbyaddr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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.")
示例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)
示例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)
示例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
示例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)
示例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)
示例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
示例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
示例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
示例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))
示例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')
示例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)
示例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 ""))