本文整理匯總了Python中socket.getservbyport方法的典型用法代碼示例。如果您正苦於以下問題:Python socket.getservbyport方法的具體用法?Python socket.getservbyport怎麽用?Python socket.getservbyport使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類socket
的用法示例。
在下文中一共展示了socket.getservbyport方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: scan
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def scan(ip,port,l):
printer("Testing Port: "+str(port))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
space = 10 - l
space = " " * space
if s.connect_ex((ip,port)):
return None
else :
try:
service = socket.getservbyport(port)
print(str(port) + "/TCP" + space + service)
except socket.error:
print(str(port) + "/TCP" + space + "Unknown")
except KeyboardInterrupt:
print(red+"[-] Exiting!"+end)
exit(1)
return True
示例2: validate_service_arg
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def validate_service_arg(args, name):
"""Validate a service argument. Can be either a port number, a port range,
or a symbolic service name from /etc/services."""
value = args.get(name) if isinstance(args, dict) else args
if value.isdigit():
port = int(value)
if not 1 <= port < 65536:
raise ValueError('illegal port number for {0}: {1}'.format(name, value))
try:
name = socket.getservbyport(port)
except socket.error:
name = 'p-{0}'.format(port)
elif re_range.match(value):
start, end = map(int, value.split('-'))
if not 1 <= start < 65536 or not 1 <= end < 65536 or end <= start:
raise ValueError('illegal port range for {0}: {1}'.format(name, value))
name = 'r-{0}+{1}'.format(start, end-start)
else:
name = value
try:
value = socket.getservbyname(name)
except socket.error:
raise ValueError('unknown service for {0}: {1}'.format(name, value))
return (name, value)
示例3: testGetServBy
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def testGetServBy(self):
eq = self.assertEqual
# Find one service that exists, then check all the related interfaces.
# I've ordered this by protocols that have both a tcp and udp
# protocol, at least for modern Linuxes.
if (sys.platform.startswith('linux') or
sys.platform.startswith('freebsd') or
sys.platform.startswith('netbsd') or
sys.platform == 'darwin'):
# avoid the 'echo' service on this platform, as there is an
# assumption breaking non-standard port/protocol entry
services = ('daytime', 'qotd', 'domain')
else:
services = ('echo', 'daytime', 'domain')
for service in services:
try:
port = socket.getservbyname(service, 'tcp')
break
except socket.error:
pass
else:
raise socket.error
# Try same call with optional protocol omitted
port2 = socket.getservbyname(service)
eq(port, port2)
# Try udp, but don't barf if it doesn't exist
try:
udpport = socket.getservbyname(service, 'udp')
except socket.error:
udpport = None
else:
eq(udpport, port)
# Now make sure the lookup by port returns the same service name
eq(socket.getservbyport(port2), service)
eq(socket.getservbyport(port, 'tcp'), service)
if udpport is not None:
eq(socket.getservbyport(udpport, 'udp'), service)
# Make sure getservbyport does not accept out of range ports.
self.assertRaises(OverflowError, socket.getservbyport, -1)
self.assertRaises(OverflowError, socket.getservbyport, 65536)
示例4: sock_conn
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def sock_conn(ip, port, output, result):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
s.connect((ip, port))
s.close()
service = socket.getservbyport(port, 'tcp')
print(G + '[+] ' + C + str(port).ljust(7) + W + service.ljust(9))
if output != 'None':
result.update({str(port):service})
except:
s.close()
pass
示例5: service
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def service(self):
# Resolve ports to their services, if known
default = "({} {})".format(self.src_port, self.dest_port)
with contextlib.suppress(OSError):
return socket.getservbyport(self.src_port)
with contextlib.suppress(OSError):
return socket.getservbyport(self.dest_port)
return default
示例6: testGetServBy
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def testGetServBy(self):
eq = self.assertEqual
# Find one service that exists, then check all the related interfaces.
# I've ordered this by protocols that have both a tcp and udp
# protocol, at least for modern Linuxes.
if (sys.platform.startswith(('freebsd', 'netbsd', 'gnukfreebsd'))
or sys.platform in ('linux', 'darwin')):
# avoid the 'echo' service on this platform, as there is an
# assumption breaking non-standard port/protocol entry
services = ('daytime', 'qotd', 'domain')
else:
services = ('echo', 'daytime', 'domain')
for service in services:
try:
port = socket.getservbyname(service, 'tcp')
break
except OSError:
pass
else:
raise OSError
# Try same call with optional protocol omitted
port2 = socket.getservbyname(service)
eq(port, port2)
# Try udp, but don't barf if it doesn't exist
try:
udpport = socket.getservbyname(service, 'udp')
except OSError:
udpport = None
else:
eq(udpport, port)
# Now make sure the lookup by port returns the same service name
eq(socket.getservbyport(port2), service)
eq(socket.getservbyport(port, 'tcp'), service)
if udpport is not None:
eq(socket.getservbyport(udpport, 'udp'), service)
# Make sure getservbyport does not accept out of range ports.
self.assertRaises(OverflowError, socket.getservbyport, -1)
self.assertRaises(OverflowError, socket.getservbyport, 65536)
示例7: find_service_name
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def find_service_name():
protocolname = 'tcp'
for port in [80, 25]:
print ("Port: %s => service name: %s" %(port, socket.getservbyport(port, protocolname)))
print ("Port: %s => service name: %s" %(53, socket.getservbyport(53, 'udp')))
開發者ID:PacktPublishing,項目名稱:Learning-Python-Networking-Second-Edition,代碼行數:8,代碼來源:socket_finding_service_name.py
示例8: _getnameinfo
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def _getnameinfo(sockaddr, flags=0):
host = sockaddr[0]
port = sockaddr[1]
if len(sockaddr) == 4:
scope = sockaddr[3]
family = socket.AF_INET6
else:
scope = None
family = socket.AF_INET
tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM,
socket.SOL_TCP, 0)
if len(tuples) > 1:
raise socket.error('sockaddr resolved to multiple addresses')
addr = tuples[0][4][0]
if flags & socket.NI_DGRAM:
pname = 'udp'
else:
pname = 'tcp'
qname = dns.reversename.from_address(addr)
if flags & socket.NI_NUMERICHOST == 0:
try:
answer = _resolver.query(qname, 'PTR')
hostname = answer.rrset[0].target.to_text(True)
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
if flags & socket.NI_NAMEREQD:
raise socket.gaierror(socket.EAI_NONAME)
hostname = addr
if scope is not None:
hostname += '%' + str(scope)
else:
hostname = addr
if scope is not None:
hostname += '%' + str(scope)
if flags & socket.NI_NUMERICSERV:
service = str(port)
else:
service = socket.getservbyport(port, pname)
return (hostname, service)
示例9: test_getservbyport
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def test_getservbyport(self):
self.assertEqual(_socket.getservbyport(80), "http")
示例10: getservbyport
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def getservbyport(port):
"""Like socket.getservbyport() but return a descriptive string if the
service is not found."""
try:
name = socket.getservbyport(port)
except socket.error:
name = 'port-{0}'.format(port)
return name
示例11: url_is_local
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def url_is_local (arg) :
"""
Returns True if the given url points to localhost.
We consider all URLs which explicitly define a port as non-local, because it
looks like someone wants to explicitly use some protocol --
`ssh://localost:2222/` is likely to point at an ssh tunnel.
If, however, the port matches the default port for the given protocol, we
consider it local again -- `ssh://localhost:22/` is most likely a real local
activity.
Note that the schema set operates on substring level, so that we will accept
port 22 for `ssh` and also for `sge+ssh` -- this may break in corner cases
(altough I can't think of any right now).
"""
u = saga.Url (arg)
if not host_is_local (u.host) :
return False
# host is local, but what does the port indicate?
if u.port and u.port > 0 :
try :
if socket.getservbyport (u.port) in u.schema :
# some non-default port is used -- consider remote
return False
except :
# unknown service port --assume this is non-standard...
return False
# port is not set or points to default port for service
return True
# --------------------------------------------------------------------
#
示例12: testGetServBy
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def testGetServBy(self):
eq = self.assertEqual
# Find one service that exists, then check all the related interfaces.
# I've ordered this by protocols that have both a tcp and udp
# protocol, at least for modern Linuxes.
if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
'darwin') or is_bsd:
# avoid the 'echo' service on this platform, as there is an
# assumption breaking non-standard port/protocol entry
services = ('daytime', 'qotd', 'domain')
else:
services = ('echo', 'daytime', 'domain')
for service in services:
try:
port = socket.getservbyname(service, 'tcp')
break
except socket.error:
pass
else:
raise socket.error
# Try same call with optional protocol omitted
port2 = socket.getservbyname(service)
eq(port, port2)
# Try udp, but don't barf it it doesn't exist
try:
udpport = socket.getservbyname(service, 'udp')
except socket.error:
udpport = None
else:
eq(udpport, port)
# Now make sure the lookup by port returns the same service name
eq(socket.getservbyport(port2), service)
eq(socket.getservbyport(port, 'tcp'), service)
if udpport is not None:
eq(socket.getservbyport(udpport, 'udp'), service)
示例13: _getnameinfo
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def _getnameinfo(sockaddr, flags=0):
host = sockaddr[0]
port = sockaddr[1]
if len(sockaddr) == 4:
scope = sockaddr[3]
family = socket.AF_INET6
else:
scope = None
family = socket.AF_INET
tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM,
socket.SOL_TCP, 0)
if len(tuples) > 1:
raise socket.error('sockaddr resolved to multiple addresses')
addr = tuples[0][4][0]
if flags & socket.NI_DGRAM:
pname = 'udp'
else:
pname = 'tcp'
qname = thirdparty.dns.reversename.from_address(addr)
if flags & socket.NI_NUMERICHOST == 0:
try:
answer = _resolver.query(qname, 'PTR')
hostname = answer.rrset[0].target.to_text(True)
except (thirdparty.dns.resolver.NXDOMAIN, thirdparty.dns.resolver.NoAnswer):
if flags & socket.NI_NAMEREQD:
raise socket.gaierror(socket.EAI_NONAME)
hostname = addr
if scope is not None:
hostname += '%' + str(scope)
else:
hostname = addr
if scope is not None:
hostname += '%' + str(scope)
if flags & socket.NI_NUMERICSERV:
service = str(port)
else:
service = socket.getservbyport(port, pname)
return (hostname, service)
示例14: remote_proto
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def remote_proto(self):
"""Identification of the protocol associated with the remote port.
Equals ``remote_port`` if no protocol is associated with it.
:type: :class:`str` or :class:`int`
"""
try:
return socket.getservbyport(self.remote_port, 'tcp')
except socket.error:
return self.remote_port
示例15: test_permit_privileged_ports
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getservbyport [as 別名]
def test_permit_privileged_ports(self):
# Test FTPHandler.permit_privileged_ports_active attribute
# try to bind a socket on a privileged port
sock = None
for port in reversed(range(1, 1024)):
try:
socket.getservbyport(port)
except socket.error:
# not registered port; go on
try:
sock = socket.socket(self.client.af, socket.SOCK_STREAM)
sock.settimeout(TIMEOUT)
sock.bind((HOST, port))
break
except socket.error as err:
if err.errno == errno.EACCES:
# root privileges needed
if sock is not None:
sock.close()
sock = None
break
sock.close()
continue
else:
# registered port found; skip to the next one
continue
else:
# no usable privileged port was found
sock = None
self.addCleanup(sock.close)
self.server.handler.permit_privileged_ports = False
self.assertRaises(ftplib.error_perm, self.client.sendport, HOST,
port)
if sock:
port = sock.getsockname()[1]
self.server.handler.permit_privileged_ports = True
sock.listen(5)
sock.settimeout(TIMEOUT)
self.client.sendport(HOST, port)
s, addr = sock.accept()
s.close()