def get_ips_from_url(url):
"""
Retrieve IPs from url
:param str url: The url to resolve
:rtype: list
:return: the list of resolved IP address for given url
"""
try:
parsed = urlparse(url)
if parsed.hostname:
socket.setdefaulttimeout(5)
ips = socket.gethostbyname_ex(parsed.hostname)[2]
return ips
except (ValueError, socket.error, socket.gaierror, socket.herror, socket.timeout):
pass
python类gaierror()的实例源码
def request(self, method, url, body, headers):
# Calculate the absolute URI, which fetch requires
netloc = self.host
if self.port:
netloc = '%s:%s' % (self.host, self.port)
absolute_uri = '%s://%s%s' % (self.scheme, netloc, url)
try:
response = fetch(absolute_uri, payload=body, method=method,
headers=headers, allow_truncated=False, follow_redirects=False,
deadline=self.timeout,
validate_certificate=self.validate_certificate)
self.response = ResponseDict(response.headers)
self.response['status'] = str(response.status_code)
self.response['reason'] = httplib.responses.get(response.status_code, 'Ok')
self.response.status = response.status_code
setattr(self.response, 'read', lambda : response.content)
# Make sure the exceptions raised match the exceptions expected.
except InvalidURLError:
raise socket.gaierror('')
except (DownloadError, ResponseTooLargeError, SSLCertificateError):
raise httplib.HTTPException()
def gethostbyname2(self, hostname):
try:
iplist = self.dns_cache[hostname]
except KeyError:
if re.match(r'^\d+\.\d+\.\d+\.\d+$', hostname) or ':' in hostname:
iplist = [hostname]
elif self.dns_servers:
try:
record = dnslib_resolve_over_udp(hostname, self.dns_servers, timeout=2, blacklist=self.dns_blacklist)
except socket.gaierror:
record = dnslib_resolve_over_tcp(hostname, self.dns_servers, timeout=2, blacklist=self.dns_blacklist)
iplist = dnslib_record2iplist(record)
else:
iplist = socket.gethostbyname_ex(hostname)[-1]
self.dns_cache[hostname] = iplist
return iplist
def choose_boundary():
"""Return a string usable as a multipart boundary.
The string chosen is unique within a single program run, and
incorporates the user id (if available), process id (if available),
and current time. So it's very unlikely the returned string appears
in message text, but there's no guarantee.
The boundary contains dots so you have to quote it in the header."""
global _prefix
import time
if _prefix is None:
import socket
try:
hostid = socket.gethostbyname(socket.gethostname())
except socket.gaierror:
hostid = '127.0.0.1'
try:
uid = repr(os.getuid())
except AttributeError:
uid = '1'
try:
pid = repr(os.getpid())
except AttributeError:
pid = '1'
_prefix = hostid + '.' + uid + '.' + pid
return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter())
# Subroutines for decoding some common content-transfer-types
def select_ip_version(host, port):
"""Returns AF_INET4 or AF_INET6 depending on where to connect to."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with any other
# ways to implement this.
# try:
# info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
# socket.SOCK_STREAM, 0,
# socket.AI_PASSIVE)
# if info:
# return info[0][0]
# except socket.gaierror:
# pass
if ':' in host and hasattr(socket, 'AF_INET6'):
return socket.AF_INET6
return socket.AF_INET
def select_ip_version(host, port):
"""Returns AF_INET4 or AF_INET6 depending on where to connect to."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with any other
# ways to implement this.
# try:
# info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
# socket.SOCK_STREAM, 0,
# socket.AI_PASSIVE)
# if info:
# return info[0][0]
# except socket.gaierror:
# pass
if ':' in host and hasattr(socket, 'AF_INET6'):
return socket.AF_INET6
return socket.AF_INET
def resolve(self, host, port, family):
"""Return list of (family, address) pairs."""
child_gr = greenlet.getcurrent()
main = child_gr.parent
assert main is not None, "Should be on child greenlet"
def handler(exc_typ, exc_val, exc_tb):
# If netutil.Resolver is configured to use TwistedResolver.
if DomainError and issubclass(exc_typ, DomainError):
exc_typ = socket.gaierror
exc_val = socket.gaierror(str(exc_val))
# Depending on the resolver implementation, we could be on any
# thread or greenlet. Return to the loop's thread and raise the
# exception on the calling greenlet from there.
self.io_loop.add_callback(functools.partial(
child_gr.throw, exc_typ, exc_val, exc_tb))
return True # Don't propagate the exception.
with stack_context.ExceptionStackContext(handler):
self.resolver.resolve(host, port, family, callback=child_gr.switch)
return main.switch()
simple_httpclient_test.py 文件源码
项目:noc-orchestrator
作者: DirceuSilvaLabs
项目源码
文件源码
阅读 48
收藏 0
点赞 0
评论 0
def test_ipv6(self):
try:
[sock] = bind_sockets(None, '::1', family=socket.AF_INET6)
port = sock.getsockname()[1]
self.http_server.add_socket(sock)
except socket.gaierror as e:
if e.args[0] == socket.EAI_ADDRFAMILY:
# python supports ipv6, but it's not configured on the network
# interface, so skip this test.
return
raise
url = '%s://[::1]:%d/hello' % (self.get_protocol(), port)
# ipv6 is currently enabled by default but can be disabled
self.http_client.fetch(url, self.stop, allow_ipv6=False)
response = self.wait()
self.assertEqual(response.code, 599)
self.http_client.fetch(url, self.stop)
response = self.wait()
self.assertEqual(response.body, b"Hello world!")
def resolve(self, host, port, family):
"""Return list of (family, address) pairs."""
child_gr = greenlet.getcurrent()
main = child_gr.parent
assert main is not None, "Should be on child greenlet"
def handler(exc_typ, exc_val, exc_tb):
# If netutil.Resolver is configured to use TwistedResolver.
if DomainError and issubclass(exc_typ, DomainError):
exc_typ = socket.gaierror
exc_val = socket.gaierror(str(exc_val))
# Depending on the resolver implementation, we could be on any
# thread or greenlet. Return to the loop's thread and raise the
# exception on the calling greenlet from there.
self.io_loop.add_callback(functools.partial(
child_gr.throw, exc_typ, exc_val, exc_tb))
return True # Don't propagate the exception.
with stack_context.ExceptionStackContext(handler):
self.resolver.resolve(host, port, family, callback=child_gr.switch)
return main.switch()
simple_httpclient_test.py 文件源码
项目:noc-orchestrator
作者: DirceuSilvaLabs
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
def test_ipv6(self):
try:
[sock] = bind_sockets(None, '::1', family=socket.AF_INET6)
port = sock.getsockname()[1]
self.http_server.add_socket(sock)
except socket.gaierror as e:
if e.args[0] == socket.EAI_ADDRFAMILY:
# python supports ipv6, but it's not configured on the network
# interface, so skip this test.
return
raise
url = '%s://[::1]:%d/hello' % (self.get_protocol(), port)
# ipv6 is currently enabled by default but can be disabled
self.http_client.fetch(url, self.stop, allow_ipv6=False)
response = self.wait()
self.assertEqual(response.code, 599)
self.http_client.fetch(url, self.stop)
response = self.wait()
self.assertEqual(response.body, b"Hello world!")
def is_valid_ip(ip):
"""Returns true if the given string is a well-formed IP address.
Supports IPv4 and IPv6.
"""
if not ip or '\x00' in ip:
# getaddrinfo resolves empty strings to localhost, and truncates
# on zero bytes.
return False
try:
res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
socket.SOCK_STREAM,
0, socket.AI_NUMERICHOST)
return bool(res)
except socket.gaierror as e:
if e.args[0] == socket.EAI_NONAME:
return False
raise
return True
def resolve(self, host, port, family):
"""Return list of (family, address) pairs."""
child_gr = greenlet.getcurrent()
main = child_gr.parent
assert main is not None, "Should be on child greenlet"
def handler(exc_typ, exc_val, exc_tb):
# If netutil.Resolver is configured to use TwistedResolver.
if DomainError and issubclass(exc_typ, DomainError):
exc_typ = socket.gaierror
exc_val = socket.gaierror(str(exc_val))
# Depending on the resolver implementation, we could be on any
# thread or greenlet. Return to the loop's thread and raise the
# exception on the calling greenlet from there.
self.io_loop.add_callback(functools.partial(
child_gr.throw, exc_typ, exc_val, exc_tb))
return True # Don't propagate the exception.
with stack_context.ExceptionStackContext(handler):
self.resolver.resolve(host, port, family, callback=child_gr.switch)
return main.switch()
def is_valid_ip(ip):
"""Returns true if the given string is a well-formed IP address.
Supports IPv4 and IPv6.
"""
if not ip or '\x00' in ip:
# getaddrinfo resolves empty strings to localhost, and truncates
# on zero bytes.
return False
try:
res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
socket.SOCK_STREAM,
0, socket.AI_NUMERICHOST)
return bool(res)
except socket.gaierror as e:
if e.args[0] == socket.EAI_NONAME:
return False
raise
return True
def resolve(self, host, port, family):
"""Return list of (family, address) pairs."""
child_gr = greenlet.getcurrent()
main = child_gr.parent
assert main is not None, "Should be on child greenlet"
def handler(exc_typ, exc_val, exc_tb):
# If netutil.Resolver is configured to use TwistedResolver.
if DomainError and issubclass(exc_typ, DomainError):
exc_typ = socket.gaierror
exc_val = socket.gaierror(str(exc_val))
# Depending on the resolver implementation, we could be on any
# thread or greenlet. Return to the loop's thread and raise the
# exception on the calling greenlet from there.
self.io_loop.add_callback(functools.partial(
child_gr.throw, exc_typ, exc_val, exc_tb))
return True # Don't propagate the exception.
with stack_context.ExceptionStackContext(handler):
self.resolver.resolve(host, port, family, callback=child_gr.switch)
return main.switch()
def run(self):
value = getword()
try:
print "-"*12
print "User:",user[:-1],"Password:",value
pop = poplib.POP3(ipaddr[0])
pop.user(user[:-1])
pop.pass_(value)
print "\t\nLogin successful:",value, user
print pop.stat()
pop.quit()
work.join()
sys.exit(2)
except(poplib.error_proto, socket.gaierror, socket.error, socket.herror), msg:
#print "An error occurred:", msg
pass
def sendchk(listindex, host, user, password): # seperated function for checking
try:
smtp = smtplib.SMTP(host)
smtp.login(user, password)
code = smtp.ehlo()[0]
if not (200 <= code <= 299):
code = smtp.helo()[0]
if not (200 <= code <= 299):
raise SMTPHeloError(code, resp)
smtp.sendmail(fromaddr, toaddr, message)
print "\n\t[!] Email Sent Successfully:",host, user, password
print "\t[!] Message Sent Successfully\n"
LSstring = host+":"+user+":"+password+"\n"
nList.append(LSstring) # special list for AMS file ID's
LFile = open(output, "a")
LFile.write(LSstring) # save working host/usr/pass to file
LFile.close()
AMSout = open("AMSlist.txt", "a")
AMSout.write("[Server"+str(nList.index(LSstring))+"]\nName="+str(host)+"\nPort=25\nUserID=User\nBccSize=50\nUserName="+str(user)+"\nPassword="+str(password)+"\nAuthType=0\n\n")
smtp.quit()
except(socket.gaierror, socket.error, socket.herror, smtplib.SMTPException), msg:
print "[-] Login Failed:", host, user, password
pass
def test(host):
socket.setdefaulttimeout(5)
if int(verbose) == 1:
s.send("PRIVMSG %s :%s%s\r\n" % (CHAN, "[+] Testing:", host))
try:
if host[:7] != "http://":
host = "http://"+host
source = urllib2.urlopen(host).read()
if re.search(MATCH, source):
s.send("PRIVMSG %s :%s%s\r\n" % (CHAN, "[!] Found:", host))
file = open("foundsqli.txt", "a")
file.write("\n[!] Found: "+host)
file.close()
else:
if int(verbose) == 1:
s.send("PRIVMSG %s :%s%s\r\n" % (CHAN, "[-] Not Vuln:", host))
except(socket.gaierror, socket.timeout, socket.error), msg:
s.send("PRIVMSG %s :%s%s @ %s\r\n" % (CHAN, "[-] Error: ",msg, host))
except:
pass
def select_ip_version(host, port):
"""Returns AF_INET4 or AF_INET6 depending on where to connect to."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with any other
# ways to implement this.
# try:
# info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
# socket.SOCK_STREAM, 0,
# socket.AI_PASSIVE)
# if info:
# return info[0][0]
# except socket.gaierror:
# pass
if ':' in host and hasattr(socket, 'AF_INET6'):
return socket.AF_INET6
return socket.AF_INET
def isProgramURL(url: str, acceptAll=True) -> bool:
""" Whether the given url is a program URL """
domain = urlparse(url).netloc.split(':')[0].lower()
if not config.domains:
return True
if config.domains or (not acceptAll):
try:
ip = socket.gethostbyname(domain)
except (socket.gaierror, UnicodeError):
ip = None
if domain and isinstance(config.domains, list):
return (any([domain.endswith(hostname.lower()) for hostname in config.domains]) and
ip != '127.0.0.1')
return False
if acceptAll:
return True
def select_ip_version(host, port):
"""Returns AF_INET4 or AF_INET6 depending on where to connect to."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with any other
# ways to implement this.
# try:
# info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
# socket.SOCK_STREAM, 0,
# socket.AI_PASSIVE)
# if info:
# return info[0][0]
# except socket.gaierror:
# pass
if ':' in host and hasattr(socket, 'AF_INET6'):
return socket.AF_INET6
return socket.AF_INET
def select_ip_version(host, port):
"""Returns AF_INET4 or AF_INET6 depending on where to connect to."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with any other
# ways to implement this.
# try:
# info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
# socket.SOCK_STREAM, 0,
# socket.AI_PASSIVE)
# if info:
# return info[0][0]
# except socket.gaierror:
# pass
if ':' in host and hasattr(socket, 'AF_INET6'):
return socket.AF_INET6
return socket.AF_INET
def select_ip_version(host, port):
"""Returns AF_INET4 or AF_INET6 depending on where to connect to."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with any other
# ways to implement this.
# try:
# info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
# socket.SOCK_STREAM, 0,
# socket.AI_PASSIVE)
# if info:
# return info[0][0]
# except socket.gaierror:
# pass
if ':' in host and hasattr(socket, 'AF_INET6'):
return socket.AF_INET6
return socket.AF_INET
def select_ip_version(host, port):
"""Returns AF_INET4 or AF_INET6 depending on where to connect to."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with any other
# ways to implement this.
# try:
# info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
# socket.SOCK_STREAM, 0,
# socket.AI_PASSIVE)
# if info:
# return info[0][0]
# except socket.gaierror:
# pass
if ':' in host and hasattr(socket, 'AF_INET6'):
return socket.AF_INET6
return socket.AF_INET
def verbose_ping(dest_addr, timeout = 2, count = 5):
"""
Send >count< ping to >dest_addr< with the given >timeout< and display
the result.
"""
Stats = "socketError"
for i in xrange(count):
print "ping %s..." % dest_addr,
try:
delay = do_one(dest_addr, timeout)
except socket.gaierror, e:
print "failed. (socket error: '%s')" % e[1]
break
if delay == None:
print "failed. (timeout within %ssec.)" % timeout
Stats = "Down"
else:
delay = delay * 1000
print "get ping in %0.4fms" % delay
return "Up"
print
return Stats
def select_ip_version(host, port):
"""Returns AF_INET4 or AF_INET6 depending on where to connect to."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with any other
# ways to implement this.
# try:
# info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
# socket.SOCK_STREAM, 0,
# socket.AI_PASSIVE)
# if info:
# return info[0][0]
# except socket.gaierror:
# pass
if ':' in host and hasattr(socket, 'AF_INET6'):
return socket.AF_INET6
return socket.AF_INET
def get_camera_details(self):
"""
Return the details of the cameras.
@rtype: list [str]
@return: ordered list of camera details
"""
camera_dict = dict()
camera_config_param = "/robot_config/camera_config"
try:
camera_dict = rospy.get_param(camera_config_param)
except KeyError:
rospy.logerr("RobotParam:get_camera_details cannot detect any "
"cameras under the parameter {0}".format(camera_config_param))
except (socket.error, socket.gaierror):
self._log_networking_error()
return camera_dict
def get_robot_assemblies(self):
"""
Return the names of the robot's assemblies from ROS parameter.
@rtype: list [str]
@return: ordered list of assembly names
(e.g. right, left, torso, head). on networked robot
"""
assemblies = list()
try:
assemblies = rospy.get_param("/robot_config/assembly_names")
except KeyError:
rospy.logerr("RobotParam:get_robot_assemblies cannot detect assembly names"
" under param /robot_config/assembly_names")
except (socket.error, socket.gaierror):
self._log_networking_error()
return assemblies
def get_joint_names(self, limb_name):
"""
Return the names of the joints for the specified
limb from ROS parameter.
@type limb_name: str
@param limb_name: name of the limb for which to retrieve joint names
@rtype: list [str]
@return: ordered list of joint names from proximal to distal
(i.e. shoulder to wrist). joint names for limb
"""
joint_names = list()
try:
joint_names = rospy.get_param(
"robot_config/{0}_config/joint_names".format(limb_name))
except KeyError:
rospy.logerr(("RobotParam:get_joint_names cannot detect joint_names for"
" arm \"{0}\"").format(limb_name))
except (socket.error, socket.gaierror):
self._log_networking_error()
return joint_names
def get_robot_name(self):
"""
Return the name of class of robot from ROS parameter.
@rtype: str
@return: name of the class of robot (eg. "sawyer", "baxter", etc.)
"""
robot_name = None
try:
robot_name = rospy.get_param("/manifest/robot_class")
except KeyError:
rospy.logerr("RobotParam:get_robot_name cannot detect robot name"
" under param /manifest/robot_class")
except (socket.error, socket.gaierror):
self._log_networking_error()
return robot_name
def select_ip_version(host, port):
"""Returns AF_INET4 or AF_INET6 depending on where to connect to."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with any other
# ways to implement this.
##try:
## info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
## socket.SOCK_STREAM, 0,
## socket.AI_PASSIVE)
## if info:
## return info[0][0]
##except socket.gaierror:
## pass
if ':' in host and hasattr(socket, 'AF_INET6'):
return socket.AF_INET6
return socket.AF_INET