• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python netifaces.gateways函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中netifaces.gateways函数的典型用法代码示例。如果您正苦于以下问题:Python gateways函数的具体用法?Python gateways怎么用?Python gateways使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了gateways函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: update

    def update(self):
        """Update IP stats using the input method.

        Stats is dict
        """
        # Reset stats
        self.reset()

        if self.input_method == 'local' and netifaces_tag:
            # Update stats using the netifaces lib
            try:
                if not 'freebsd' in sys.platform:
                    default_gw = netifaces.gateways()['default'][netifaces.AF_INET]
                else:
                    raise KeyError, 'On FreeBSD, Calling gateways would segfault'
            except KeyError:
                logger.debug("Can not grab the default gateway")
            else:
                try:
                    self.stats['address'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr']
                    self.stats['mask'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['netmask']
                    self.stats['mask_cidr'] = self.ip_to_cidr(self.stats['mask'])
                    if not 'freebsd' in sys.platform:
                        self.stats['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0]
                except KeyError as e:
                    logger.debug("Can not grab IP information (%s)".format(e))

        elif self.input_method == 'snmp':
            # Not implemented yet
            pass

        # Update the view
        self.update_views()

        return self.stats
开发者ID:hank,项目名称:glances,代码行数:35,代码来源:glances_ip.py


示例2: _get_address

def _get_address():
    """
    Returns the address of some selected network gateway interface.

    """
    if netifaces.AF_INET not in netifaces.gateways():
        print('No network interfaces available')
        sys.exit()

    available_gateways = {}
    for i, (_, intf, _) in \
            enumerate(netifaces.gateways()[netifaces.AF_INET]):
        available_gateways[str(i)] = intf
    gateway = handle_console_input(available_gateways)
    address = netifaces.ifaddresses(gateway)[netifaces.AF_INET][0]['addr']

    """
    Why did i have to use the ifaddresses method? instead of just grabbing
    the address from the gateways()[2] tuple?
    this is returning 10.1.1.1, the location of the router.
    The gateways assigned address must be given by the ifaddresses function

    netifaces.gateways()
    - will only return the gateway/interface that is 'active(?)', so if both
    wlan0 and eth0 are plugged in, only one connection is used as a network
    connection , for example browsers will only connect through the single
    'active' gateway.

    """
    return address
开发者ID:manno23,项目名称:Hydra,代码行数:30,代码来源:config.py


示例3: update

    def update(self):
        """Update IP stats using the input method.

        Stats is dict
        """
        # Reset stats
        self.reset()

        if self.input_method == 'local' and netifaces_tag:
            # Update stats using the netifaces lib
            try:
                default_gw = netifaces.gateways()['default'][netifaces.AF_INET]
            except (KeyError, AttributeError) as e:
                logger.debug("Cannot grab the default gateway ({0})".format(e))
            else:
                try:
                    self.stats['address'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr']
                    self.stats['mask'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['netmask']
                    self.stats['mask_cidr'] = self.ip_to_cidr(self.stats['mask'])
                    self.stats['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0]
                except (KeyError, AttributeError) as e:
                    logger.debug("Cannot grab IP information: {0}".format(e))
        elif self.input_method == 'snmp':
            # Not implemented yet
            pass

        # Update the view
        self.update_views()

        return self.stats
开发者ID:0daybug,项目名称:glances,代码行数:30,代码来源:glances_ip.py


示例4: main

def main():
    setup()

    bus = pydbus.SystemBus()

    pattern_include = re.compile("wlan*")
    pattern_exclude = re.compile("ScreenlyOSE-*")

    wireless_connections = filter(
        lambda c: not pattern_exclude.search(str(c['Id'])),
        filter(
            lambda c: pattern_include.search(str(c['Devices'])),
            get_active_connections(bus)
        )
    )

    # Displays the hotspot page
    if not path.isfile(HOME + INITIALIZED_FILE) and not gateways().get('default'):
        if wireless_connections is None or len(wireless_connections) == 0:
            url = 'http://{0}/hotspot'.format(LISTEN)
            load_browser(url=url)

    # Wait until the network is configured
    while not path.isfile(HOME + INITIALIZED_FILE) and not gateways().get('default'):
        if len(wireless_connections) == 0:
            sleep(1)
            wireless_connections = filter(
                lambda c: not pattern_exclude.search(str(c['Id'])),
                filter(
                    lambda c: pattern_include.search(str(c['Devices'])),
                    get_active_connections(bus)
                )
            )
            continue
        if wireless_connections is None:
            sleep(1)
            continue
        break

    wait_for_node_ip(5)

    url = 'http://{0}:{1}/splash_page'.format(LISTEN, PORT) if settings['show_splash'] else 'file://' + BLACK_PAGE
    browser_url(url=url)

    if settings['show_splash']:
        sleep(SPLASH_DELAY)

    global scheduler
    scheduler = Scheduler()

    subscriber = ZmqSubscriber()
    subscriber.daemon = True
    subscriber.start()

    # We don't want to show splash_page if there are active assets but all of them are not available
    view_image(HOME + LOAD_SCREEN)

    logging.debug('Entering infinite loop.')
    while True:
        asset_loop(scheduler)
开发者ID:wireload,项目名称:screenly-ose,代码行数:60,代码来源:viewer.py


示例5: __init__

    def __init__(self):
        # ----------------- NIC INFO -----------------
        self.os = platform.dist()[0]
        # If system is "debian":
        if self.os == 'debian':
            self.hostname = socket.gethostname()
            self.iface = ni.interfaces()[1]
            self.ipaddress = ni.ifaddresses(self.iface)[ni.AF_INET][0]['addr']
            self.subnet = ni.ifaddresses(self.iface)[ni.AF_INET][0]['netmask']
            self.gateways = ni.gateways()['default'][ni.AF_INET][0]
            # --- OS INFO ---------------------

            self.os_ver = platform.dist()[1]
            self.mac = ''.join('%012x' % get_mac())
            self.ip_data = get_ip()
            self.path_ip = '/etc/network/interfaces'
            self.dns_file = '/etc/resolv.conf'
        # If system is "Arch Linux":
        else:
            self.hostname = socket.gethostname()
            self.iface = ni.interfaces()[1]
            self.ipaddress = ni.ifaddresses(self.iface)[ni.AF_INET][0]['addr']
            self.subnet = ni.ifaddresses(self.iface)[ni.AF_INET][0]['netmask']
            self.gateways = ni.gateways()['default'][ni.AF_INET][0]
            # --- OS INFO ---------------------
            self.os_ver = platform.dist()[1]
            self.mac = ''.join('%012x' % get_mac())
            self.ip_data = get_ip()
            self.path_ip = '/etc/netctl/eth0'
            self.dns_file = '/etc/resolv.conf'
        logger.debug('GET IP SETTING OK!')
开发者ID:jense-arntz,项目名称:Full-Stack-Server-Client-App,代码行数:31,代码来源:views.py


示例6: update

    def update(self):
        """Update IP stats using the input method.

        Stats is dict
        """
        # Init new stats
        stats = self.get_init_value()

        if self.input_method == 'local' and not import_error_tag:
            # Update stats using the netifaces lib
            try:
                default_gw = netifaces.gateways()['default'][netifaces.AF_INET]
            except (KeyError, AttributeError) as e:
                logger.debug("Cannot grab the default gateway ({})".format(e))
            else:
                try:
                    stats['address'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr']
                    stats['mask'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['netmask']
                    stats['mask_cidr'] = self.ip_to_cidr(stats['mask'])
                    stats['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0]
                    stats['public_address'] = self.public_address
                except (KeyError, AttributeError) as e:
                    logger.debug("Cannot grab IP information: {}".format(e))
        elif self.input_method == 'snmp':
            # Not implemented yet
            pass

        # Update the stats
        self.stats = stats

        return self.stats
开发者ID:nicolargo,项目名称:glances,代码行数:31,代码来源:glances_ip.py


示例7: get_network_buoy_info

def get_network_buoy_info(interface):
    """Returns info about the network and buoy in the given net interface."""
    ret = {}
    n_info = netifaces.interfaces().get(interface)
    if n_info:
        """
        AF_LINK: {17: [{'broadcast': 'ff:ff:ff:ff:ff:ff',
                        'addr': 'a0:ce:c8:05:35:f9'}],
        AF_INET:  2: [{'broadcast': '10.172.203.255', 'netmask': '255.255.255.0',
                       'addr': '10.172.203.199'}],
        AF_INET6: 10: [{'netmask': 'ffff:ffff:ffff:ffff::',
                        'addr': 'fe80::a2ce:c8ff:fe05:35f9%eth1'}]}
        """
        # Get the addresses for the given interface
        ret['AF_INET'] = n_info.get(netifaces.AF_INET) # IPv4
        ret['AF_INET6'] = n_info.get(netifaces.AF_INET6) # IPv6
        ret['AF_LINK'] = n_info[netifaces.AF_LINK] # link layer interface
        """
        {2: [('10.0.1.1', 'en0', True), ('10.2.1.1', 'en1', False)],
         30: [('fe80::1', 'en0', True)],
         'default': { 2: ('10.0.1.1', 'en0'), 30: ('fe80::1', 'en0') }}
        """
        # Get the default gateways for IPv4 and IPv6
        ret['gateways'] = {}
        ret['gateways']['AF_INET'] = netifaces.gateways()['default'].get(
            netifaces.AF_INET)
        ret['gateways']['AF_INET6'] = netifaces.gateways()['default'].get(
            netifaces.AF_INET6)
    return ret
开发者ID:7flying,项目名称:netpicket,代码行数:29,代码来源:netscan.py


示例8: get_interfaces

 def get_interfaces():
     interfaces = {'activated':None,'all':[],'gateway':None,'IPaddress':None}
     interfaces['all'] = netifaces.interfaces()
     try:
         interfaces['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0]
         interfaces['activated'] = netifaces.gateways()['default'][netifaces.AF_INET][1]
         interfaces['IPaddress'] = Refactor.get_Ipaddr(interfaces['activated'])
     except KeyError:
         print('Error: find network interface information ')
     return interfaces
开发者ID:laykatz,项目名称:WiFi-Pumpkin,代码行数:10,代码来源:Utils.py


示例9: setNetworkInfo

def setNetworkInfo() :
    global dev
    global my_ip
    global my_mac
    global gateway_ip
    global gateway_mac

    dev = netifaces.gateways()['default'][netifaces.AF_INET][1]
    my_ip = netifaces.ifaddresses(dev)[2][0]['addr']
    my_mac = netifaces.ifaddresses(dev)[17][0]['addr']
    gateway_ip = netifaces.gateways()[2][0][0]
    gateway_mac = getBash("arp -a | grep \"("+gateway_ip+")\" | awk -F ' ' '{print $4}'")
开发者ID:sianux1209,项目名称:arp_poison,代码行数:12,代码来源:spoofer.py


示例10: default_interface

def default_interface():
    """ Get default gateway interface.

    Some OSes return 127.0.0.1 when using
    socket.gethostbyname(socket.gethostname()),
    so we're attempting to get a kind of valid hostname here.
    """
    try:
        return netifaces.gateways()["default"][netifaces.AF_INET][1]
    except KeyError:
        # Sometimes 'default' is empty but AF_INET exists alongside it
        return netifaces.gateways()[netifaces.AF_INET][0][1]
开发者ID:pombredanne,项目名称:zget,代码行数:12,代码来源:utils.py


示例11: viewNetworkSettings

def viewNetworkSettings():
	global screenMode,curIPEth0,curMskEth0,curMACEth0,curIPWlan0,curMskWlan0,curMACWlan0,curGWDefault,curDNS1,curDNS2,dnslist
	dnslist = []
	curIPEth0 = netifaces.ifaddresses('eth0').setdefault(netifaces.AF_INET,[{'addr':''}])[0]['addr']
	curMskEth0 = netifaces.ifaddresses('eth0').setdefault(netifaces.AF_INET,[{'netmask':''}])[0]['netmask']
	curMACEth0 = netifaces.ifaddresses('eth0').setdefault(netifaces.AF_LINK,[{'addr':''}])[0]['addr']
	try:
		curIPWlan0 = netifaces.ifaddresses('wlan0').setdefault(netifaces.AF_INET,[{'addr':''}])[0]['addr']
		curMskWlan0 = netifaces.ifaddresses('wlan0').setdefault(netifaces.AF_INET,[{'netmask':''}])[0]['netmask']
		curMACWlan0 = netifaces.ifaddresses('wlan0').setdefault(netifaces.AF_LINK,[{'addr':''}])[0]['addr']
	except:
		curIPWlan0 = ""
		curMskWlan0 = ""
		curMACWlan0 = ""
	gws = netifaces.gateways()
	try:
		curGWDefault = gws['default'][netifaces.AF_INET][0]
	except:
		curGWDefault = ""
	f = open("/etc/resolv.conf") 
	line = f.readline()
	while line:
		line = line.replace('nameserver','')
		line = line.replace(' ','')
		line = line.replace('\n','')
		if isIpAddr(line):
			dnslist.append(line)
		line = f.readline()
	f.close()
	screenMode = 4
开发者ID:FishTest,项目名称:xpi,代码行数:30,代码来源:tools.py


示例12: ip_relay_callback

def ip_relay_callback(packet):
	ether_dst = packet.sprintf("%Ether.dst%")
	ether_src = packet.sprintf("%Ether.src%")
	ip_src = packet.sprintf("%IP.src%")
	ip_dst = packet.sprintf("%IP.dst%")
	if ARP in packet:
		arp_p = ARP_POISION()
		arp_p.send_poision()
	else:
	#packet[IP].chksum = ""
	#packet.show()
		ni.interfaces()
		gate_addr = ni.gateways()['default'][2][0]
		my_mac = ni.ifaddresses('eth0')[ni.AF_LINK][0]['addr']
		target_addr = sys.argv[1]
		if packet[IP].src == target_addr  :
			packet[Ether].dst=global_gate_mac
			packet[Ether].src=my_mac
			if packet.haslayer(UDP):
				del packet[UDP].chksum	
				del packet[UDP].len
			del packet.chksum
			del packet.len
			sendp(packet, verbose=False)
		elif packet[IP].dst == target_addr  :
			packet[Ether].dst=global_target_mac
			packet[Ether].src=my_mac
			if packet.haslayer(UDP):
				del packet[UDP].chksum	
				del packet[UDP].len
			del packet.chksum
			del packet.len
			sendp(packet, verbose=False)
	return 
开发者ID:kcatss,项目名称:network-3,代码行数:34,代码来源:arp_spoof.py


示例13: forwardPort

def forwardPort(privatePort, publicPort, lifeTime, protocol):
	privatePort = checkInt(privatePort)
	publicPort = checkInt(publicPort)
	lifeTime = checkInt(lifeTime)

	if privatePort and publicPort and lifeTime:
		#udpPacket = struct.pack("!BBIIII", 0x0, 0x2, 0x0, 0x16, 0x16, 0x3C)
		protocol = 1 if protocol.lower() == "udp" else 2

		udpPacket = struct.pack("!BBIIII", 0x0, protocol, 0x0, privatePort, publicPort, lifeTime)
		gateway = netifaces.gateways()["default"]

		if netifaces.AF_INET in gateway:
			gateway = gateway[netifaces.AF_INET][0]
			sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			sock.settimeout(10)
			try:
				sock.connect((gateway, 5351))

				sock.send(udpPacket)
				response = sock.recvfrom(16)
				sock.close

				resultArray = map(ord, response[0])
				for index in range(len(resultArray)):
					resultArray[index] = hex(resultArray[index])

				parseResult(resultArray)
			except socket.timeout:
				print "Could not connect to NAT-PMP on port 5351 (timed out after 10 seconds)"
		else:
			print "Not connected to a network!"

	else:
		print "Please input valid values"
开发者ID:teknogeek,项目名称:NAT-PMP-Python,代码行数:35,代码来源:nat-pmp.py


示例14: main

def main():

    # bssid = get_bssid(iface)



    # needs try / catch
    iface = netifaces.gateways()['default'][netifaces.AF_INET][1]
    conf.iface = iface

    local_mac = netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr']
    local_ip = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']
    print local_mac
    print local_ip

    bssid = get_bssid(iface)

    nm = nmap.PortScanner()
    nm_scan = nm.scan(hosts = '192.168.0.0/24', arguments='-sP')
    eligible_hosts = collect_eligible_hosts(nm_scan, local_ip, '192.168.0.1')
    display_eligible_hosts(eligible_hosts)
    user_choice = ask_user()
    enable_monitor_mode(iface)

    # client_to_deauth = eligible_hosts[2].mac_address
    while (True):
        for e in eligible_hosts:
            for n in range(20):
                sendp(RadioTap()/Dot11(type=0,subtype=12,addr1=test_client,addr2=bssid,addr3=bssid)/Dot11Deauth(reason=7))
开发者ID:m4ttclendenen,项目名称:deauth,代码行数:29,代码来源:deauth.py


示例15: configure

def configure(protocol, port, pipes, interface):
  remove_all()
  reactor.addSystemEventTrigger('after', 'shutdown', remove_all)

  # gets default (outward-facing) network interface (e.g. deciding which of
  # eth0, eth1, wlan0 is being used by the system to connect to the internet)
  if interface == "auto":
    interface = netifaces.gateways()['default'][netifaces.AF_INET][1]
  else:
    if interface not in netifaces.interfaces():
      raise ValueError("Given interface does not exist.", interface)

  add(protocol, port, interface)
  manager = libnetfilter_queue.Manager()

  def on_up(packet):
    def accept():
      manager.set_verdict(packet, libnetfilter_queue.NF_ACCEPT)
    pipes.up.attempt(accept, packet.size)

  def on_down(packet):
    def accept():
      manager.set_verdict(packet, libnetfilter_queue.NF_ACCEPT)
    pipes.down.attempt(accept, packet.size)

  manager.bind(UP_QUEUE, on_up)
  manager.bind(DOWN_QUEUE, on_down)

  reader = abstract.FileDescriptor()
  reader.doRead = manager.process
  reader.fileno = lambda: manager.fileno
  reactor.addReader(reader)
开发者ID:kleopatra999,项目名称:packet-queue,代码行数:32,代码来源:nfqueue.py


示例16: get_gateway_addr

def get_gateway_addr():
    """Use netifaces to get the gateway address, if we can't import it then
       fall back to a hack to obtain the current gateway automatically, since
       Python has no interface to sysctl().

       This may or may not be the gateway we should be contacting.
       It does not guarantee correct results.

       This function requires the presence of netstat on the path on POSIX
    and NT.
    """
    try:
        import netifaces
        return netifaces.gateways()["default"][netifaces.AF_INET][0]
    except ImportError:
        shell_command = 'netstat -rn'
        if os.name == "posix":
            pattern = \
                re.compile('(?:default|0\.0\.0\.0|::/0)\s+([\w\.:]+)\s+.*UG')
        elif os.name == "nt":
            if platform.version().startswith("6.1"):
                pattern = re.compile(".*?0.0.0.0[ ]+0.0.0.0[ ]+(.*?)[ ]+?.*?\n")
            else:
                pattern = re.compile(".*?Default Gateway:[ ]+(.*?)\n")
        system_out = os.popen(shell_command, 'r').read()
        if not system_out:
            raise NATPMPNetworkError(NATPMP_GATEWAY_CANNOT_FIND,
                                     error_str(NATPMP_GATEWAY_CANNOT_FIND))
        match = pattern.search(system_out)
        if not match:
            raise NATPMPNetworkError(NATPMP_GATEWAY_CANNOT_FIND,
                                     error_str(NATPMP_GATEWAY_CANNOT_FIND))
        addr = match.groups()[0].strip()
        return addr
开发者ID:littleskunk,项目名称:pyp2p,代码行数:34,代码来源:nat_pmp.py


示例17: main

def main():	
	gws=netifaces.gateways()
	gatewayip = gws['default'][netifaces.AF_INET][0]
	victimip = input("please enter victim IP:")

	victimmac = getMAC(victimip)
	gatewaymac = getMAC(gatewayip)
	
	if victimmac == None or gatewaymac == None:
		print('Could not find MAC Address')
		return
	
	print('+++ ARP Spoofing START -> VICTIM IP[%s]' %victimip)	
	print('[%s]:POISON ARP Table [%s] -> [%s]' %(victimip, gatewaymac, victimmac))	
	try:
		while True:
			p1 = IP(dst = gatewayip, src = victimip)/TCP(dport=80, sport=5000, flags='S')
			sr(p1)
			print ("Okay")

			poisonARP(gatewayip, victimip, victimmac)
			poisonARP(victimip, gatewayip, gatewaymac)
			
			
			seq = sys.stdin.readline()
			
			seq = int(seq[:-1])
			p2 = IP(dst = victimip, src = gatewayip)/TCP(dport=80, sport = 5000, flags='A',ack=seq+1, seq=1)
			sr(p2)
			
			sleep(1)
			
	except KeyboardInterrupt:  
		restoreARP(victimip, gatewayip, victimmac, gatewaymac)
		print('--- ARP Spoofing END -> RESTORED ARP Table')	
开发者ID:Soheeekim,项目名称:-BoB5-DigitalForensic-soheeKim-Network-,代码行数:35,代码来源:ARPSpoof_HW.py


示例18: get_interfaces

 def get_interfaces(self):
     '''
     Retrieve the interfaces of the VM
     '''
     interfaces = netifaces.interfaces()
     self.interfaces = []
     for interface in interfaces:
         if interface == 'lo':
             continue
         default_gw = ''
         configuration_type = None
         gws = netifaces.gateways()
         if gws['default'] != {} and gws['default'][netifaces.AF_INET][1] == interface:
             default_gw = gws['default'][netifaces.AF_INET][0]
         interface_af_link_info = netifaces.ifaddresses(interface)[17]
         if 2 in netifaces.ifaddresses(interface):
             interface_af_inet_info = netifaces.ifaddresses(interface)[2]
             ipv4_address = interface_af_inet_info[0]['addr']
             netmask = interface_af_inet_info[0]['netmask']
         else:
             ipv4_address = ""
             netmask = ""
         if interface == constants.configuration_interface:
             _type = 'config'
             configuration_type = 'dhcp'
         else:
             _type = 'not_defined'
         self.interfaces.append(Interface(name = interface, status = None, 
                   mac_address = interface_af_link_info[0]['addr'],
                   ipv4_address = ipv4_address,
                   netmask = netmask,
                   default_gw = default_gw,
                   _type = _type,
                   configuration_type = configuration_type))
开发者ID:netgroup-polito,项目名称:un-orchestrator,代码行数:34,代码来源:dhcp_server.py


示例19: add_bridge

def add_bridge(name, interface):
    network_configuration = UbuntuIntfMgmt()

    if check_interface(name):
        return
    data = get_int_config(interface)
    netmask = data[0]['netmask']
    addr = data[0]['addr']
    gateway = ni.gateways()
    gw = gateway['default'][ni.AF_INET][0]

    extra_params = network_configuration.extract_net_config(interface,
                                                            backup=True,
                                                            read_only=False)
    extra_params['inet_type'] = 'manual'
    extra_params['bridge_name'] = name
    extra_params = dict([(k, "".join(list(v))) for k, v in extra_params
                         .iteritems()])
    network_configuration._write_net_config_bridged_iface_br(interface,
                                                             **extra_params)

    extra_params = {'source_intf': interface, 'inet_type': 'static', }
    network_configuration._write_net_config_bridge(name, addr, netmask, gw,
                                                   **extra_params)

    restart_network_service(name, interface)
开发者ID:thedac,项目名称:dvnd-juju,代码行数:26,代码来源:cplane_network.py


示例20: log_message

 def log_message(self, format, *args):
     if len(args) < 3 or "200" not in args[1]:
         return
     try:
         request = pickle.load(open("pickle_data.txt","r"))
     except:
         request=OrderedDict()
     time_now = datetime.now()
     ts = time_now.strftime('%Y-%m-%d %H:%M:%S')
     iface=netifaces.gateways()['default'][netifaces.AF_INET][1]
     server = self.get_ip_address(iface)
     host=self.address_string()
     addr_pair = (host,server)
     if addr_pair not in request:
         request[addr_pair]=[1,ts]
     else:
         num = request[addr_pair][0]+1
         del request[addr_pair]
         request[addr_pair]=[num,ts]
     file=open("index.html", "w")
     file.write("<!DOCTYPE html> <html> <body><center><h1><font color=\"blue\" face=\"Georgia, Arial\" size=8><em>Real</em></font> Visit Results</h1></center>");
     for pair in request:
         if pair[0] == host:
             guest = "LOCAL: "+pair[0]
         else:
             guest = pair[0]
         if (time_now-datetime.strptime(request[pair][1],'%Y-%m-%d %H:%M:%S')).seconds < 3:
             file.write("<p style=\"font-size:150%\" >#"+ str(request[pair][1]) +": <font color=\"red\">"+str(request[pair][0])+ "</font> requests " + "from &lt<font color=\"blue\">"+guest+"</font>&gt to WebServer &lt<font color=\"blue\">"+pair[1]+"</font>&gt</p>")
         else:
             file.write("<p style=\"font-size:150%\" >#"+ str(request[pair][1]) +": <font color=\"maroon\">"+str(request[pair][0])+ "</font> requests " + "from &lt<font color=\"navy\">"+guest+"</font>&gt to WebServer &lt<font color=\"navy\">"+pair[1]+"</font>&gt</p>")
     file.write("</body> </html>");
     file.close()
     pickle.dump(request,open("pickle_data.txt","w"))
开发者ID:fernandosanchezmunoz,项目名称:simpleweb,代码行数:33,代码来源:index.py



注:本文中的netifaces.gateways函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python netifaces.ifaddresses函数代码示例发布时间:2022-05-27
下一篇:
Python utils.get_data_path函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap