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', 'freebsd7', '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 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)
def ReplacePortNames(port_range_string): """Replace port names with port numbers in a port-range string. Args: port_range_string: The string to parse. Returns: A port range string specifying ports only by number. Raises: ValueError: If the port_range_string is the wrong type or malformed. """ if not isinstance(port_range_string, basestring): raise ValueError('Invalid port range: %s' % port_range_string) ports = port_range_string.split('-') if len(ports) not in [1, 2]: raise ValueError('Invalid port range: %s' % port_range_string) try: low_port = socket.getservbyname(ports[0]) except socket.error: low_port = int(ports[0]) try: high_port = socket.getservbyname(ports[-1]) except socket.error: high_port = int(ports[-1]) if low_port == high_port: return '%d' % low_port else: return '%d-%d' % (low_port, high_port)
def get_port(p): sport = p.sprintf("%TCP.sport%") dport = p.sprintf("%TCP.dport%") if not sport.isdigit(): sport = str(getservbyname(sport)) if not dport.isdigit(): dport = str(getservbyname(dport)) return sport, dport
def addr(val, default_port=8000, defualt_host='localhost'): """ Convert a string of format host[:port] into Addr(host, port). >>> addr('0:80') Addr(host='0', port=80) >>> addr('127.0.0.1:80') Addr(host='127.0.0.1', port=80) >>> addr('0.0.0.0', default_port=8000) Addr(host='0.0.0.0', port=8000) """ import re import socket match = re.match(r'\A(?P<host>.*?)(:(?P<port>(\d+|\w+)))?\Z', val) if match is None: raise argparse.ArgumentTypeError( '%r is not a valid host[:port] address.' % val ) host, port = match.group('host', 'port') if not host: host = defualt_host if not port: port = default_port elif port.isdigit(): port = int(port) else: port = socket.getservbyname(port) return Addr(host, port)
def test(): """Test program for tn3270lib. Usage: python tn3270lib.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 = TN3270() tn.set_debuglevel(debuglevel) tn.initiate(host, port) tn.print_screen() tn.disconnect()
def cmd_dispatcher(host,msg,cmd,args): try: if cmd=='GETHOSTBYNAME': msg.result=socket.gethostbyname(args['HOST']) elif cmd=='GETHOSTNAME': msg.result=socket.gethostname() elif cmd=='GETHOSTBYADDR': (msg.result,aliaslist,ipaddrlist) = socket.gethostbyaddr(args['IPADDR']) elif cmd=='GETSERVBYNAME': if args['TCP']: prot='tcp' if args['UDP']: prot='udp' msg.result=`socket.getservbyname(args['SERVICE'],prot)` elif cmd=='CONNECTSOCKET': sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect(args['HOST'],args['PORT']) sockets[sock.fileno()]=sock msg.result=`sock.fileno()` elif cmd=='CLOSESOCKET': fd=args['SOCKET'] sockets[fd].close() del sockets[fd] elif cmd=='READSOCKET': msg.result=sockets[args['SOCKET']].recv(args['LEN']) if not msg.result: msg.rc=ARexx.RC_WARN elif cmd=='WRITESOCKET': msg.result=`sockets[args['SOCKET']].send(args['DATA'])` elif cmd=='WRITESOCKETCR': msg.result=`sockets[args['SOCKET']].send(args['DATA']+'\n')` except socket.error,string: msg.rc=ARexx.RC_ERROR if type(string)==type(''): msg.rc2=string else: msg.rc2=string[1]
def __call__(self, parser, args, value, option_string=None): try: host, port = map(str.strip, value.split(':')) except ValueError as e: parser.error("invalid {} argument '{}': {}".format( self.metavar or self.dest, value, e)) args.__delattr__(self.dest) if host: args.__setattr__(self.dest + '_host', host) if port: try: # as number port = int(port) if not (0 < port <= 65535): parser.error("invalid port number '{}'".format(port)) except ValueError: try: # as well known service name import socket port = socket.getservbyname(port, 'tcp') except socket.error as e: parser.error( "invalid port service name '{}': {}".format( port, e)) args.__setattr__(self.dest + '_port', port)
def main(): argc = len(sys.argv) if argc < 2: print(""" Usage: echo_server port """) sys.exit() #get port porttext = sys.argv[1] try: port = int(porttext) except: try: port = socket.getservbyname(porttext) except socket.gaierror: print('port is illegal!') sys.exit() server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True) server_sock.bind((socket.gethostbyname('localhost'), port)) server_sock.listen(5) print "start server:", server_sock.getsockname() while True: try: (client_sock, client_addr) = server_sock.accept() print "got connection from", client_addr handle(client_sock, client_addr) except KeyboardInterrupt: break
def test(): import sys, string, socket, select 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 = string.atoi(portstr) except string.atoi_error: port = socket.getservbyname(portstr, 'tcp') tn = Telnet(host, port) tn.set_debuglevel(debuglevel) while 1: rfd, wfd, xfd = select.select([tn, sys.stdin], [], []) if sys.stdin in rfd: line = sys.stdin.readline() tn.write(line) if tn in rfd: try: text = tn.read_eager() except EOFError: print '*** Connection closed by remote host ***' break if text: sys.stdout.write(text) sys.stdout.flush() tn.close()
def requestProcessor(self, request): if self.include: request_data = self.SEPARATOR % 'Request' genHdr = [] try: remadd = socket.gethostbyname(request.get_host()) + ':' + str(socket.getservbyname(request.get_type())) except: pass else: genHdr.append(('Remote Address', remadd)) genHdr.append(('Request Url', request.get_full_url())) genHdr.append(('Request Method', request.get_method())) # genHdr.append(('Status Code', str(request.getcode()))) for key, value in genHdr: request_data += '\n' + key + ': ' + str(value) request_data += self.HEAD_SEP request_headers = request.headers for key, value in sorted(request_headers.items()): request_data += '\n' + key + ': ' + str(value) if request.unredirected_hdrs: request_data += self.HEAD_SEP for key, value in request.unredirected_hdrs.items(): request_data += '\n' + key + ': ' + str(value) self.log += request_data if self.origReqMethod and self.origReqMethod not in ['GET', 'POST'] and self.errCode in [301,302,303]: setattr(request, 'get_method', lambda: self.origReqMehod) self.errCode = 0 return request pass
def main(): argc = len(sys.argv) if argc < 3: print(""" Usage : echo_server ipaddr port """) sys.exit() ipaddr = sys.argv[1] porttext = sys.argv[2] #get port try: port = int(porttext) except: try: port = socket.getservbyname(porttext) except socket.gaierror : print('port is illeagl') sys.exit() #get connection try: echo = EchoServer(ipaddr,port,10) echo.run() echo.close() except KeyboardInterrupt: print('server stop')
def find_service_name(): protocolname = 'tcp' try: print ("service name: %s => port: %s" %(app_name, socket.getservbyname(app_name,'tcp'))) except Exception as err: print (err)
def get_disk_xml(params): """ <disk type='file' device='cdrom'> <driver name='qemu' type='raw'/> [source XML according to src_type] <target dev='%(dev)s' bus='%(bus)s'/> <readonly/> </disk> """ path = params['path'] disk_type = params.get('disk', None) if disk_type is None: disk_type = _get_disk_type(path) if len(path) > 0 else 'file' disk = E.disk(type=disk_type, device=params['type']) driver = E.driver(name='qemu', type=params['format']) if params['type'] != 'cdrom': driver.set('cache', 'none') if params.get('pool_type') == "netfs": driver.set("io", "native") disk.append(driver) # Get device name according to bus and index values dev = params.get('dev', (BUS_TO_DEV_MAP[params['bus']] + string.lowercase[params.get('index', 0)])) disk.append(E.target(dev=dev, bus=params['bus'])) if params.get('address'): # ide disk target id is always '0' disk.append(E.address( type='drive', controller=params['address']['controller'], bus=params['address']['bus'], target='0', unit=params['address']['unit'])) if len(params['path']) == 0: return (dev, ET.tostring(disk, encoding='utf-8', pretty_print=True)) if disk_type == 'network': """ <source protocol='%(protocol)s' name='%(url_path)s'> <host name='%(hostname)s' port='%(port)s'/> </source> """ output = urlparse.urlparse(params['path']) port = str(output.port or socket.getservbyname(output.scheme)) source = E.source(protocol=output.scheme, name=output.path) source.append(E.host(name=output.hostname, port=port)) else: """ <source file='%(src)s' /> """ source = E.source() source.set(DEV_TYPE_SRC_ATTR_MAP[disk_type], params['path']) disk.append(source) return (dev, ET.tostring(disk, encoding='utf-8', pretty_print=True))
def getIp(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = socket.getservbyname('http', 'tcp') s.connect(('www.baidu.com', port)) ip = s.getsockname()[0] s.close() return ip
def main(): conf = [['echo','tcp', '', EchoHandler], \ ['daytime','tcp', '', DaytimeHandler], \ ['chargen','tcp', '', ChargenHandler], \ ['echo', 'udp', '', UDPEchoHandler] ] if (len(sys.argv) >= 2): conf[0][0] = int(sys.argv[1]) if (len(sys.argv) >= 3): conf[1][0] = int(sys.argv[2]) if (len(sys.argv) >= 4): conf[2][0] = int(sys.argv[3]) if (len(sys.argv) >= 5): conf[3][0] = int(sys.argv[4]) for serv in conf: service = serv[3] try: # resolve by service name first port = socket.getservbyname(serv[0]) except: # if not resolvable by name then assume that it is a port number port = int(serv[0]) if serv[1] == 'tcp': TCPServer(('localhost',port),service) else: UDPServer(('localhost',port),service) try: asyncore.loop() except KeyboardInterrupt: sys.exit(1)
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 = [] while 1: (ttype, value) = tok.get() if ttype == dnspython.tokenizer.EOL or ttype == dnspython.tokenizer.EOF: break if value.isdigit(): serv = int(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(value, protocol_text) i = serv // 8 l = len(bitmap) if l < i + 1: for j in xrange(l, i + 1): bitmap.append('\x00') bitmap[i] = chr(ord(bitmap[i]) | (0x80 >> (serv % 8))) bitmap = dnspython.rdata._truncate_bitmap(bitmap) return cls(rdclass, rdtype, address, protocol, bitmap)
def turtle_client(self): s = socket.socket() HOST = socket.gethostbyname("measerver") PORT = socket.getservbyname("mea_srv") print HOST print PORT #invoco el metodo connect del socket pasando como parametro la tupla IP , puerto s.connect((HOST, PORT)) print "Turtle_com------->conectado a servidor." message = str(self.img_mea) print "Turtle_com----------->enviando mensaje a servidor:" print message s.send(message) print "Turtle_com---------->esperando respuesta del servidor:" recibido = s.recv(1024) print "Turtle_com---------->recibido: " print recibido #cierro socket s.close() self.pub_Cult.publish(recibido) return True
def makeConnection(transport): nstHost = host try: try: transport.connect(host, port) except ValueError: # Avoid ImportError: cannot import name dns from untwisted import dns nstHost = (yield dns.lookup(host)).answer[0].address transport.connect(nstHost, port) # tcp.Connector calls socket.getservbyname() but .connect() doesn't : ( except TypeError: nstPort = socket.getservbyname(port, 'udp') # Avoid RuntimeError: already connected transport._connectedAddr = None transport.connect(nstHost, nstPort) raise StopIteration(transport)
def passiveUDP(host, service, qlen=0, portbase=0): ''' create and bind a UDP server socket parametrs: host: network interface the service to be bound service: name (string) or port number (short) of service qlen: queue length portbase: a workaround for some privilege services, eg, echo, a portbase of 7000 will shift echo service to port 7007 (7000+7) (host, service) defines the server address each call reuses the specified port number ''' serv_name = str(service) if '0' <= serv_name[:1] <= '9': # port # in integer port = int(serv_name) else: # resolve by service name try: port = socket.getservbyname(serv_name, 'udp') except: # something wrong with port # sys.exit('Format error in port number!\n') port += portbase msock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) msock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) msock.bind((host, port)) return msock
def getSocket(host, textport): client_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: port = int(textport) except ValueError: port = socket.getservbyname(textport, 'udp') client_sock.connect((host, port))
def _getsockname(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = socket.getservbyname("http", "tcp") s.connect(("www.google.com", port)) sockname = s.getsockname() s.close() return sockname
def _parse_port_range(port_range, protocol): # Try for an integer try: return (int(port_range), int(port_range)) except ValueError: pass # Try for an integer range if port_range.count('-') == 1: ports = port_range.split('-') try: return (int(ports[0]), int(ports[1])) except ValueError: pass # Try for a service name if isinstance(protocol, six.string_types): try: # This is going to fail if protocol is a number. port = socket.getservbyname(port_range, protocol) return (port, port) except socket.error: pass # That's all, folks! raise ArgumentError("argument -p/--port-range: '{0}' is neither a port " "number, range of port numbers, nor a recognized " "service name".format(port_range))
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 range(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)
def __init__(self, host, port, factory, timeout, bindAddress, reactor=None): self.host = host if isinstance(port, types.StringTypes): try: port = socket.getservbyname(port, 'tcp') except socket.error, e: raise error.ServiceNameUnknownError(string="%s (%r)" % (e, port))
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()
def buildOptions(self, parser): """ Command-line options to be supported """ SMTP_PORT = 25 try: SMTP_PORT = socket.getservbyname('smtp', 'tcp') except socket.error: pass parser.add_option('--useFileDescriptor', dest='useFileDescriptor', default=-1, type="int", help="File descriptor to use for listening") parser.add_option('--listenPort', dest='listenPort', default=SMTP_PORT, type="int", help="Alternative listen port to use (default %default)") parser.add_option('--eventseverity', dest='eventseverity', default="2", type="int", help="Severity for events created") parser.add_option('--listenip', dest='listenip', default='0.0.0.0', help='IP address to listen on. Default is 0.0.0.0')
def main(): server = pbs.pbs_default() c = pbs.pbs_connect(server) nodes = pbs.pbs_statnode(c, '', 'NULL', 'NULL') for node in nodes: print node.name, ' :' attrs = node.attribs for attr in attrs: print '\t%s = %s' %(attr.name, attr.value) try: mom_port = socket.getservbyname('pbs_resmon', 'tcp') except socket.error: mom_port = pbs.PBS_MANAGER_SERVICE_PORT mom_id = pbs.openrm(node.name, mom_port) mom_keys = pbs.get_mom_values(mom_id) for key in mom_keys.keys(): print '\t%s = %s' %(key, mom_keys[key]) print '\nTesting list with user supplied keywords' l = [ 'bas', 'ncpus', 'loadave' ] mom_keys = pbs.get_mom_values(mom_id, l) for key in mom_keys.keys(): print '\t%s = %s' %(key, mom_keys[key]) print '' pbs.closerm(mom_id)
def create_new_vm(vmdef): image = cache.get_image(name=vmdef['image']) image = copy.deepcopy(image) vm = ravello.update_luids(image) vm['name'] = vmdef['name'] vm['customVmConfigurationData'] = { 'keypair': env.public_key } vm['hostname'] = [ vmdef['name'] ] vm['numCpus'] = vmdef['smp'] vm['memorySize'] = { 'unit': 'MB', 'value': vmdef['memory'] } vm.setdefault('suppliedServices', []) for svcdef in vmdef.get('services', []): if isinstance(svcdef, int): port = str(svcdef) svcdef = 'port-{0}'.format(svcdef) else: port = socket.getservbyname(svcdef) svc = { 'globalService': True, 'id': ravello.random_luid(), 'ip': None, 'name': svcdef, 'portRange': port, 'protocol': 'ANY_OVER_TCP' } vm['suppliedServices'].append({'baseService': svc}) # Set a fixed Mac. This way applications created from blueprints # created from these VMs will have the same Mac. # See also https://github.com/ravello/testmill/issues/15 conn = vm['networkConnections'][0] conn['device']['mac'] = get_new_mac() conn['device']['useAutomaticMac'] = False return vm
def _get_storage_xml(params, ignore_source=False): src_type = params.get('src_type') disk = E.disk(type=src_type, device=params.get('type')) disk.append(E.driver(name='qemu', type=params['format'])) disk.append(E.target(dev=params.get('dev'), bus=params['bus'])) if params.get('address'): # ide disk target id is always '0' disk.append(E.address( type='drive', controller=params['address']['controller'], bus=params['address']['bus'], target='0', unit=params['address']['unit'])) if ignore_source: return ET.tostring(disk) # Working with url paths if src_type == 'network': output = urlparse.urlparse(params.get('path')) host = E.host(name=output.hostname, port= output.port or socket.getservbyname(output.scheme)) source = E.source(protocol=output.scheme, name=output.path) source.append(host) disk.append(source) else: # Fixing source attribute source = E.source() source.set(DEV_TYPE_SRC_ATTR_MAP[src_type], params.get('path')) disk.append(source) return ET.tostring(disk)
def __init__(self, data, panda): self.data = data self.panda = panda service = data[7].split("[") #self.blinks = {} print service[0] try: port = socket.getservbyname(service[0]) print port except: port = "" if service[0] == "init": col1 = self.panda.single_node.main_node.colorScaleInterval(1, (1, 1, 0, 0.7), (0.4, 0.2, 0.7, 0.4)) col2 = self.panda.single_node.main_node.colorScaleInterval(1, (0.4, 0.2, 0.7, 0.4), (1, 1, 0, 0.7)) col3 = self.panda.single_node.main_node.colorScaleInterval(5, (0.4, 0.2, 0.7, 0.4), (0.4, 0.2, 0.7, 0.4)) blink = Sequence(col1, col2, col3, name="blink") #blink.loop() for i in self.panda.single_node.services: print ":" + str(i[0]) + ":" + str(port) + ":" if str(i[0]) == str(port): print "match" self.panda.single_node.apps[i].setColorOff() col1 = self.panda.single_node.apps[i].colorScaleInterval(1, (1, 1, 0, 1), (1, 0.4, 0.7, 1.0)) col2 = self.panda.single_node.apps[i].colorScaleInterval(1, (1, 0.4, 0.7, 1.0), (1, 1, 0, 1)) col3 = self.panda.single_node.apps[i].colorScaleInterval(2, (random.uniform(1,3), 0.4, 0.7, 1.0), (1, 0.4, 0.7, 1.0)) blink = Sequence(col1, col2, col3, name="blink") #self.blinks[port].loop() #looper = Parallel(name="looper") try: self.panda.single_node.looper.append(blink) except: pass self.panda.single_node.looper.loop()
def handle_data(self, data): if self.queried_ip is "": matches = re.findall("(\d+\.\d+\.\d+\.\d+)", data) if len(matches) > 0: self.queried_ip = matches[0] if data.__contains__("Active TCP/UDP Sessions"): self.in_session = 1 if data.__contains__("The color of the host"): self.sessions.append("NumSessions:%d" % int(self.session_num)) self.in_session = 0 source_sessions = 0 dest_sessions = 0 for sess in self.sessions: src_str = "^%s:.*" % self.queried_ip dst_str = "^\d+\.\d+\.\d+\.\d+:\S+\s+-->\s+%s:.*" % self.queried_ip src_sess = "^%s:\S+\s+-->\s+(\d+\.\d+\.\d+\.\d+):(\S+)" % self.queried_ip dst_sess = "^(\d+\.\d+\.\d+\.\d+):\S+\s+-->\s+%s:(\S+)" % self.queried_ip if re.findall(src_str, sess): source_sessions += 1 if re.findall(dst_str, sess): dest_sessions += 1 matches = re.findall(src_sess, sess) if len(matches) > 0: if matches[0][1] in self.src_port_group: self.src_port_group[matches[0][1]].add(matches[0][0]) else: self.src_port_group[matches[0][1]] = Set() self.src_port_group[matches[0][1]].add(matches[0][0]) matches = re.findall(dst_sess, sess) if len(matches) > 0: if matches[0][1] in self.dst_port_group: self.dst_port_group[matches[0][1]].add(matches[0][0]) else: self.dst_port_group[matches[0][1]] = Set() self.dst_port_group[matches[0][1]].add(matches[0][0]) self.sessions.append("SessionsAsSource:%s" % source_sessions) self.sessions.append("SessionsAsDest:%s" % dest_sessions) for port in self.src_port_group: self.sessions.append("UniqPort%sAsSourceSessions:%d" % (port, len(self.src_port_group[port]))) for port in self.dst_port_group: self.sessions.append("UniqPort%sAsDestSessions:%d" % (port, len(self.dst_port_group[port]))) if self.inside_table_element and self.in_session: if self.td_count <= 2: matches = re.findall(":(\w+)", data) if len(matches) > 0: try: port = socket.getservbyname(matches[0]) except: port = matches[0] if self.td_count is 1: self.source_port = port elif self.td_count is 2: self.dest_port = port elif self.td_count is 3: if self.seen == 0: self.data_sent = float(data) self.seen = 1 else: if data.__contains__("KB"): self.data_sent *= 1024 elif data.__contains__("MB"): self.data_sent *= 1024 * 1024 elif data.__contains__("GB"): self.data_sent *= 1024 * 1024 * 1024 self.seen = 0 elif self.td_count is 4: if self.seen == 0: self.data_rcvd = float(data) self.seen = 1 else: if data.__contains__("KB"): self.data_rcvd *= 1024 elif data.__contains__("MB"): self.data_rcvd *= 1024 * 1024 elif data.__contains__("GB"): self.data_rcvd *= 1024 * 1024 * 1024 self.seen = 0 elif self.td_count is 5: self.active_since = data elif self.td_count is 6: self.last_seen = data elif self.td_count is 7: self.duration = self.tosecs(data) elif self.td_count is 8: self.inactive = self.tosecs(data)
hname, aliases, ipaddrs = socket.gethostbyaddr(ip) all_host_names = [hname] + aliases if verbose: print hostname print ip print hname, aliases, ipaddrs print all_host_names for name in all_host_names: if string.find(name, '.'): break else: print 'FQDN not found' print socket.getservbyname('telnet', 'tcp') try: socket.getservbyname('telnet', 'udp') except socket.error: pass canfork = hasattr(os, 'fork') try: PORT = 50007 if not canfork or os.fork(): # parent is server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(hostname, PORT) s.listen(1) if verbose: print 'parent accepting'
def get_disk_xml(params): """ <disk type='file' device='cdrom'> <driver name='qemu' type='raw'/> [source XML according to src_type] <target dev='%(dev)s' bus='%(bus)s'/> <readonly/> </disk> """ path = params['path'] disk_type = params.get('disk', None) if disk_type is None: disk_type = _get_disk_type(path) if len(path) > 0 else 'file' disk = E.disk(type=disk_type, device=params['type']) driver = E.driver(name='qemu', type=params['format']) try: fd = os.open(path, os.O_RDONLY | os.O_DIRECT) os.close(fd) wok_log.debug("Disk '%s' supports direct I/O. Setting cache=none" 'to enable live migration' % path) except OSError as e: if e.errno == errno.EINVAL: wok_log.debug("Disk '%s' does not support direct I/O: " "'%s'. Let libvirt sets the default cache mode." % (path, e)) else: if params['type'] != 'cdrom': driver.set('cache', 'none') if params.get('pool_type') == 'netfs': driver.set('io', 'native') disk.append(driver) # Get device name according to bus and index values dev = params.get( 'dev', (BUS_TO_DEV_MAP[params['bus']] + string.ascii_lowercase[params.get('index', 0)]), ) disk.append(E.target(dev=dev, bus=params['bus'])) if params.get('address'): # ide disk target id is always '0' disk.append( E.address( type='drive', controller=params['address']['controller'], bus=params['address']['bus'], target='0', unit=params['address']['unit'], )) if len(params['path']) == 0: return dev, ET.tostring(disk, encoding='unicode', pretty_print=True) if disk_type == 'network': """ <source protocol='%(protocol)s' name='%(url_path)s'> <host name='%(hostname)s' port='%(port)s'/> </source> """ output = urllib.parse.urlparse(params['path']) port = str(output.port or socket.getservbyname(output.scheme)) source = E.source(protocol=output.scheme, name=output.path) source.append(E.host(name=output.hostname, port=port)) else: """ <source file='%(src)s' /> """ source = E.source() source.set(DEV_TYPE_SRC_ATTR_MAP[disk_type], params['path']) disk.append(source) return dev, ET.tostring(disk, encoding='unicode', pretty_print=True)
def CreateParser(self, *args, **kwargs): parser = optparse.OptionParser(*args, **kwargs) # Selection group group = optparse.OptionGroup(parser, 'Which browser to use') group.add_option('--browser', dest='browser_type', default=None, help='Browser type to run, ' 'in order of priority. Supported values: list,%s' % ','.join(browser_finder.FindAllBrowserTypes(self))) group.add_option('--browser-executable', dest='browser_executable', help='The exact browser to run.') group.add_option('--chrome-root', dest='chrome_root', help='Where to look for chrome builds. ' 'Defaults to searching parent dirs by default.') group.add_option( '--chromium-output-directory', dest='chromium_output_dir', help='Where to look for build artifacts. ' 'Can also be specified by setting environment variable ' 'CHROMIUM_OUTPUT_DIR.') group.add_option( '--remote', dest='cros_remote', help='The hostname of a remote ChromeOS device to use.') group.add_option( '--remote-ssh-port', type=int, default=socket.getservbyname('ssh'), dest='cros_remote_ssh_port', help= 'The SSH port of the remote ChromeOS device (requires --remote).') identity = None testing_rsa = os.path.join(util.GetTelemetryThirdPartyDir(), 'chromite', 'ssh_keys', 'testing_rsa') if os.path.exists(testing_rsa): identity = testing_rsa group.add_option( '--identity', dest='cros_ssh_identity', default=identity, help= 'The identity file to use when ssh\'ing into the ChromeOS device') parser.add_option_group(group) # Debugging options group = optparse.OptionGroup(parser, 'When things go wrong') profiler_choices = profiler_finder.GetAllAvailableProfilers() group.add_option( '--profiler', default=None, type='choice', choices=profiler_choices, help='Record profiling data using this tool. Supported values: %s. ' '(Notice: this flag cannot be used for Timeline Based Measurement ' 'benchmarks.)' % ', '.join(profiler_choices)) group.add_option('-v', '--verbose', action='count', dest='verbosity', help='Increase verbosity level (repeat as needed)') group.add_option('--print-bootstrap-deps', action='store_true', help='Output bootstrap deps list.') group.add_option( '--extra-chrome-categories', dest='extra_chrome_categories', type=str, help= 'Filter string to enable additional chrome tracing categories. See' ' documentation here: https://cs.chromium.org/chromium/src/base/' 'trace_event/trace_config.h?rcl=' 'c8db6c6371ca047c24d41f3972d5819bc83d83ae&l=125') group.add_option( '--extra-atrace-categories', dest='extra_atrace_categories', type=str, help='Comma-separated list of extra atrace categories. Use atrace' ' --list_categories to get full list.') group.add_option( '--enable-systrace', dest='enable_systrace', action='store_true', help='Enable collection of systrace. (Useful on ChromeOS where' ' atrace is not supported; collects scheduling information.)') parser.add_option_group(group) # Platform options group = optparse.OptionGroup(parser, 'Platform options') group.add_option( '--no-performance-mode', action='store_true', help='Some platforms run on "full performance mode" where the ' 'test is executed at maximum CPU speed in order to minimize noise ' '(specially important for dashboards / continuous builds). ' 'This option prevents Telemetry from tweaking such platform settings.' ) group.add_option( '--webview-embedder-apk', help= 'When running tests on android webview, more than one apk needs to' ' be installed. The apk running the test is said to embed webview.' ) parser.add_option_group(group) # Remote platform options group = optparse.OptionGroup(parser, 'Remote platform options') group.add_option('--android-blacklist-file', help='Device blacklist JSON file.') group.add_option( '--device', help='The device ID to use. ' 'If not specified, only 0 or 1 connected devices are supported. ' 'If specified as "android", all available Android devices are ' 'used.') parser.add_option_group(group) # Browser options. self.browser_options.AddCommandLineArgs(parser) real_parse = parser.parse_args def ParseArgs(args=None): defaults = parser.get_default_values() for k, v in defaults.__dict__.items(): if k in self.__dict__ and self.__dict__[k] != None: continue self.__dict__[k] = v ret = real_parse(args, self) # pylint: disable=E1121 if self.verbosity >= 2: global_hooks.InstallSpyOnPopenArgs() logging.getLogger().setLevel(logging.DEBUG) elif self.verbosity: logging.getLogger().setLevel(logging.INFO) else: logging.getLogger().setLevel(logging.WARNING) if self.chromium_output_dir: os.environ['CHROMIUM_OUTPUT_DIR'] = self.chromium_output_dir # Parse remote platform options. self.BuildRemotePlatformOptions() if self.remote_platform_options.device == 'list': if binary_manager.NeedsInit(): binary_manager.InitDependencyManager([]) devices = device_finder.GetDevicesMatchingOptions(self) print 'Available devices:' for device in devices: print ' ', device.name sys.exit(0) if self.browser_executable and not self.browser_type: self.browser_type = 'exact' if self.browser_type == 'list': if binary_manager.NeedsInit(): binary_manager.InitDependencyManager([]) devices = device_finder.GetDevicesMatchingOptions(self) if not devices: sys.exit(0) browser_types = {} for device in devices: try: possible_browsers = browser_finder.GetAllAvailableBrowsers( self, device) browser_types[device.name] = sorted([ browser.browser_type for browser in possible_browsers ]) except browser_finder_exceptions.BrowserFinderException as ex: print >> sys.stderr, 'ERROR: ', ex sys.exit(1) print 'Available browsers:' if len(browser_types) == 0: print ' No devices were found.' for device_name in sorted(browser_types.keys()): print ' ', device_name for browser_type in browser_types[device_name]: print ' ', browser_type if len(browser_types[device_name]) == 0: print ' No browsers found for this device' sys.exit(0) # Parse browser options. self.browser_options.UpdateFromParseResults(self) return ret parser.parse_args = ParseArgs return parser
def http_handle(socket_con, address): # Save the request received from the connection and decode as ascii data_str = socket_con.recv(1024) # enforce adding extra line breaks at the end the request in case the user didn't add them # without this a "functional" request would receive no answer from the server if (data_str[-5:] != b'\r\n\r\n\r\n'): data_str += b'\r\n\r\n' # turn the data into a usable string request = data_str.decode('ascii').rstrip() print("\n\nReceived request") print("======================") print(request.rstrip()) print("======================") reply = b'' # First Step: Handle Method req_lines = request.split('\n') # first line is our initial request line header_line = req_lines[0].split(' ') path = header_line[1] if path[0:7] == "http://": path = path[7:] if (path.find('/') != -1): url = path[:path.find('/')] else: url = path else: if (path.find('/') != -1): url = path[:path.find('/')] else: url = path port = 80 # default port 80 print("Creating a new socket...") req_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) req_socket.settimeout(20) try: print("Trying To Connect To: " + url) try: port = socket.getservbyname(url, 'tcp') except: port = 80 # connect our socket to the url given req_socket.connect((url, port)) print("Connected.") print("Sending Request") req_socket.sendall(data_str) print("Sent: ") print(data_str) print("Receiving Reply...") while True: buffer = req_socket.recv(1024) if not buffer: break reply += buffer except (socket.gaierror): reply = "404 Not Found." reply = reply.encode('ascii') except (socket.timeout): print("Connection Timeout") # if the connection times out and the reply is empty inform the client if reply.decode('ascii') == "": temp = "Connection Timeout Nothing Received." reply = temp.encode('ascii') # Use the connection socket to send the reply encoded as bytestream print("\n\nReplied with") print("======================") print(reply) socket_con.sendall(reply) print("======================") req_socket.close() socket_con.close()
import socket hostname = socket.gethostname() address = socket.gethostbyname(hostname) # 通过地址获取主机网络信息 host_byaddr = socket.gethostbyaddr('127.0.0.1') # (主机名, 别名, 网络地址) b = socket.inet_aton('192.168.1.2') ip = socket.inet_ntoa(b'\xc0\xa8\x01\x02') # 获取一个应用的端口号 port = socket.getservbyname('http') print(hostname) print(address) print(host_byaddr) print(b) print(ip) print(port)
def _getaddrinfo(host=None, service=None, family=socket.AF_UNSPEC, socktype=0, proto=0, flags=0): if flags & (socket.AI_ADDRCONFIG | socket.AI_V4MAPPED) != 0: raise NotImplementedError if host is None and service is None: raise socket.gaierror(socket.EAI_NONAME) v6addrs = [] v4addrs = [] canonical_name = None try: # Is host None or a V6 address literal? if host is None: canonical_name = 'localhost' if flags & socket.AI_PASSIVE != 0: v6addrs.append('::') v4addrs.append('0.0.0.0') else: v6addrs.append('::1') v4addrs.append('127.0.0.1') else: parts = host.split('%') if len(parts) == 2: ahost = parts[0] else: ahost = host addr = dns.ipv6.inet_aton(ahost) v6addrs.append(host) canonical_name = host except: try: # Is it a V4 address literal? addr = dns.ipv4.inet_aton(host) v4addrs.append(host) canonical_name = host except: if flags & socket.AI_NUMERICHOST == 0: try: qname = None if family == socket.AF_INET6 or family == socket.AF_UNSPEC: v6 = _resolver.query(host, dns.rdatatype.AAAA, raise_on_no_answer=False) # Note that setting host ensures we query the same name # for A as we did for AAAA. host = v6.qname canonical_name = v6.canonical_name.to_text(True) if v6.rrset is not None: for rdata in v6.rrset: v6addrs.append(rdata.address) if family == socket.AF_INET or family == socket.AF_UNSPEC: v4 = _resolver.query(host, dns.rdatatype.A, raise_on_no_answer=False) host = v4.qname canonical_name = v4.canonical_name.to_text(True) if v4.rrset is not None: for rdata in v4.rrset: v4addrs.append(rdata.address) except dns.resolver.NXDOMAIN: raise socket.gaierror(socket.EAI_NONAME) except: raise socket.gaierror(socket.EAI_SYSTEM) port = None try: # Is it a port literal? if service is None: port = 0 else: port = int(service) except: if flags & socket.AI_NUMERICSERV == 0: try: port = socket.getservbyname(service) except: pass if port is None: raise socket.gaierror(socket.EAI_NONAME) tuples = [] if socktype == 0: socktypes = [socket.SOCK_DGRAM, socket.SOCK_STREAM] else: socktypes = [socktype] if flags & socket.AI_CANONNAME != 0: cname = canonical_name else: cname = '' if family == socket.AF_INET6 or family == socket.AF_UNSPEC: for addr in v6addrs: for socktype in socktypes: for proto in _protocols_for_socktype[socktype]: tuples.append((socket.AF_INET6, socktype, proto, cname, (addr, port, 0, 0))) if family == socket.AF_INET or family == socket.AF_UNSPEC: for addr in v4addrs: for socktype in socktypes: for proto in _protocols_for_socktype[socktype]: tuples.append( (socket.AF_INET, socktype, proto, cname, (addr, port))) if len(tuples) == 0: raise socket.gaierror(socket.EAI_NONAME) return tuples
print data if data == "": break except socket.timeout: print "connection timeout. please check your data" finally: s.close() host = sys.argv[1] textport = sys.argv[2] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: port = int(textport) except ValueError: port = socket.getservbyname(textport, "udp") s.connect((host, port)) print "entrez les donnees a transmettre" data = sys.stdin.readline().strip() s.sendall(data) print "attente de reponse, Ctrl-C pour arreter" while 1: buf = s.recv(2048) if not len(buf): break print buf host = "ftp.ibiblio.org" port = 21
#%% #%% print('-' * 30) web_site = 'www.crappytaxidermy.com' hostbyname = socket.gethostbyname_ex(web_site) print('web_site:', web_site, '\nhostbyname:', hostbyname) #%% #%% print('-' * 30) web_site = 'www.crappytaxidermy.com' port_num = 80 addrinfo = socket.getaddrinfo(web_site, port_num) print('web_site:', web_site, '\naddrinfo:', addrinfo) #%% #%% print('-' * 30) server = 'http' port_num = socket.getservbyname(server) print('server:', server, '\nport_num:', port_num) #%% #%% print('-' * 30) port_num = 80 server = socket.getservbyport(port_num) print('port_num:', port_num, '\nserver:', server) #%%
from socket import socket, getservbyname from socket import AF_INET, SOCK_DGRAM from socket import SOL_SOCKET, SO_REUSEADDR import time import struct import traceback import sys host = "" textport = 12345 # 步骤一 s = socket(AF_INET, SOCK_DGRAM) #设定通信类型和 # 步骤二 try: port = int(textport) except ValueError: port = getservbyname(textport, 'udp') s.connect((host, port)) #print("输入要发送的日期") #data = sys.stdin.readline().strip() data = raw_input("输入要发送的日期").strip() s.sendall(data) print("等待回复,按CTRL-C或者CTRl-BREAK结束") buf = s.recvfrom(2048)[0] if len(buf) != 4: print("错误的长度{a}:{b}".format(a=len(buf), b=buf)) sys.exit(1) print time.ctime(int(struct.unpack("!I", buf)[0] - 2208988800))
filename = sys.argv[3] try: print "Creating socket....", s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print "Strange error creating sock:%s" % e sys.exit(1) print "done" try: port = int(textport) except ValueError: try: print "Looking up port number...", port = socket.getservbyname("http", "tcp") except socket.error, e: print "Couldn't find your port:%s" % e sys.exit(1) print "done" try: print "Connecting to remote host on port %d" % port, s.connect(("www.baidu.com", port)) except socket.gaierror, e: print "Address-related error connect to server:%s" % e sys.exit(1) print "done" print "Connected from", s.getsockname() print "Connected to", s.getpeername()
#!/usr/bin/env python #--*-- coding:UTF-8 --*-- import socket, sys host = sys.argv[1] textport = sys.argv[2] archivo = sys.argv[3] try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print "error en la creación del socket: %s" % e sys.exit(1) try: port = int(textport) except ValueError: try: port = socket.getservbyname(host, 'tcp') except socket.error, e: print "no se encuentra el puerto %s" % e sys.exit(1) try: s.connect((host, port)) except socket.gaierror, e: print "error de dirección de conexión al servidor:%s" % e sys.exit(1) except socket.error, e: print "error de conexión: %s" % e sys.exit(1) try: s.sendall("GET %s HTTP/1.0\r\n\r\n" % archivo) except socket.error, e: print "error de envío de datos: %s " % e
import sys host = sys.argv[1] textport = sys.argv[2] try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except socket.error, e: print "Strange error creating socket: %s" % e sys.exit(1) try: port = int(textport) except ValueError: try: port = socket.getservbyname(textport, 'udp') except socket.error, e: print "Couldn't find your port: %s" % e sys.exit(1) s.connect((host, port)) # 可以忽略 print "Enter data to transmit: " data = sys.stdin.readline().strip() s.sendall(data) print "Looking for replies; press CTRl-C or CTRL-Break to stop." while True: buf = s.recv(2048) # 可能永远收不到数据,会阻塞;但tcp也会阻塞啊? if not len(buf): break sys.stdout.write(buf)
# Finding Service Information import urlparse for url in [ 'http://www.python.org', 'https://www.mybank.com', 'ftp://prep.ai.mit.edu', 'gopher://gopher.micro.umn.edu', 'smtp://mail.example.com', 'imap://mail.example.com', 'imaps://mail.example.com', 'pop3://pop.example.com', 'pop3s://pop.example.com', ]: parsed_url = urlparse.urlparse(url) port = socket.getservbyname(parsed_url.scheme) print '%6s : %s' % (parsed_url.scheme, port) for port in [80, 443, 21, 70, 25, 143, 993, 110, 995]: print urlparse.urlunparse( (socket.getservbyport(port), 'example.com', '/', '', '', '')) """ http : 80 https : 443 ftp : 21 gopher : 70 smtp : 25 imap : 143 imaps : 993 pop3 : 110 pop3s : 995
def _parse_acl_with_textfsm(self, parser_file, output): import textfsm tmp = open(parser_file) re_table = textfsm.TextFSM(tmp) results = re_table.ParseText(output) fsm_results = [] for item in results: facts = {} facts.update(dict(zip(re_table.header, item))) fsm_results.append(facts) pd = [] parsed_acl = [] # Convert dictionary of terms into flows dictionary for term in fsm_results: pd_it = {} original_terms = {} for k, v in term.items(): if k == 'LINE_NUM' and v == '': # Empty line with just name continue elif k == 'LINE_NUM' and v != '': pd_it["service_line_index"] = v original_terms["service_line_index"] = v if k == 'PROTOCOL' and v != '': pd_it["proto"] = v original_terms['proto'] = v if k == 'ACTION' and v != '': pd_it["action"] = v original_terms['action'] = v if k == 'SRC_NETWORK' and v != '': if 'SRC_WILDCARD' in term: src_mask = term['SRC_WILDCARD'] src_invert_mask = sum([bin(255 - int(x)).count("1") for x in src_mask.split(".")]) else: src_invert_mask = '32' cidr = "%s/%s" % (v, src_invert_mask) src_ip = netaddr.IPNetwork(cidr) size_subnet = src_ip.size host_index = int(size_subnet / 2) pd_it['src'] = str(src_ip[host_index]) original_terms['src'] = src_ip if k == 'SRC_ANY' and v != '': pd_it['src'] = "any" original_terms['src'] = netaddr.IPNetwork('0.0.0.0/0') if k == 'SRC_HOST' and v != '': pd_it['src'] = v original_terms['src'] = v if k == 'SRC_PORT' and v != '': if not v[0].isdigit(): v = str(socket.getservbyname(v)) pd_it['src_port'] = v original_terms['src_port'] = v if k == 'DST_NETWORK' and v != '': if 'DST_WILDCARD' in term: dst_mask = term['DST_WILDCARD'] dst_invert_mask = sum([bin(255 - int(x)).count("1") for x in dst_mask.split(".")]) else: dst_invert_mask = '32' d_cidr = "%s/%s" % (v, dst_invert_mask) dst_ip = netaddr.IPNetwork(d_cidr) d_size_subnet = dst_ip.size d_host_index = int(d_size_subnet / 2) pd_it['dst'] = str(dst_ip[d_host_index]) original_terms['dst'] = dst_ip if k == 'DST_ANY' and v != '': pd_it['dst'] = "any" original_terms['dst'] = netaddr.IPNetwork('0.0.0.0/0') if k == 'DST_HOST' and v != '': pd_it['dst'] = v original_terms['dst'] = v if k == 'DST_PORT' and v != '': if not v[0].isdigit(): v = str(socket.getservbyname(v)) pd_it['dst_port'] = v original_terms['dst_port'] = v if pd_it: pd.append(pd_it) if original_terms: parsed_acl.append(original_terms) # Store parsed acl on this object for later processing self._parsed_acl = parsed_acl return json.dumps(pd, indent=4)
def parse_url(url): """ Parses a URL like, 'ssh://user@host:22' and returns a dict of:: { 'scheme': scheme, 'user': user, 'host': host, 'port': port, 'password': password, 'identities': identities, 'debug': debug } .. note:: 'web+ssh://' URLs are also supported. If an ssh URL is given without a username, os.environ['GO_USER'] will be used and if that doesn't exist it will fall back to os.environ['USER']. SSH Identities may be specified as a query string: ssh://user@host:22/?identities=id_rsa,id_ecdsa .. note:: *password* and *identities* may be returned as None and [], respectively if not provided. """ identities = set() debug = False import socket try: from urlparse import urlparse, parse_qs, uses_query if 'ssh' not in uses_query: # Only necessary in Python 2.X uses_query.append('ssh') except ImportError: # Python 3 from urllib.parse import urlparse, parse_qs parsed = urlparse(url) if parsed.query: q_attrs = parse_qs(parsed.query) for ident in q_attrs.get('identities', identities): identities.update(ident.split(',')) debug = q_attrs.get('debug', False) if debug: # Passing anything turns on debug debug = True if parsed.port: port = parsed.port else: port = socket.getservbyname(parsed.scheme, 'tcp') # Commented these out so that users can enter an arbitrary username. It is # more user-friendly this way since users won't have to have multiple # bookmarks to the same host just to connect with different usernames. #elif os.environ.get('GO_USER'): #username = os.environ['GO_USER'] #elif os.environ.get('USER'): #username = os.environ['USER'] #return (o.scheme, username, o.hostname, port, o.password, identities) return { 'scheme': parsed.scheme, 'user': parsed.username, 'host': parsed.hostname, 'port': port, 'password': parsed.password, 'identities': identities, 'debug': debug }
def CreateParser(self, *args, **kwargs): parser = optparse.OptionParser(*args, **kwargs) # Selection group group = optparse.OptionGroup(parser, 'Which browser to use') group.add_option('--browser', dest='browser_type', default=None, help='Browser type to run, ' 'in order of priority. Supported values: list,%s' % ','.join(browser_finder.FindAllBrowserTypes(self))) group.add_option('--browser-executable', dest='browser_executable', help='The exact browser to run.') group.add_option('--chrome-root', dest='chrome_root', help='Where to look for chrome builds. ' 'Defaults to searching parent dirs by default.') group.add_option( '--chromium-output-directory', dest='chromium_output_dir', help='Where to look for build artifacts. ' 'Can also be specified by setting environment variable ' 'CHROMIUM_OUTPUT_DIR.') group.add_option( '--remote', dest='cros_remote', help='The hostname of a remote ChromeOS device to use.') group.add_option( '--remote-ssh-port', type=int, default=socket.getservbyname('ssh'), dest='cros_remote_ssh_port', help= 'The SSH port of the remote ChromeOS device (requires --remote).') parser.add_option( '--compatibility-mode', action='append', dest='compatibility_mode', choices=[ compact_mode_options.NO_FIELD_TRIALS, compact_mode_options.IGNORE_CERTIFICATE_ERROR, compact_mode_options.LEGACY_COMMAND_LINE_PATH, compact_mode_options.GPU_BENCHMARKING_FALLBACKS ], default=[], help='Select the compatibility change that you want to enforce when ' 'running benchmarks') identity = None testing_rsa = os.path.join(util.GetTelemetryThirdPartyDir(), 'chromite', 'ssh_keys', 'testing_rsa') if os.path.exists(testing_rsa): identity = testing_rsa group.add_option( '--identity', dest='cros_ssh_identity', default=identity, help= 'The identity file to use when ssh\'ing into the ChromeOS device') parser.add_option_group(group) # Debugging options group = optparse.OptionGroup(parser, 'When things go wrong') group.add_option('-v', '--verbose', action='count', dest='verbosity', help='Increase verbosity level (repeat as needed)') group.add_option('--print-bootstrap-deps', action='store_true', help='Output bootstrap deps list.') group.add_option( '--extra-chrome-categories', dest='extra_chrome_categories', type=str, help= 'Filter string to enable additional chrome tracing categories. See' ' documentation here: https://cs.chromium.org/chromium/src/base/' 'trace_event/trace_config.h?rcl=' 'c8db6c6371ca047c24d41f3972d5819bc83d83ae&l=125') group.add_option( '--extra-atrace-categories', dest='extra_atrace_categories', type=str, help='Comma-separated list of extra atrace categories. Use atrace' ' --list_categories to get full list.') group.add_option( '--enable-systrace', dest='enable_systrace', action='store_true', help='Enable collection of systrace. (Useful on ChromeOS where' ' atrace is not supported; collects scheduling information.)') parser.add_option_group(group) # Platform options group = optparse.OptionGroup(parser, 'Platform options') group.add_option( '--no-performance-mode', action='store_true', help='Some platforms run on "full performance mode" where the ' 'test is executed at maximum CPU speed in order to minimize noise ' '(specially important for dashboards / continuous builds). ' 'This option prevents Telemetry from tweaking such platform settings.' ) group.add_option( '--webview-embedder-apk', help= 'When running tests on android webview, more than one apk needs to' ' be installed. The apk running the test is said to embed webview.' ) parser.add_option_group(group) # Remote platform options group = optparse.OptionGroup(parser, 'Remote platform options') group.add_option('--android-blacklist-file', help='Device blacklist JSON file.') group.add_option( '--device', help='The device ID to use. ' 'If not specified, only 0 or 1 connected devices are supported. ' 'If specified as "android", all available Android devices are ' 'used.') parser.add_option_group(group) # CPU profiling on Android. group = optparse.OptionGroup( parser, ('CPU profiling over intervals of interest, ' 'Android and Linux only')) group.add_option( '--interval-profiling-target', dest='interval_profiling_target', default='renderer:main', metavar='PROCESS_NAME[:THREAD_NAME]', help= 'Run the CPU profiler on this process/thread (default=%default).') group.add_option( '--interval-profiling-period', dest='interval_profiling_periods', type='choice', choices=('navigation', 'interactions'), action='append', default=[], metavar='PERIOD', help='Run the CPU profiler during this test period. ' 'May be specified multiple times; available choices ' 'are ["navigation", "interactions"]. Profile data will be written to' 'artifacts/*.perf.data (Android) or artifacts/*.profile.pb (Linux) ' 'files in the output directory. See ' 'https://developer.android.com/ndk/guides/simpleperf for more info on ' 'Android profiling via simpleperf.') group.add_option( '--interval-profiling-frequency', default=1000, metavar='FREQUENCY', type=int, help='Frequency of CPU profiling samples, in samples per second ' '(default=%default).') parser.add_option_group(group) # Browser options. self.browser_options.AddCommandLineArgs(parser) real_parse = parser.parse_args def ParseArgs(args=None): defaults = parser.get_default_values() for k, v in defaults.__dict__.items(): if k in self.__dict__ and self.__dict__[k] != None: continue self.__dict__[k] = v ret = real_parse(args, self) # pylint: disable=E1121 if self.verbosity >= 2: global_hooks.InstallSpyOnPopenArgs() logging.getLogger().setLevel(logging.DEBUG) elif self.verbosity: logging.getLogger().setLevel(logging.INFO) else: logging.getLogger().setLevel(logging.WARNING) if self.chromium_output_dir: os.environ['CHROMIUM_OUTPUT_DIR'] = self.chromium_output_dir # Parse remote platform options. self.BuildRemotePlatformOptions() if self.remote_platform_options.device == 'list': if binary_manager.NeedsInit(): binary_manager.InitDependencyManager([]) devices = device_finder.GetDevicesMatchingOptions(self) print 'Available devices:' for device in devices: print ' ', device.name sys.exit(0) if self.browser_executable and not self.browser_type: self.browser_type = 'exact' if self.browser_type == 'list': if binary_manager.NeedsInit(): binary_manager.InitDependencyManager([]) devices = device_finder.GetDevicesMatchingOptions(self) if not devices: sys.exit(0) browser_types = {} for device in devices: try: possible_browsers = browser_finder.GetAllAvailableBrowsers( self, device) browser_types[device.name] = sorted([ browser.browser_type for browser in possible_browsers ]) except browser_finder_exceptions.BrowserFinderException as ex: print >> sys.stderr, 'ERROR: ', ex sys.exit(1) print 'Available browsers:' if len(browser_types) == 0: print ' No devices were found.' for device_name in sorted(browser_types.keys()): print ' ', device_name for browser_type in browser_types[device_name]: print ' ', browser_type if len(browser_types[device_name]) == 0: print ' No browsers found for this device' sys.exit(0) # Parse browser options. self.browser_options.UpdateFromParseResults(self) return ret parser.parse_args = ParseArgs return parser
def prn(pk): p_or_s = pk.sprintf('%TCP.sport%').replace('_', '-') port = p_or_s if p_or_s.isdigit() else socket.getservbyname(p_or_s, 'tcp') service = 'unknown' if p_or_s.isdigit() else p_or_s return '{:<5} open {}'.format(port, service)
def load_i18n(canonical_host, canonical_scheme, project_root, tell_sentry): # Load the locales localeDir = os.path.join(project_root, 'i18n', 'core') locales = LOCALES source_strings = {} for file in os.listdir(localeDir): try: parts = file.split(".") if not (len(parts) == 2 and parts[1] == "po"): continue lang = parts[0] with open(os.path.join(localeDir, file), 'rb') as f: l = locales[lang.lower()] = Locale(lang) c = l.catalog = read_po(f) share_source_strings(c, source_strings) c.plural_func = get_function_from_rule(c.plural_expr) replace_unused_singulars(c) try: l.countries = make_sorted_dict(COUNTRIES, l.territories) except KeyError: l.countries = COUNTRIES try: l.languages_2 = make_sorted_dict(LANGUAGES_2, l.languages) except KeyError: l.languages_2 = LANGUAGES_2 except Exception as e: tell_sentry(e, {}) del source_strings # Prepare a unique and sorted list for use in the language switcher percent = lambda l, total: sum((percent(s, len(s)) if isinstance(s, tuple) else 1) for s in l if s) / total for l in list(locales.values()): if l.language == 'en': l.completion = 1 continue l.completion = percent([m.string for m in l.catalog if m.id and not m.fuzzy], len(l.catalog)) if l.completion == 0: del locales[l.language] loc_url = canonical_scheme+'://%s.'+canonical_host domain, port = (canonical_host.split(':') + [None])[:2] port = int(port) if port else socket.getservbyname(canonical_scheme, 'tcp') subdomains = { l.subdomain: loc_url % l.subdomain for l in locales.values() if resolve(l.subdomain + '.' + domain, port) } lang_list = sorted( ( (l.completion, l.language, l.language_name.title(), loc_url % l.subdomain) for l in set(locales.values()) if l.completion > 0.5 ), key=lambda t: (-t[0], t[1]), ) # Add year-less date format year_re = re.compile(r'(^y+[^a-zA-Z]+|[^a-zA-Z]+y+$)') for l in locales.values(): short_format = l.date_formats['short'].pattern assert short_format[0] == 'y' or short_format[-1] == 'y', (l.language, short_format) l.date_formats['short_yearless'] = year_re.sub('', short_format) # Add aliases for k, v in list(locales.items()): locales.setdefault(ALIASES.get(k, k), v) locales.setdefault(ALIASES_R.get(k, k), v) for k, v in list(locales.items()): locales.setdefault(k.split('_', 1)[0], v) # Patch the locales to look less formal locales['fr'].currency_formats['standard'] = parse_pattern('#,##0.00\u202f\xa4') locales['fr'].currencies['USD'] = 'dollar états-unien' # Load the markdown files docs = {} heading_re = re.compile(r'^(#+ )', re.M) for path in find_files(os.path.join(project_root, 'i18n'), '*.md'): d, b = os.path.split(path) doc = os.path.basename(d) lang = b[:-3] with open(path, 'rb') as f: md = f.read().decode('utf8') if md.startswith('# '): md = '\n'.join(md.split('\n')[1:]).strip() md = heading_re.sub(r'##\1', md) docs.setdefault(doc, {}).__setitem__(lang, markdown.render(md)) return {'docs': docs, 'lang_list': lang_list, 'locales': locales, 'subdomains': subdomains}
peerFh = peerSh.makefile() query = peerFh.readline().strip("\r\n") detailed = False if query[:3] == "/W ": query = query[3:] detailed = True reListSessions(peerFh) peerFh.close() peerSh.close() opt_force_inet4 = True port = so.getservbyname("finger") or 79 if so.has_ipv6 and not opt_force_inet4: family, interface = so.AF_INET6, "::" else: family, interface = so.AF_INET, "0.0.0.0" serverSh = so.socket(family, so.SOCK_STREAM) serverSh.bind((interface, port)) serverSh.listen(1) print "Listening on %(interface)s/%(port)d" % locals() while True: (peerSh, peerAddr) = serverSh.accept() print "Connected from %s:%d" % peerAddr handler(peerSh, peerAddr) serverSh.close()
def port_to_int(port): try: return int(port) except ValueError: return socket.getservbyname(port)
def __init__(self, host, port, factory, timeout, bindAddress, reactor=None): if isinstance(port, types.StringTypes): try: port = socket.getservbyname(port, 'tcp') except socket.error, e: raise error.ServiceNameUnknownError(string="%s (%r)" % (e, port))
return ok self.log( 'TRACE', "subtract_quota: %s for %i" % (pageunits, self.printer_quota.account_id)) self.printer_quota.pages_printed += pageunits self.printer_quota.printer_quota -= pageunits self.printer_quota.write_db() db.commit() return ok # send(line) - send a line (terminated by CR NL) def send(self, msg): self.wfile.write("%s^M\n" % msg) # @foo = &get; - Returns a list of tokens def get(self): return self.rfile.readline().rstrip().split() def log(self, lvl, msg): f = file(pqdlog, "a") f.write("%s [%s] %s %s\n" % (strftime("%Y-%m-%d %H:%M:%S", gmtime()), my_pid, lvl, msg)) f.close() if __name__ == '__main__': server = MyServer(('', socket.getservbyname("prissquota", "tcp")), RequestHandler) server.serve_forever()
def main(): user_source_file = "running-config.cfg" # Open the source configuration file for reading and import/parse it. x = open(user_source_file,'r') config_raw = x.readlines() config_parse = CiscoConfParse(config_raw) x.close() # Send configuration off to get split up into different lists/dictionaries for reference ret_names, ret_objects, ret_object_groups, ret_access_lists, ret_object_nat, ret_static_nat, ret_service_objects, ret_custom_objects = parse_asa_configuration(config_raw,config_parse) # Fine tune Lists and Dictionaries network_objects = {} object_groups = {} network_services = {} service_objects = {} # Names for x in ret_names: tmp = x.split(' ') network_objects[tmp[-1][:-1]] = tmp[1]+"/32" # Objects for x in ret_objects: if ret_objects[x][0].lstrip().split(" ")[0] == "host": network_objects[x] = ret_objects[x][0].lstrip().split(" ")[1][:-1]+"/32" else: netmask = netaddr.IPAddress(ret_objects[x][0].lstrip().split(" ")[-1][:-1]).netmask_bits() network_objects[x] = ret_objects[x][0].lstrip().split(" ")[1]+"/"+str(netmask) # Object Groups for x in ret_object_groups: object_groups[x] = [] for y in ret_object_groups[x]: if y.lstrip().split(" ")[0] == "network-object" and y.lstrip().split(" ")[1] == "host": object_groups[x].append(y.lstrip().split(" ")[-1][:-1]+"/32") elif y.lstrip().split(" ")[0] == "network-object" and y.lstrip().split(" ")[1] == "object": object_groups[x].append(y.lstrip().split(" ")[-1][:-1]) elif y.lstrip().split(" ")[0] == "network-object": object_groups[x].append(y.lstrip().split(" ")[1]+"/"+str(netaddr.IPAddress(y.lstrip().split(" ")[-1][:-1]).netmask_bits())) elif y.lstrip().split(" ")[0] == "group-object": object_groups[x].append(y.lstrip().split(" ")[-1][:-1]) else: print "error occured during Object Groups" # Services for x in ret_custom_objects: tmp = ret_custom_objects[x][0].strip().split(" ") if not is_number(tmp[-1]): network_services[x] = tmp[1]+"/"+str(getservbyname(tmp[-1])) else: network_services[x] = tmp[1]+"/"+tmp[-1] # Service Objects ## for x in ret_service_objects: ## service_objects[x] = [] ## for y in ret_service_objects[x]: ## tmp = y.lstrip().split(" ") ## if tmp[0] == "port-object" and tmp[1] == "eq": ## if not is_number(tmp[-1]): ## service_objects[x].append("tcp/"+str(getservbyname(tmp[-1][:-1]))) ## else: ## service_objects[x].append("tcp/"+tmp[-1][:-1]) ## elif tmp[0] == "port-object" and tmp[1] == "range": ## service_objects[x].append("tcp/"+tmp[-2]+"-"+tmp[1][:-1]) ## elif tmp[0] == "group-object": ## service_objects[x].append(tmp[-1][:-1]) ## elif tmp[0] == "service-object" and tmp[1] == "tcp": ## if not is_number(tmp[-1]): ## service_objects[x].append("tcp/"+str(getservbyname(tmp[-1][:-1]))) ## else: ## service_objects[x].append("tcp/"+tmp[-1][:-1]) for x in ret_access_lists:
def load_i18n(canonical_host, canonical_scheme, project_root, tell_sentry): def compute_percentage(it, total): return sum( (compute_percentage(s, len(s)) if isinstance(s, tuple) else 1) for s in it if s) / total # Load the base locales localeDir = os.path.join(project_root, 'i18n', 'core') locales = LOCALES source_strings = {} for file in os.listdir(localeDir): try: parts = file.split(".") if not (len(parts) == 2 and parts[1] == "po"): continue lang = parts[0] with open(os.path.join(localeDir, file), 'rb') as f: l = Locale(lang) c = l.catalog = read_po(f) share_source_strings(c, source_strings) c.plural_func = get_function_from_rule(c.plural_expr) replace_unused_singulars(c) l.completion = compute_percentage( (m.string for m in c if m.id and not m.fuzzy), len(c)) if l.completion == 0: continue else: locales[lang.lower()] = l try: l.countries = make_sorted_dict(COUNTRIES, l.territories) except KeyError: l.countries = COUNTRIES try: l.languages_2 = make_sorted_dict(LANGUAGES_2, l.languages) except KeyError: l.languages_2 = LANGUAGES_2 except Exception as e: tell_sentry(e) del source_strings # Load the variants for loc_id in babel.localedata.locale_identifiers(): if loc_id in locales: continue i = loc_id.rfind('_') if i == -1: continue base = locales.get(loc_id[:i]) if base: l = locales[loc_id.lower()] = Locale.parse(loc_id) l.catalog = base.catalog l.completion = base.completion l.countries = base.countries l.languages_2 = base.languages_2 # Unload the Babel data that we no longer need # We load a lot of data to populate the LANGUAGE_NAMES dict, we don't want # to keep it all in RAM. used_data_dict_addresses = set(id(l._data._data) for l in locales.values()) for key, data_dict in list(babel.localedata._cache.items()): if id(data_dict) not in used_data_dict_addresses: del babel.localedata._cache[key] # Prepare a unique and sorted list for use in the language switcher loc_url = canonical_scheme + '://%s.' + canonical_host domain, port = (canonical_host.split(':') + [None])[:2] port = int(port) if port else socket.getservbyname(canonical_scheme, 'tcp') subdomains = { l.subdomain: loc_url % l.subdomain for l in locales.values() if not l.territory and resolve(l.subdomain + '.' + domain, port) } lang_list = sorted( ((l.completion, l.language, l.language_name.title(), loc_url % l.subdomain) for l in set(locales.values()) if not l.territory and l.completion > 0.5), key=lambda t: (-t[0], t[1]), ) # Add year-less date format year_re = re.compile(r'(^y+[^a-zA-Z]+|[^a-zA-Z]+y+$)') for l in locales.values(): short_format = l.date_formats['short'].pattern assert short_format[0] == 'y' or short_format[-1] == 'y', ( l.language, short_format) l.date_formats['short_yearless'] = year_re.sub('', short_format) # Add aliases for k, v in list(locales.items()): locales.setdefault(ALIASES.get(k, k), v) locales.setdefault(ALIASES_R.get(k, k), v) for k, v in list(locales.items()): locales.setdefault(k.split('_', 1)[0], v) # Add universal strings # These strings don't need to be translated, but they have to be in the catalogs # so that they're counted as translated. for l in locales.values(): l.catalog.add("PayPal", "PayPal") # Patch the locales to look less formal locales['fr'].currency_formats['standard'] = parse_pattern( '#,##0.00\u202f\xa4') locales['fr'].currencies['USD'] = 'dollar états-unien' # Load the markdown files docs = {} heading_re = re.compile(r'^(#+ )', re.M) for path in find_files(os.path.join(project_root, 'i18n'), '*.md'): d, b = os.path.split(path) doc = os.path.basename(d) lang = b[:-3] with open(path, 'rb') as f: md = f.read().decode('utf8') if md.startswith('# '): md = '\n'.join(md.split('\n')[1:]).strip() md = heading_re.sub(r'##\1', md) docs.setdefault(doc, {}).__setitem__(lang, markdown.render(md)) return { 'docs': docs, 'lang_list': lang_list, 'locales': locales, 'subdomains': subdomains }
def ParseArgs(args=None): defaults = parser.get_default_values() for k, v in defaults.__dict__.items(): if k in self.__dict__ and self.__dict__[k] != None: continue self.__dict__[k] = v ret = real_parse(args, self) # pylint: disable=E1121 if self.chromium_output_dir: os.environ['CHROMIUM_OUTPUT_DIR'] = self.chromium_output_dir # Parse remote platform options. self.BuildRemotePlatformOptions() if self.remote_platform_options.device == 'list': if binary_manager.NeedsInit(): binary_manager.InitDependencyManager([]) devices = device_finder.GetDevicesMatchingOptions(self) print 'Available devices:' for device in devices: print ' ', device.name sys.exit(0) if self.browser_executable and not self.browser_type: self.browser_type = 'exact' if self.browser_type == 'list': if binary_manager.NeedsInit(): binary_manager.InitDependencyManager([]) devices = device_finder.GetDevicesMatchingOptions(self) if not devices: sys.exit(0) browser_types = {} for device in devices: try: possible_browsers = browser_finder.GetAllAvailableBrowsers( self, device) browser_types[device.name] = sorted([ browser.browser_type for browser in possible_browsers ]) except browser_finder_exceptions.BrowserFinderException as ex: print >> sys.stderr, 'ERROR: ', ex sys.exit(1) print 'Available browsers:' if len(browser_types) == 0: print ' No devices were found.' for device_name in sorted(browser_types.keys()): print ' ', device_name for browser_type in browser_types[device_name]: print ' ', browser_type if len(browser_types[device_name]) == 0: print ' No browsers found for this device' sys.exit(0) if self.browser_type == 'cros-chrome' and self.cros_remote and ( self.cros_remote_ssh_port < 0): try: self.cros_remote_ssh_port = socket.getservbyname('ssh') except OSError as e: raise RuntimeError( 'Running a CrOS test in remote mode, but failed to retrieve port ' 'used by SSH service. This likely means SSH is not installed on ' 'the system. Original error: %s' % e) # Profiling other periods along with the story_run period leads to running # multiple profiling processes at the same time. The effects of performing # muliple CPU profiling at the same time is unclear and may generate # incorrect profiles so this will not be supported. if (len(self.interval_profiling_periods) > 1 and 'story_run' in self.interval_profiling_periods): print 'Cannot specify other periods along with the story_run period.' sys.exit(1) self.interval_profiler_options = shlex.split( self.interval_profiler_options, posix=(not _IsWin())) # Parse browser options. self.browser_options.UpdateFromParseResults(self) return ret
def _do_call(self, obj, targets=None, registry=None): # pylint: disable=unused-argument if not targets: targets = self.targets param_target = obj.get_params().get('target') for target in targets: (data, conn) = (None, None) cfg = target.config common_name = cfg.get('common_name') cfg['verify_peer'] = cfg.get('verify_peer', True) cfg['ip_protocol'] = _IP_PROTOCOLS.get(cfg.get('ip_protocol'), socket.AF_INET) if cfg.get('timeout') is not None: cfg['timeout'] = float(cfg['timeout']) else: cfg['timeout'] = None if param_target and not cfg.get('uri'): uri = param_target else: uri = cfg.get('uri') if not uri: raise CovenantConfigurationError( "missing uri or target in configuration") uri_split = urisup.uri_help_split(uri) scheme = None if not isinstance(uri_split[1], tuple): host = uri_split[0] port = uri_split[2] elif uri_split[1]: scheme = uri_split[0] host, port = uri_split[1][2:4] else: raise CovenantConfigurationError( "missing host and port in uri: %r" % uri) if not host: raise CovenantConfigurationError( "missing or invalid host in uri: %r" % uri) if scheme and not port: try: port = socket.getservbyname(scheme) except socket.error: pass if not port: raise CovenantConfigurationError( "missing or invalid port in uri: %r" % uri) data = { 'connect_success': False, 'cert_secure': False, "%s_success" % self.type: False } conn = None try: server_hostname = common_name or host context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE self._load_context_options(context, cfg.get('options')) conn = self._connect(context, host, port, server_hostname, cfg['ip_protocol'], cfg['timeout']) data['cipher_info'] = conn.cipher()[0] data['version_info'] = conn.version() valid_hosts = {'subject': [], 'subjectAltName': []} cert_der = conn.getpeercert(True) if cert_der: self._subject_alt_name( self._load_cert(cert_der, data)[0], data, valid_hosts) data['hostname_valid'] = self._valid_hostname( valid_hosts, server_hostname) if cfg['verify_peer']: if conn: conn.shutdown(socket.SHUT_RDWR) conn.close() conn = None context.verify_mode = ssl.CERT_REQUIRED context.load_default_certs(ssl.Purpose.SERVER_AUTH) conn = self._connect(context, host, port, server_hostname, cfg['ip_protocol'], cfg['timeout']) except ssl.SSLError as e: LOG.warning("ssl error on target: %r. exception: %r", target.name, e) except Exception as e: data = CovenantTargetFailed(e) LOG.exception("error on target: %r. exception: %r", target.name, e) else: if data.get('connect_success'): if not cfg['verify_peer']: data["%s_success" % self.type] = True elif not data.get('cert_has_expired') \ and data.get('hostname_valid'): data['cert_secure'] = True data["%s_success" % self.type] = True finally: if conn: conn.shutdown(socket.SHUT_RDWR) conn.close() target(data) return self.generate_latest(registry)
def CreateParser(self, *args, **kwargs): parser = optparse.OptionParser(*args, **kwargs) # Selection group group = optparse.OptionGroup(parser, 'Which browser to use') group.add_option('--browser', dest='browser_type', default=None, help='Browser type to run, ' 'in order of priority. Supported values: list,%s' % ','.join(browser_finder.FindAllBrowserTypes(self))) group.add_option('--browser-executable', dest='browser_executable', help='The exact browser to run.') group.add_option('--chrome-root', dest='chrome_root', help='Where to look for chrome builds. ' 'Defaults to searching parent dirs by default.') group.add_option( '--chromium-output-directory', dest='chromium_output_dir', help='Where to look for build artifacts. ' 'Can also be specified by setting environment variable ' 'CHROMIUM_OUTPUT_DIR.') group.add_option( '--device', dest='device', help='The device ID to use. ' 'If not specified, only 0 or 1 connected devices are supported. ' 'If specified as "android", all available Android devices are ' 'used.') group.add_option( '--remote', dest='cros_remote', help='The hostname of a remote ChromeOS device to use.') group.add_option( '--remote-ssh-port', type=int, default=socket.getservbyname('ssh'), dest='cros_remote_ssh_port', help= 'The SSH port of the remote ChromeOS device (requires --remote).') identity = None testing_rsa = os.path.join(util.GetTelemetryThirdPartyDir(), 'chromite', 'ssh_keys', 'testing_rsa') if os.path.exists(testing_rsa): identity = testing_rsa group.add_option( '--identity', dest='cros_ssh_identity', default=identity, help= 'The identity file to use when ssh\'ing into the ChromeOS device') parser.add_option_group(group) # Debugging options group = optparse.OptionGroup(parser, 'When things go wrong') profiler_choices = profiler_finder.GetAllAvailableProfilers() group.add_option( '--profiler', default=None, type='choice', choices=profiler_choices, help='Record profiling data using this tool. Supported values: %s. ' '(Notice: this flag cannot be used for Timeline Based Measurement ' 'benchmarks.)' % ', '.join(profiler_choices)) group.add_option('-v', '--verbose', action='count', dest='verbosity', help='Increase verbosity level (repeat as needed)') group.add_option('--print-bootstrap-deps', action='store_true', help='Output bootstrap deps list.') parser.add_option_group(group) # Platform options group = optparse.OptionGroup(parser, 'Platform options') group.add_option( '--no-performance-mode', action='store_true', help='Some platforms run on "full performance mode" where the ' 'test is executed at maximum CPU speed in order to minimize noise ' '(specially important for dashboards / continuous builds). ' 'This option prevents Telemetry from tweaking such platform settings.' ) group.add_option('--android-rndis', dest='android_rndis', default=False, action='store_true', help='Use RNDIS forwarding on Android.') group.add_option('--no-android-rndis', dest='android_rndis', action='store_false', help='Do not use RNDIS forwarding on Android.' ' [default]') group.add_option('--android-blacklist-file', help='Device blacklist JSON file.') parser.add_option_group(group) # Browser options. self.browser_options.AddCommandLineArgs(parser) real_parse = parser.parse_args def ParseArgs(args=None): defaults = parser.get_default_values() for k, v in defaults.__dict__.items(): if k in self.__dict__ and self.__dict__[k] != None: continue self.__dict__[k] = v ret = real_parse(args, self) # pylint: disable=E1121 if self.verbosity >= 2: logging.getLogger().setLevel(logging.DEBUG) elif self.verbosity: logging.getLogger().setLevel(logging.INFO) else: logging.getLogger().setLevel(logging.WARNING) if self.chromium_output_dir: os.environ['CHROMIUM_OUTPUT_DIR'] = self.chromium_output_dir if self.device == 'list': if binary_manager.NeedsInit(): binary_manager.InitDependencyManager(None) devices = device_finder.GetDevicesMatchingOptions(self) print 'Available devices:' for device in devices: print ' ', device.name sys.exit(0) if self.browser_executable and not self.browser_type: self.browser_type = 'exact' if self.browser_type == 'list': if binary_manager.NeedsInit(): binary_manager.InitDependencyManager(None) devices = device_finder.GetDevicesMatchingOptions(self) if not devices: sys.exit(0) browser_types = {} for device in devices: try: possible_browsers = browser_finder.GetAllAvailableBrowsers( self, device) browser_types[device.name] = sorted([ browser.browser_type for browser in possible_browsers ]) except browser_finder_exceptions.BrowserFinderException as ex: print >> sys.stderr, 'ERROR: ', ex sys.exit(1) print 'Available browsers:' if len(browser_types) == 0: print ' No devices were found.' for device_name in sorted(browser_types.keys()): print ' ', device_name for browser_type in browser_types[device_name]: print ' ', browser_type sys.exit(0) # Parse browser options. self.browser_options.UpdateFromParseResults(self) return ret parser.parse_args = ParseArgs return parser
import socket import utils HOST = 'localhost' service = 'daytime' port = socket.getservbyname(service) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect((HOST, port)) sock.send(utils.ensure_bytes(service)) data = sock.recvfrom(1024) print(utils.ensure_unicode(data)) sock.close()
#!/usr/bin/env python # encoding: utf-8 """ @desc: @software: pycharm @file: draft.py @time: 2018/10/14 11:41 @author: liuzy @contact: [email protected] @license: (C) Copyright 2015-2018, Node Supply Chain Manager Corporation Limited. """ if __name__ == '__main__': import socket from pprint import pprint pprint(socket.has_ipv6) infolist = socket.getaddrinfo('baidu.com', 'www') pprint(infolist) print(socket.gethostbyname('baidu.com')) # print(socket.getfqdn('baidu.com')) print(socket.gethostbyaddr('127.0.0.1')) print(socket.getprotobyname('udp')) print(socket.getservbyport(22)) print(socket.getservbyname('ssh')) socket.gethostbyname(socket.getfqdn())