本文整理汇总了Python中netifaces.gateways函数的典型用法代码示例。如果您正苦于以下问题:Python gateways函数的具体用法?Python gateways怎么用?Python gateways使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了gateways函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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
示例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)
示例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!')
示例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
示例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
示例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
示例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}'")
示例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]
示例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
示例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
示例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"
示例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))
示例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)