本文整理汇总了Python中socket.getservbyname方法的典型用法代码示例。如果您正苦于以下问题:Python socket.getservbyname方法的具体用法?Python socket.getservbyname怎么用?Python socket.getservbyname使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket
的用法示例。
在下文中一共展示了socket.getservbyname方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def create(args):
vpc = ensure_vpc()
if args.security_groups is None:
args.security_groups = [__name__]
ensure_security_group(__name__, vpc, tcp_ingress=[dict(port=socket.getservbyname("nfs"),
source_security_group_name=__name__)])
creation_token = base64.b64encode(bytearray(os.urandom(24))).decode()
args.tags.append("Name=" + args.name)
create_file_system_args = dict(CreationToken=creation_token,
PerformanceMode=args.performance_mode,
ThroughputMode=args.throughput_mode,
Tags=encode_tags(args.tags))
if args.throughput_mode == "provisioned":
create_file_system_args.update(ProvisionedThroughputInMibps=args.provisioned_throughput_in_mibps)
fs = clients.efs.create_file_system(**create_file_system_args)
waiter = make_waiter(clients.efs.describe_file_systems, "FileSystems[].LifeCycleState", "available", "pathAny")
waiter.wait(FileSystemId=fs["FileSystemId"])
security_groups = [resolve_security_group(g, vpc).id for g in args.security_groups]
for subnet in vpc.subnets.all():
clients.efs.create_mount_target(FileSystemId=fs["FileSystemId"],
SubnetId=subnet.id,
SecurityGroups=security_groups)
return fs
示例2: parsePort
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def parsePort(port):
"""
Converts port in string format to an int
:param port: a string or integer value
:returns: an integer port number
:rtype: int
"""
result = None
try:
result = int(port)
except ValueError:
import socket
result = socket.getservbyname(port)
return result
示例3: validate_service_arg
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [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)
示例4: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def __init__(self, service=None):
try:
self.port = socket.getservbyname("auth")
except socket.error:
self.port = 113
self.os_name = "WIN32"
# Connections waiting for acception, per interface
self.listen_backlog = 3
self.listeners = []
self.clients = []
self.buffers = {}
self.peers = {}
self.requests = {}
self._service = service
示例5: check_name
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def check_name(self, name, objtype):
""" check name validy """
msg = None
if len(name) >= 32 or len(re.findall(r'(^_*$|^\d*$|[^a-zA-Z0-9_])', name)) > 0:
msg = "The {0} name must be less than 32 characters long, may not consist of only numbers, may not consist of only underscores, ".format(objtype)
msg += "and may only contain the following characters: a-z, A-Z, 0-9, _"
elif name in ["port", "pass"]:
msg = "The {0} name must not be either of the reserved words 'port' or 'pass'".format(objtype)
else:
try:
socket.getprotobyname(name)
msg = 'The {0} name must not be an IP protocol name such as TCP, UDP, ICMP etc.'.format(objtype)
except socket.error:
pass
try:
socket.getservbyname(name)
msg = 'The {0} name must not be a well-known or registered TCP or UDP port name such as ssh, smtp, pop3, tftp, http, openvpn etc.'.format(objtype)
except socket.error:
pass
if msg is not None:
self.module.fail_json(msg=msg)
示例6: test
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def test():
"""Test program for telnetlib.
Usage: python telnetlib.py [-d] ... [host [port]]
Default host is localhost; default port is 23.
"""
debuglevel = 0
while sys.argv[1:] and sys.argv[1] == '-d':
debuglevel = debuglevel+1
del sys.argv[1]
host = 'localhost'
if sys.argv[1:]:
host = sys.argv[1]
port = 0
if sys.argv[2:]:
portstr = sys.argv[2]
try:
port = int(portstr)
except ValueError:
port = socket.getservbyname(portstr, 'tcp')
tn = Telnet()
tn.set_debuglevel(debuglevel)
tn.open(host, port, timeout=0.5)
tn.interact()
tn.close()
示例7: testGetServBy
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [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)
示例8: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def __init__(self, host, port, factory, timeout, bindAddress, reactor=None):
if isinstance(port, _portNameType):
try:
port = socket.getservbyname(port, 'tcp')
except socket.error as e:
raise error.ServiceNameUnknownError(string="%s (%r)" % (e, port))
self.host, self.port = host, port
if abstract.isIPv6Address(host):
self._addressType = address.IPv6Address
self.bindAddress = bindAddress
base.BaseConnector.__init__(self, factory, timeout, reactor)
示例9: test_connectByService
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def test_connectByService(self):
"""
L{IReactorTCP.connectTCP} accepts the name of a service instead of a
port number and connects to the port number associated with that
service, as defined by L{socket.getservbyname}.
"""
serverFactory = MyServerFactory()
serverConnMade = defer.Deferred()
serverFactory.protocolConnectionMade = serverConnMade
port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
self.addCleanup(port.stopListening)
portNumber = port.getHost().port
clientFactory = MyClientFactory()
clientConnMade = defer.Deferred()
clientFactory.protocolConnectionMade = clientConnMade
def fakeGetServicePortByName(serviceName, protocolName):
if serviceName == 'http' and protocolName == 'tcp':
return portNumber
return 10
self.patch(socket, 'getservbyname', fakeGetServicePortByName)
reactor.connectTCP('127.0.0.1', 'http', clientFactory)
connMade = defer.gatherResults([serverConnMade, clientConnMade])
def connected(result):
serverProtocol, clientProtocol = result
self.assertTrue(
serverFactory.called,
"Server factory was not called upon to build a protocol.")
serverProtocol.transport.loseConnection()
clientProtocol.transport.loseConnection()
connMade.addCallback(connected)
return connMade
示例10: port_to_int
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def port_to_int(port):
"""Convert a port string to an integer."""
try:
return int(port)
except ValueError:
return socket.getservbyname(port)
示例11: get_valid_port
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def get_valid_port(port):
if isinstance(port, str):
try:
port = int(socket.getservbyname(port.lower()))
except OSError:
raise ValueError("Service for port '{}' not found.".format(port.lower()))
elif isinstance(port, int):
if not 0 <= port <= 65535:
raise ValueError("Port must be between 0 and 65535.")
else:
raise ValueError("Invalid port '{}'.".format(port))
return port
示例12: testGetServBy
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [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)
示例13: get_envoy_admin_port
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def get_envoy_admin_port(self) -> int:
""" Get the port that Envoy's admin interface is listening on
from /etc/services. """
return socket.getservbyname(
self.config_dict.get("envoy_admin_domain_name", "envoy-admin")
)
示例14: test
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def test():
"""Test program for telnetlib.
Usage: python telnetlib.py [-d] ... [host [port]]
Default host is localhost; default port is 23.
"""
debuglevel = 0
while sys.argv[1:] and sys.argv[1] == '-d':
debuglevel = debuglevel+1
del sys.argv[1]
host = 'localhost'
if sys.argv[1:]:
host = sys.argv[1]
port = 0
if sys.argv[2:]:
portstr = sys.argv[2]
try:
port = int(portstr)
except ValueError:
port = socket.getservbyname(portstr, 'tcp')
with Telnet() as tn:
tn.set_debuglevel(debuglevel)
tn.open(host, port, timeout=0.5)
tn.interact()
示例15: from_text
# 需要导入模块: import socket [as 别名]
# 或者: from socket import getservbyname [as 别名]
def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True):
address = tok.get_string()
protocol = tok.get_string()
if protocol.isdigit():
protocol = int(protocol)
else:
protocol = socket.getprotobyname(protocol)
bitmap = bytearray()
while 1:
token = tok.get().unescape()
if token.is_eol_or_eof():
break
if token.value.isdigit():
serv = int(token.value)
else:
if protocol != _proto_udp and protocol != _proto_tcp:
raise NotImplementedError("protocol must be TCP or UDP")
if protocol == _proto_udp:
protocol_text = "udp"
else:
protocol_text = "tcp"
serv = socket.getservbyname(token.value, protocol_text)
i = serv // 8
l = len(bitmap)
if l < i + 1:
for j in xrange(l, i + 1):
bitmap.append(0)
bitmap[i] = bitmap[i] | (0x80 >> (serv % 8))
bitmap = dns.rdata._truncate_bitmap(bitmap)
return cls(rdclass, rdtype, address, protocol, bitmap)