def get_network_info(): try: addresses = psutil.net_if_addrs() stats = psutil.net_if_stats() except: print "psutil information not found." #if no psutil found return error return "error" dict = {} for name in addresses: #for each individual value, say no ___ if not found try: mac_address = getHwAddr(name) except: mac_address = "No mac_address found" try: ip_address = addresses[name][0][1] except: ip_address = "no ip_address found" try: speed = stats[name][2] / 1000.0 except: speed = "no speed found" try: link = stats[name][0] except: link = False dict[name] = {"mac_address": mac_address, "ip_address": ip_address, \ "speed": speed, "link": link} return dict
def test_collect_only_alive_interfaces(self): container = SystemContainer() container.discover_objects() os_obj = container.objects.values().pop() collector = SystemMetricsCollector(object=os_obj) collector.collect() collector.collect() # double collect is needed, because otherwise we do not collect metrics properly # get interfaces info all_interfaces = netifaces.interfaces() alive_interfaces = set() down_interfaces = set() for interface_name, interface in psutil.net_if_stats().iteritems(): if interface.isup: alive_interfaces.add(interface_name) else: down_interfaces.add(interface_name) # check collected_metrics = os_obj.statsd.current net_metrics_found = False for metric in collected_metrics['counter'].keys(): if metric.startswith('system.net.') and '|' in metric: net_metrics_found = True metric_name, label_name = metric.split('|') assert_that(all_interfaces, has_item(label_name)) assert_that(alive_interfaces, has_item(label_name)) assert_that(down_interfaces, not_(has_item(label_name))) assert_that(net_metrics_found, equal_to(True))
def test_net_if_stats_enodev(self): # See: https://github.com/giampaolo/psutil/issues/1279 with mock.patch('psutil._psutil_posix.net_if_mtu', side_effect=OSError(errno.ENODEV, "")) as m: ret = psutil.net_if_stats() self.assertEqual(ret, {}) assert m.called
def alive_interfaces(): """ Returns a list of all network interfaces which have UP state see ip link show dev eth0 will always return lo in a list if lo exists :return: [] of str """ alive_interfaces = set() try: for interface_name, interface in psutil.net_if_stats().iteritems(): if interface.isup: alive_interfaces.add(interface_name) except: # fallback for centos6 for interface_name in netifaces.interfaces(): ip_link_out, _ = subp.call("ip link show dev %s" % interface_name, check=False) if ip_link_out: first_line = ip_link_out[0] state_match = re.match('.+state\s+(\w+)\s+.*', first_line) if state_match: state = state_match.group(1) if interface_name == 'lo' or state == 'UP': alive_interfaces.add(interface_name) elif state == 'UNKNOWN': # If state is 'UNKNOWN" (e.g. venet with OpenVZ) check to see if 'UP' is in bracket summary bracket_match = re.match('.+<([\w,\,]+)>.+', first_line) bracket = bracket_match.group(0) for value in bracket.split(','): if value == 'UP': alive_interfaces.add(interface_name) break return alive_interfaces
def alive_interfaces(): """ Returns a list of all network interfaces which have UP state see ip link show dev eth0 will always return lo in a list if lo exists :return: [] of str """ alive_interfaces = set() try: for interface_name, interface in psutil.net_if_stats().iteritems(): if interface.isup: alive_interfaces.add(interface_name) except: context.log.debug('failed to use psutil.net_if_stats', exc_info=True) # fallback for centos6 for interface_name in netifaces.interfaces(): ip_link_out, _ = subp.call("ip link show dev %s" % interface_name, check=False) if ip_link_out: first_line = ip_link_out[0] r = re.match('.+state\s+(\w+)\s+.*', first_line) if r: state = r.group(1) if interface_name == 'lo' or state == 'UP': alive_interfaces.add(interface_name) return alive_interfaces
def main(): stats = psutil.net_if_stats() io_counters = psutil.net_io_counters(pernic=True) for nic, addrs in psutil.net_if_addrs().items(): print("%s:" % (nic)) if nic in stats: st = stats[nic] print(" stats : ", end='') print("speed=%sMB, duplex=%s, mtu=%s, up=%s" % ( st.speed, duplex_map[st.duplex], st.mtu, "yes" if st.isup else "no")) if nic in io_counters: io = io_counters[nic] print(" incoming : ", end='') print("bytes=%s, pkts=%s, errs=%s, drops=%s" % ( io.bytes_recv, io.packets_recv, io.errin, io.dropin)) print(" outgoing : ", end='') print("bytes=%s, pkts=%s, errs=%s, drops=%s" % ( io.bytes_sent, io.packets_sent, io.errout, io.dropout)) for addr in addrs: print(" %-4s" % af_map.get(addr.family, addr.family), end="") print(" address : %s" % addr.address) if addr.broadcast: print(" broadcast : %s" % addr.broadcast) if addr.netmask: print(" netmask : %s" % addr.netmask) if addr.ptp: print(" p2p : %s" % addr.ptp) print("")
def run(): stats = psutil.net_if_stats() for nic, addrs in psutil.net_if_addrs().items(): print('<div class="panel panel-default">') ut.printTableHeader(nic + ' tarmog`ining xususiyatlari') print('<table class="table">') print('<tr>') ut.printTH('Tezligi') ut.printTH('Duplex') ut.printTH('MTU') ut.printTH('isUp') print('</tr>') print('<tr>') ut.printTD(stats[nic].speed) ut.printTD(duplex_map[stats[nic].duplex]) ut.printTD(stats[nic].mtu) ut.printTD("yes" if stats[nic].isup else "no") print('</tr>') for addr in addrs: print('<tr>') print('<td>') print(" %-8s" % af_map.get(addr.family, addr.family), end="") print('</td>') ut.printTD(" address : %s" % addr.address) ut.printTD(" broadcast : %s" % addr.broadcast) ut.printTD(" netmask : %s" % addr.netmask) print('</tr>') print('</table>') print('</div>')
def getNetworkInfo(cls): interfaces = {} stats = psutil.net_if_stats() for key, value in six.iteritems(stats): interfaces[key] = value.__dict__ interfaces[key]['addresses'] = [] interfaces[key]['io_counters'] = None addresses = psutil.net_if_addrs() for key, value in six.iteritems(addresses): if key not in interfaces: continue for addr in value: interfaces[key]['addresses'].append(addr.__dict__) traffic = psutil.net_io_counters(pernic=True) for key, value in six.iteritems(traffic): if key not in interfaces: continue interfaces[key]['io_counters'] = value.__dict__ return interfaces
def test_parse_only_alive_interfaces(self): container = SystemContainer() container.discover_objects() os_obj = container.objects.values().pop() collector = SystemCommonMetaCollector(object=os_obj) collector.collect() # get interfaces info all_interfaces = netifaces.interfaces() alive_interfaces = set() down_interfaces = set() for interface_name, interface in psutil.net_if_stats().iteritems(): if interface.isup: alive_interfaces.add(interface_name) else: down_interfaces.add(interface_name) # check intefaces collected_interfaces = os_obj.metad.current['network']['interfaces'] for interface_info in collected_interfaces: name = interface_info['name'] assert_that(all_interfaces, has_item(name)) assert_that(alive_interfaces, has_item(name)) assert_that(down_interfaces, not_(has_item(name)))
def test_parse_only_alive_interfaces(self): container = SystemManager() container._discover_objects() os_obj = container.objects.find_all(types=container.types)[0] collector = SystemMetaCollector(object=os_obj) collector.collect() # get interfaces info all_interfaces = netifaces.interfaces() alive_interfaces = set() down_interfaces = set() for interface_name, interface in psutil.net_if_stats().iteritems(): if interface.isup: alive_interfaces.add(interface_name) else: down_interfaces.add(interface_name) # check interfaces collected_interfaces = os_obj.metad.current['network']['interfaces'] for interface_info in collected_interfaces: assert_that(interface_info, has_key('name')) assert_that(interface_info, has_key('mac')) assert_that(interface_info, has_key('ipv4')) ipv4 = interface_info['ipv4'] assert_that(ipv4, has_key('netmask')) assert_that(ipv4, has_key('address')) assert_that(ipv4, has_key('prefixlen')) name = interface_info['name'] assert_that(all_interfaces, has_item(name)) assert_that(alive_interfaces, has_item(name)) assert_that(down_interfaces, not_(has_item(name)))
def net_if_stats(): name = ['isup', 'duplex', 'speed', 'mtu'] r = dict() for key, value in psutil.net_if_stats().iteritems(): r[key] = dict(zip(name, value)) return r
def test_net_if_addrs(self): nics = psutil.net_if_addrs() assert nics, nics nic_stats = psutil.net_if_stats() # Not reliable on all platforms (net_if_addrs() reports more # interfaces). # self.assertEqual(sorted(nics.keys()), # sorted(psutil.net_io_counters(pernic=True).keys())) families = set([socket.AF_INET, socket.AF_INET6, psutil.AF_LINK]) for nic, addrs in nics.items(): self.assertIsInstance(nic, str) self.assertEqual(len(set(addrs)), len(addrs)) for addr in addrs: self.assertIsInstance(addr.family, int) self.assertIsInstance(addr.address, str) self.assertIsInstance(addr.netmask, (str, type(None))) self.assertIsInstance(addr.broadcast, (str, type(None))) self.assertIn(addr.family, families) if sys.version_info >= (3, 4): self.assertIsInstance(addr.family, enum.IntEnum) if nic_stats[nic].isup: # Do not test binding to addresses of interfaces # that are down if addr.family == socket.AF_INET: s = socket.socket(addr.family) with contextlib.closing(s): s.bind((addr.address, 0)) elif addr.family == socket.AF_INET6: info = socket.getaddrinfo( addr.address, 0, socket.AF_INET6, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0] af, socktype, proto, canonname, sa = info s = socket.socket(af, socktype, proto) with contextlib.closing(s): s.bind(sa) for ip in (addr.address, addr.netmask, addr.broadcast, addr.ptp): if ip is not None: # TODO: skip AF_INET6 for now because I get: # AddressValueError: Only hex digits permitted in # u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0' if addr.family != socket.AF_INET6: check_net_address(ip, addr.family) # broadcast and ptp addresses are mutually exclusive if addr.broadcast: self.assertIsNone(addr.ptp) elif addr.ptp: self.assertIsNone(addr.broadcast) if BSD or OSX or SUNOS: if hasattr(socket, "AF_LINK"): self.assertEqual(psutil.AF_LINK, socket.AF_LINK) elif LINUX: self.assertEqual(psutil.AF_LINK, socket.AF_PACKET) elif WINDOWS: self.assertEqual(psutil.AF_LINK, -1)
def get_invalid_net_card(): temp_list = list() info = psutil.net_if_stats() for k, v in info.items(): # print("k = {0}, v = {1}".format(k, v)) if v[0]: temp_list.append(k) return temp_list
def test_net_if_stats(self): for name, stats in psutil.net_if_stats().items(): try: out = sh("ifconfig %s" % name) except RuntimeError: pass else: self.assertEqual(stats.isup, 'RUNNING' in out, msg=out) self.assertEqual(stats.mtu, int(re.findall(r'mtu (\d+)', out)[0]))
def get_if(): io = psutil.net_io_counters(pernic=True) IF = psutil.net_if_stats() if_info = dict() for i in io: info = obj2dict(io[i]) if i in IF: info.update(obj2dict(IF[i])) if_info[i] = info return if_info
def test_net_if_stats(self): nics = psutil.net_if_stats() assert nics, nics all_duplexes = (psutil.NIC_DUPLEX_FULL, psutil.NIC_DUPLEX_HALF, psutil.NIC_DUPLEX_UNKNOWN) for nic, stats in nics.items(): isup, duplex, speed, mtu = stats self.assertIsInstance(isup, bool) self.assertIn(duplex, all_duplexes) self.assertIn(duplex, all_duplexes) self.assertGreaterEqual(speed, 0) self.assertGreaterEqual(mtu, 0)
def get_network_info(): addresses = psutil.net_if_addrs() stats = psutil.net_if_stats() dict = {} for name in addresses: mac_address = getHwAddr(name) ip_address = addresses[name][0][1] speed = stats[name][2] / 1000.0 link = stats[name][0] dict[name] = {"mac_address": mac_address, "ip_address": ip_address, \ "speed": speed, "link": link} return dict
def interfaces(): return { 'addrs': { x:[ { k:v for k,v in z.__dict__.iteritems() } for z in y ] for x,y in psutil.net_if_addrs().iteritems() }, 'stats': { x:{ k:v for k,v in y.__dict__.iteritems() } for x,y in psutil.net_if_stats().iteritems() } }
def test_collect_each_interface_once(self): container = SystemManager() container._discover_objects() os_obj = container.objects.find_all(types=container.types)[0] collector = SystemMetaCollector(object=os_obj) num_interfaces = len(psutil.net_if_stats()) for x in xrange(3): collector.collect() collected_interfaces = os_obj.metad.current['network']['interfaces'] assert_that(collected_interfaces, only_contains(contains_inanyorder('mac', 'name', 'ipv4', 'ipv6'))) assert_that(collected_interfaces, has_length(num_interfaces))
def refreshNetworkTraffic(self): excluded_interfaces = set(["lo", 'br-lan', 'docker0', 'wlan0']) interfaces = {} stats = psutil.net_if_stats() for key, value in six.iteritems(stats): if key in excluded_interfaces: continue # ignore virtual ethernet interfaces if key.startswith('veth'): continue # Quick fix - ignore interfaces with dots because our server # refuses to accept keys with dots. if '.' in key: continue interfaces[key] = { 'isup': value.isup, 'speed': value.speed, 'mtu': value.mtu } addresses = psutil.net_if_addrs() for key, value in six.iteritems(addresses): if key not in interfaces: continue for i in value: if i.family == 2: interfaces[key]['ipv4'] = i.address interfaces[key]['netmask'] = i.netmask elif i.family == 17: interfaces[key]['mac'] = i.address traffic = psutil.net_io_counters(pernic=True) for key, value in six.iteritems(traffic): if key not in interfaces: continue interfaces[key]['bytes_sent'] = value.bytes_sent interfaces[key]['bytes_recv'] = value.bytes_recv interfaces[key]['packets_sent'] = value.packets_sent interfaces[key]['packets_recv'] = value.packets_recv interfaces[key]['errin'] = value.errin interfaces[key]['errout'] = value.errout interfaces[key]['dropin'] = value.dropin interfaces[key]['dropout'] = value.dropout self.network = interfaces
def _run(self): """ Runs the data collection. :return: """ self.logger.info( "Running the data collection." ) # Get Addreses address = psutil.net_if_addrs() # Get stats stats = psutil.net_if_stats() # Set the data template = self.get_template() data = template['data'] data['ifaddrs'].update( { 'ifaddrs' : address, } ) data = template['data'] data['ifstats'].update( { 'ifstats' : stats, } ) template['data'].update( { 'data' : data } ) # Update the data self.set_data( template ) self.logger.info( "Data collection complete." ) # Delete the temp objects del template, \ address, \ stats, \ data return
def updateInfoPerSecond(self): self.cpuPercent = psutil.cpu_percent(interval=1, percpu=True) self.ramInfo = psutil.virtual_memory() self.swapInfo = psutil.swap_memory() self.diskParts = psutil.disk_partitions() self.diskPartsUsage = {} for disk in self.diskParts: mnt = disk.mountpoint usage = psutil.disk_usage(mnt) self.diskPartsUsage.update({mnt:usage}) self.oldNetCounters = self.netCounters self.netCounters = psutil.net_io_counters(pernic=True) self.netNicStats = psutil.net_if_stats() self.netStats = {} for nic in self.netCounters.iterkeys(): m = self.netNicStats[nic].speed sent = self.netCounters[nic].bytes_sent recv = self.netCounters[nic].bytes_recv oSent = self.oldNetCounters[nic].bytes_sent oRecv = self.oldNetCounters[nic].bytes_recv sent = (sent-oSent)*8 recv = (recv-oRecv)*8 try: pr = recv/(m*1000.0) except ZeroDivisionError: pr = 0 try: ps = sent/(m*1000.0) except ZeroDivisionError: ps = 0 self.netStats.update({nic:{'sent':sent, 'recv':recv, 's_per':ps, 'r_per':pr}}) self.sensors = [] for c in sensors.iter_detected_chips(): for f in c: self.sensors.append(f.get_value()) self.raid = {} self.raid = readRaid() #fetches the data from hddtemp #self.hdd = {} try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost',7634)) data = s.recv(4096) s.close() parts = data.split('|') for i in range(1,len(parts),5): self.hdd[parts[i].split('/dev/')[1]] = int(parts[i+2]) except: pass
def get_computer_stats(self): cpu_usage = psutil.cpu_percent(interval=0.5) # Gets the CPU usage memory = psutil.virtual_memory() # Gets statistics about different memories memory_usage = (100 * memory.free / memory.total) # Calculates the percentage of free memory network_speed = psutil.net_if_stats() # Gets speeds of different networks network_usage = psutil.net_io_counters(pernic=True) # Gets packet usage in different networks in the computer counter = 0 net = "" for network in network_usage: if network_usage[network].packets_sent > counter: # If a packet was sent through the network, it is the computer's main network. counter = network_usage[network].packets_sent net = network speed = network_speed[net].speed # Get the speed of the network self.profile = str(self.calculate_profile(cpu_usage, memory_usage, speed)) # Calculate the profile and update your information return self.profile
def main(): stats = psutil.net_if_stats() for nic, addrs in psutil.net_if_addrs().items(): if nic in stats: print("%s (speed=%sMB, duplex=%s, mtu=%s, up=%s):" % ( nic, stats[nic].speed, duplex_map[stats[nic].duplex], stats[nic].mtu, "yes" if stats[nic].isup else "no")) else: print("%s:" % (nic)) for addr in addrs: print(" %-8s" % af_map.get(addr.family, addr.family), end="") print(" address : %s" % addr.address) if addr.broadcast: print(" broadcast : %s" % addr.broadcast) if addr.netmask: print(" netmask : %s" % addr.netmask) print("")
def get_active_nic_name(): '''取得本机对外活跃的网卡名称,linux适用''' all_nic=psutil.net_if_stats()#取得本机所有网卡名称 nic_names=all_nic.keys() try: all_nic.pop('docker0') except: pass try: all_nic.pop('lo') except: pass return all_nic pass
def get_net_info(): net_map = {} duplex_dict = { psutil.NIC_DUPLEX_FULL: 'FULL', psutil.NIC_DUPLEX_HALF: 'HALF', psutil.NIC_DUPLEX_UNKNOWN: 'UNKNOWN' } stats = {} for k, state in psutil.net_if_stats().items(): stats[k] = {'isup': state.isup, 'duplex': duplex_dict[state.duplex], 'speed': state.speed, 'mtu': state.mtu} net_map['status'] = stats family_dict = { socket.AF_INET: 'AF_INET', socket.AF_INET6: 'AF_INET6', socket.AF_UNIX: 'AF_UNIX', socket.AF_APPLETALK: 'AF_APPLETALK', socket.AF_IPX: 'AF_IPX', socket.AF_DECnet: 'AF_DECnet', socket.AF_ROUTE: 'AF_ROUTE', socket.AF_SNA: 'AF_SNA', socket.AF_UNSPEC: 'AF_UNSPEC', psutil.AF_LINK: 'AF_LINK', } addr_dict = defaultdict(list) for k, addrs in psutil.net_if_addrs().items(): addr_dict[k] += [{'family': family_dict.get(addr.family), 'addr': addr.address, 'netmask': addr.netmask, 'broadcast': addr.broadcast} for addr in addrs] net_map['address'] = addr_dict counters = psutil.net_io_counters() net_map['counters'] = { 'bytes_send': format_memory(counters.bytes_sent), 'bytes_recv': format_memory(counters.bytes_recv), 'package_sent': counters.packets_sent, 'package_recv': counters.packets_recv, } return net_map
def run(self): ignored_ifaces = self._conf.get('ignored', ['lo']) data = dict((k, v._asdict()) for k, v in psutil.net_io_counters(True).items() if k not in ignored_ifaces) ifaces_stats = dict((k, v._asdict()) for k, v in psutil.net_if_stats().items() if k not in ignored_ifaces) ifaces_down = [k for k, v in ifaces_stats.items() if not v['isup']] bad_interfaces = dict(filter(self._iface_is_bad, data.items())) problems = [] if ifaces_down: problems.append("The following interfaces are down: %s" % ",".join(ifaces_down)) if bad_interfaces: problems.append("The following NICs appear to have issues: %s\n" "Please note that ifconfig counters need to be reset in order to avoid detecting old errors" % ", ".join(bad_interfaces.keys())) return dict(problem="\n".join(problems), extra_info=data)
def net_if_stat_info(self): ''' Note: Get nic info. net_if_stat_dict: :return: dict type { nic_name: [isup, duplex, speed, mtu] ...... } ''' net_if_stat_dict = defaultdict(list) net_if_stat = psutil.net_if_stats() for i in net_if_stat: net_if_stat_dict[i].append(net_if_stat[i].isup) net_if_stat_dict[i].append(net_if_stat[i].duplex) net_if_stat_dict[i].append(net_if_stat[i].speed) net_if_stat_dict[i].append(net_if_stat[i].mtu) return net_if_stat_dict
def __init__(self, outfile_pattern='netstat.{nic}.csv', nics=[], flush=False): print('NIC monitor started.', file=sys.stderr) all_nics = psutil.net_if_stats() self.nic_files = dict() self.flush = flush for nic_name in nics: nic_name = nic_name.strip() if nic_name not in all_nics: print('Error: NIC "%s" does not exist. Skip.' % nic_name, file=sys.stderr) else: self.nic_files[nic_name] = self.create_new_logfile(outfile_pattern, nic_name) if len(self.nic_files) == 0: raise ValueError('No NIC to monitor.') self.prev_stat = dict() for nic, stat in psutil.net_io_counters(pernic=True).items(): if nic in self.nic_files: self.prev_stat[nic] = stat self.starttime = int(time.time()) self.poll_stat()
def _get_cali_veth_stat(self): ''' Check the status of all network interfaces. Value is 1 if any one of them is DOWN ''' cali_veth_up = 0 cali_veth_down = 0 cali_veth_total = 0 tmp_veth_up = 0 tmp_veth_down = 0 tmp_veth_total = 0 for name, stat in psutil.net_if_stats().iteritems(): if name.startswith('cali'): cali_veth_total += 1 if stat.isup: cali_veth_up += 1 else: cali_veth_down += 1 elif name.startswith('tmp'): tmp_veth_total += 1 if stat.isup: tmp_veth_up += 1 else: tmp_veth_down += 1 self._result.append( GraphiteData("lain.cluster.calico.veth.cali.up", self._endpoint, cali_veth_up, self._step, "val")) self._result.append( GraphiteData("lain.cluster.calico.veth.cali.down", self._endpoint, cali_veth_down, self._step, "val")) self._result.append( GraphiteData("lain.cluster.calico.veth.cali.total", self._endpoint, cali_veth_total, self._step, "val")) self._result.append( GraphiteData("lain.cluster.calico.veth.tmp.up", self._endpoint, tmp_veth_up, self._step, "val")) self._result.append( GraphiteData("lain.cluster.calico.veth.tmp.down", self._endpoint, tmp_veth_down, self._step, "val")) self._result.append( GraphiteData("lain.cluster.calico.veth.tmp.total", self._endpoint, tmp_veth_total, self._step, "val"))
def find_default_interface(self): """Look through the list of interfaces for the non-loopback interface""" import psutil try: if self.interfaces is None: self.interfaces = {} # Look to see which interfaces are up stats = psutil.net_if_stats() for interface in stats: if interface != 'lo' and interface[:3] != 'ifb' and stats[ interface].isup: self.interfaces[interface] = {'packets': 0} if len(self.interfaces) > 1: # See which interfaces have received data cnt = psutil.net_io_counters(True) for interface in cnt: if interface in self.interfaces: self.interfaces[interface]['packets'] = \ cnt[interface].packets_sent + cnt[interface].packets_recv remove = [] for interface in self.interfaces: if self.interfaces[interface]['packets'] == 0: remove.append(interface) if len(remove): for interface in remove: del self.interfaces[interface] if len(self.interfaces) > 1: # Eliminate any with the loopback address remove = [] addresses = psutil.net_if_addrs() for interface in addresses: if interface in self.interfaces: for address in addresses[interface]: if address.address == '127.0.0.1': remove.append(interface) break if len(remove): for interface in remove: del self.interfaces[interface] except Exception: logging.exception('Error finding default interface')
def __queryNetworkStats(self): ifStatDict = psutil.net_if_stats() if not ifStatDict: return [] ifAddrDict = psutil.net_if_addrs() stats = [] for nic, ifStat in ifStatDict.items(): stat = NetworkStat() stat.nic = nic stat.isUp = ifStat.isup stat.duplex = NicDuplexType.fromPsutil(ifStat.duplex) stat.speed = ifStat.speed stat.mtu = ifStat.mtu ifAddrs = ifAddrDict[nic] addrs = [] for ifAddr in ifAddrs: addrs.append((ifAddr.family, ifAddr.address, ifAddr.netmask, ifAddr.broadcast, ifAddr.ptp)) stat.addrs = addrs stats.append(stat) return stats
def network(): network_stat = {} # 网卡基本信息 net_if_stats = psutil.net_if_stats() # 网络io信息 net_io_counters = psutil.net_io_counters(pernic=True) for i in net_if_stats: speed = net_if_stats[i][2] # 有速率的网卡是物理网卡,链路聚合的网卡状况未知 # 有的网卡速率是65535的 # 非物理网卡则跳过 if speed == 0 or speed % 10 != 0: continue network_stat[i] = {} network_stat[i]['speed'] = speed network_stat[i]['bytes_sent'] = net_io_counters[i].bytes_sent network_stat[i]['bytes_recv'] = net_io_counters[i].bytes_recv network_stat[i]['packets_sent'] = net_io_counters[i].packets_sent network_stat[i]['packets_recv'] = net_io_counters[i].packets_recv global static static['network'] = network_stat
def __init__(self, outfile_pattern='netstat.{nic}.csv', nics=[], flush=False): print('NIC monitor started.', file=sys.stderr) all_nics = psutil.net_if_stats() self.nic_files = dict() self.flush = flush for nic_name in nics: nic_name = nic_name.strip() if nic_name not in all_nics: print('Error: NIC "%s" does not exist. Skip.' % nic_name, file=sys.stderr) else: self.nic_files[nic_name] = self.create_new_logfile( outfile_pattern, nic_name) if len(self.nic_files) == 0: raise ValueError('No NIC to monitor.') self.prev_stat = dict() for nic, stat in psutil.net_io_counters(pernic=True).items(): if nic in self.nic_files: self.prev_stat[nic] = stat self.starttime = int(time.time()) self.poll_stat()
def collect_system_information(self): values = {} mem = psutil.virtual_memory() values['memory_total'] = mem.total import cpuinfo cpu = cpuinfo.get_cpu_info() values['resources_limit'] = self.resources_limit values['cpu_name'] = cpu['brand'] values['cpu'] = [cpu['hz_advertised_raw'][0], cpu['count']] values['nets'] = {} values['disks'] = {} values['gpus'] = {} values['boot_time'] = psutil.boot_time() try: for gpu_id, gpu in enumerate(aetros.cuda_gpu.get_ordered_devices()): gpu['available'] = gpu_id in self.enabled_gpus values['gpus'][gpu_id] = gpu except Exception: pass for disk in psutil.disk_partitions(): try: name = self.get_disk_name(disk[1]) values['disks'][name] = psutil.disk_usage(disk[1]).total except Exception: # suppress Operation not permitted pass try: for id, net in psutil.net_if_stats().items(): if 0 != id.find('lo') and net.isup: self.nets.append(id) values['nets'][id] = net.speed or 1000 except Exception: # suppress Operation not permitted pass return values
def getLocalNetworkInterfaces(): # # Methode haalt lokale netwerk interfaces op (getest op macOS) # Methods gets local network interfaces (tested on macOS) # stats = psutil.net_if_stats() io_counters = psutil.net_io_counters(pernic=True) ip_addresses = [] for nic, addrs in psutil.net_if_addrs().items(): hasBroadcastAddress = False #print(nic) for addr in addrs: if addr.broadcast != None: hasBroadcastAddress = True if (hasBroadcastAddress == True): _if = nic _ip = "" _nm = "" _ma = "" _gw = "" for addr in addrs: #print(addr.family) if (str(addr.family) == "AddressFamily.AF_INET"): _ip = str(addr.address) _nm = str(addr.netmask) if (str(addr.family) == "AddressFamily.AF_LINK"): _ma = str(addr.address) _gw = find_gateway(nic).ip _nic = NIC(_if, _ip, _nm, _ma, _gw) if (_ip != ""): ip_addresses.append(_nic) return ip_addresses
def print_network(): af_map = { socket.AF_INET: 'IPv4', socket.AF_INET6: 'IPv6', psutil.AF_LINK: 'MAC', } duplex_map = { psutil.NIC_DUPLEX_FULL: "full", psutil.NIC_DUPLEX_HALF: "half", psutil.NIC_DUPLEX_UNKNOWN: "?", } stats = psutil.net_if_stats() io_counters = psutil.net_io_counters(pernic=True) for nic, addresses in psutil.net_if_addrs().items(): print("%s:" % nic) if nic in stats: st = stats[nic] print(" Параметры : ", end='') print("скорость=%sMB, дуплекс=%s, mtu=%s, up=%s" % (st.speed, duplex_map[st.duplex], st.mtu, "yes" if st.isup else "no")) if nic in io_counters: io = io_counters[nic] print(" Входящие : ", end='') print("байт=%s, пакет=%s, ошиб=%s, отброш=%s" % (bytes2human( io.bytes_recv), io.packets_recv, io.errin, io.dropin)) print(" Исходящие : ", end='') print("байт=%s, пакет=%s, ошиб=%s, отброш=%s" % (bytes2human( io.bytes_sent), io.packets_sent, io.errout, io.dropout)) for address in addresses: print(" %-4s" % af_map.get(address.family, address.family), end="") print(" Адрес : %s" % address.address) if address.broadcast: print(" Трансляция: %s" % address.broadcast) if address.netmask: print(" Маска подсети : %s" % address.netmask) if address.ptp: print(" p2p : %s" % address.ptp) print("")
def get(): d = {} l = psutil.net_io_counters() aux = {} for i in range(len(l)): aux[l._fields[i]] = l[i] d['net_io_counters'] = aux l = psutil.net_connections() j = 0 for conn in l: aux = {} for i in range(len(conn)): aux[conn._fields[i]] = conn[i] d['net_connection{}'.format(j)] = aux j += 1 d['net_if_addrs'] = psutil.net_if_addrs() d['net_if_stats'] = psutil.net_if_stats() return d
def __post_init__(self): if type(self.monitored_ifaces) == tuple: self.network_interfaces = {i:self._select_iface_data(i) for i in self.monitored_ifaces} else: self.network_interfaces = self._select_iface_data(iface=self.monitored_ifaces) if self.basic == False: for cnt, elt in enumerate(ps.net_connections(), 0): try: l = elt.laddr._asdict() r = elt.raddr._asdict() self.network_connections[f"{cnt}"] = {"target": l, "incoming": r } except: pass for k, v in ps.net_if_stats().items(): if k in self.monitored_ifaces: self.network_interfaces[k]["is_up"] = v.isup self.network_interfaces[k]["nicDuplex"] = v.duplex.value self.network_interfaces[k]["speed"] = v.speed self.network_interfaces[k]["mtu"] = v.mtu
def get_net_info(request): af_map = { socket.AF_INET: 'IPv4', socket.AF_INET6: 'IPv6', psutil.AF_LINK: 'MAC', } duplex_map = { psutil.NIC_DUPLEX_FULL: "full", psutil.NIC_DUPLEX_HALF: "half", psutil.NIC_DUPLEX_UNKNOWN: "unknown", } data = {} net_stats = psutil.net_if_stats() net_addrs = psutil.net_if_addrs() for name, addrs in net_addrs.items(): sub_data = {} st = net_stats[name] sub_data['stats'] = { 'speed': st.speed, 'duplex': duplex_map.get(st.duplex), 'mtu': st.mtu, 'up': 'yes' if st.isup else 'no', } for addr in addrs: addr_data = {} addr_data['address'] = addr.address if addr.broadcast: addr_data['broadcast'] = addr.broadcast if addr.netmask: addr_data['netmask'] = addr.netmask if addr.ptp: addr_data['ptp'] = addr.ptp sub_data[af_map.get(addr.family)] = addr_data data[name] = sub_data response = JsonResponse(data) # response['Access-Control-Allow-Origin'] = '*' return response
def _network(self, now): wifi_icon = '\uf1eb' net_icon = '\uf0e8' # (this is actually the sitemap icon) vpn_icon = '\uf023' # lock icon, try to find a better one later stats = psutil.net_if_stats() default_gateway_interface = self._get_default_gateway_interface() for k, interface in stats.items(): if k == default_gateway_interface or (not default_gateway_interface and interface.isup): addrs = psutil.net_if_addrs()[k] download, upload = self._compute_nic_throughput(k, now) return { 'name': 'network', 'markup': 'pango', 'full_text': ('{} {} ' '<span foreground="#0e93cb">\uf019</span> {} ' '<span foreground="#0e93cb">\uf093</span> {}').format( net_icon, addrs[0].address, download, upload) }
def Get_Net_Info(self): '''获取网卡名字''' all_inter = psutil.net_if_stats() all_inter_info = {} for i in all_inter: per_net_info = {} '''获取单个网卡第一次接受和发送的总流量(bytes)''' first_net_sent = psutil.net_io_counters(pernic=True)[i].bytes_sent first_net_recv = psutil.net_io_counters(pernic=True)[i].bytes_recv time.sleep(0.5) '''获取单个网卡第二次接受和发送的总流量(bytes)''' current_net_sent = psutil.net_io_counters( pernic=True)[i].bytes_sent current_net_recv = psutil.net_io_counters( pernic=True)[i].bytes_recv per_net_info['net_sent'] = (current_net_sent - first_net_sent) * 2 per_net_info['net_recv'] = (current_net_recv - first_net_recv) * 2 all_inter_info[i] = per_net_info return json.dumps(all_inter_info)
def __init__(self, parent): super(QWidget, self).__init__(parent) layout = QFormLayout() print(parent) self.parent = parent addressLabel = QLabel("Address") # addressLine = QLineEdit() # addressLine.setText(str(ip)) # layout.addRow (addressLabel,addressLine) addressList = QComboBox() addresses = psutil.net_if_addrs() print(addresses) stats = psutil.net_if_stats() print(stats) available_networks = [] for intface, addr_list in addresses.items(): if any( getattr(addr, 'address').startswith("169.254") for addr in addr_list): continue elif intface in stats and getattr(stats[intface], "isup"): for addr in addr_list: addressList.addItem(getattr(addr, 'address')) addressList.activated[str].connect(self.onChanged) layout.addRow(addressLabel, addressList) portLabel = QLabel("Port") portLine = QLineEdit() portLine.setText(str(self.parent.port)) portLine.textChanged.connect(self.textChanged) layout.addRow(portLabel, portLine) prefixLabel = QLabel("Prefix") prefixLine = QLineEdit() layout.addRow(prefixLabel, prefixLine) self.setLayout(layout)
def guess_external_netiface_name() -> str: """Tries to retrieve the name of the external network interface. To do so, this function select the first returned network interface whose name suggest to be an Ethernet or wireless interface (``en*``, ``eth*`` or ``wl*``) and which appears to be connected to a full-duplex medium. :raise VirtualizedEnvironmentError: if no external network inteface could be guessed and no dummy value has been provided """ iface_name_pattern = re.compile(r'(en|eth|wl).*') if_stats: Dict[str, psutil._common.snicstats] = psutil.net_if_stats() for iface, stats in if_stats.items(): if not iface_name_pattern.fullmatch(iface): continue if stats.duplex == psutil.NIC_DUPLEX_FULL: return iface else: raise VirtualizedEnvironmentError(line( """Could not guess any potential external network interface on the current system."""))
def take_device(print_output: bool = True) -> Tuple[str]: """ Определение вафли """ global device devices = [line for line in psutil.net_if_stats()] device_list = [ line for line in devices if line != 'lo' and "enp" not in line ] if len(device_list) == 1: device = device_list[0] return device elif len(device_list) == 0: print_arr("Ошибка: Не обнаружено ни одного молуля!", color="red") raise SystemExit(1) else: device_arg = __init__.args.device if device_arg is not False: # Если был введен аргумент --device if device_arg not in device_list: # если пользователь ошибся print_arr(f"Модуль {device_arg} не найден!", color="yellow") device = input_list( "Обнаружено несколько модулей" " WI-FI, выберите нужный!", device_list, # Список с модулями color="yellow") else: # Если все норм device = device_arg elif device_arg is False: # Если аргумента непоследовало if print_output is True: device = input_list( "Обнаружено несколько модулей" " WI-FI, выберите нужный!", device_list, # Список с модулями color="yellow") return device
def collect_system_information(self): values = {} mem = psutil.virtual_memory() values['memory_total'] = mem.total import cpuinfo cpu = cpuinfo.get_cpu_info() values['cpu_name'] = cpu['brand'] values['cpu'] = [cpu['hz_actual_raw'][0], cpu['count']] values['nets'] = {} values['disks'] = {} values['gpus'] = [] values['boot_time'] = psutil.boot_time() try: for i in range(0, aetros.cuda_gpu.get_installed_devices()): values['gpus'].append(aetros.cuda_gpu.get_device_properties(i)) except: pass for disk in psutil.disk_partitions(): try: name = self.get_disk_name(disk[1]) values['disks'][name] = psutil.disk_usage(disk[1]).total except: # suppress Operation not permitted pass try: for id, net in psutil.net_if_stats().items(): if 0 != id.find('lo') and net.isup: self.nets.append(id) values['nets'][id] = net.speed or 1000 except: # suppress Operation not permitted pass return values
def gravando_dados(): #Buscando porcentagem de uso da CPU Uso_CPU_Percentual = psutil.cpu_percent(interval=None) #Buscando informações da memoria RAM RAM = psutil.virtual_memory() RAM_Percentual = RAM.percent #Buscando informações do disco Disco = psutil.disk_usage('/') Disco_Percentual = Disco.percent #Buscando informações da bateria Bateria = psutil.sensors_battery() #Buscando percentual da bateria Bateria_Percentual = Bateria.percent #Buscando tempo de duração da bateria if str(Bateria.secsleft) == 'BatteryTime.POWER_TIME_UNLIMITED': Bateria_Duracao = "Duração Infinita" else: Bateria_Duracao = (Bateria.secsleft / 60) Bateria_Duracao = str(Bateria_Duracao) + 'Minutos' #Buscando se a bataria está conectado a fonte if str(Bateria.power_plugged) == 'False': Bateria_Status = "Descarregando" else: Bateria_Status = "Carregando" #Buscando Status de conexão de rede Rede = psutil.net_if_stats()['Ethernet'] if str(Rede.isup) == 'True': Conectado_Rede = "Online" else: Conectado_Rede = "Offline" #Enviando dados para o MySql mycursor = mydb.cursor() sql = 'INSERT INTO dados_coletados(Uso_CPU_Percentual, RAM_Percentual, Disco_Percentual, Bateria_Percentual, Bateria_Duracao, Bateria_Status, Conectado_Rede) VALUES (%s, %s, %s, %s, %s, %s, %s )' sql_data = (Uso_CPU_Percentual, RAM_Percentual, Disco_Percentual, Bateria_Percentual, Bateria_Duracao, Bateria_Status, Conectado_Rede) mycursor.execute(sql, sql_data) mydb.commit()
def get_network_interface_names() -> List[str]: """Returns a list of network interfaces available on the system Args: Returns: A list of network interfaces """ addresses = psutil.net_if_addrs() stats = psutil.net_if_stats() available_networks = [] for intface, addr_list in addresses.items(): if any(getattr(addr, 'address').startswith("169.254") for addr in addr_list): continue elif intface.startswith('lo'): continue elif intface.startswith('veth'): continue elif intface.startswith('br-'): continue elif intface in stats and getattr(stats[intface], "isup"): available_networks.append(intface) return available_networks
def __init__(self, widget_manager, info): # init Widget.__init__(self, widget_manager, info) QWidget.__init__(self) self.conf = {} self.lang = info.lang self.settings_win = None # setup layout self.setLayout(QVBoxLayout(self)) self.layout().setContentsMargins(0, 0, 0, 0) # setup stylesheet with open(os.path.join(RES, 'net_stat', 'style.css'), encoding='utf-8') as file: style = file.read() self.setStyleSheet(style) self.setAttribute(Qt.WA_TranslucentBackground) # setup timer self.timer = QTimer(self) self.timer.timeout.connect(self.setup_ui) # setup vars self.stats = psutil.net_if_stats() self._widgets = [] self._setup_vars()
def collect_system_information(self): values = {} mem = psutil.virtual_memory() values['memory_total'] = mem.total import cpuinfo cpu = cpuinfo.get_cpu_info() values['cpu_name'] = cpu['brand'] values['cpu'] = [cpu['hz_actual_raw'][0], cpu['count']] values['nets'] = {} values['disks'] = {} values['boot_time'] = psutil.boot_time() for disk in psutil.disk_partitions(): name = self.get_disk_name(disk[1]) values['disks'][name] = psutil.disk_usage(disk[1]).total for id, net in psutil.net_if_stats().items(): if 0 != id.find('lo') and net.isup: self.nets.append(id) values['nets'][id] = net.speed or 1000 return values
def get_nics(): nics = {} stats = psutil.net_if_stats() for nic in stats: if nic in ["lo", "sit0"] or not stats[nic].isup: continue nics[nic] = {} addrs = psutil.net_if_addrs() for nic, values in addrs.items(): if not nic in nics: continue addr = None for value in values: if value.family == AF_INET: addr = value.address if not addr: del nics[nic] continue nics[nic]["addr"] = values[0].address return nics
def captureNetworkInterfaces(): logPath = str('networkInterfaces.log') f = open(logPath, 'a') f.write("\n\n" + separator + "\n") f.write(time.ctime() + "\n") stats = psutil.net_if_stats() io_counters = psutil.net_io_counters(pernic=True) for nic, addrs in psutil.net_if_addrs().items(): f.write("\n%s:" % (nic)) if nic in stats: st = stats[nic] f.write("\n stats: ") f.write("\tspeed=%sMB, duplex=%s, mtu=%s, up=%s" % (st.speed, duplex_map[st.duplex], st.mtu, "yes" if st.isup else "no")) if nic in io_counters: io = io_counters[nic] f.write("\n incoming: ") f.write("\tbytes=%s, pkts=%s, errs=%s, drops=%s" % (bytes2human( io.bytes_recv), io.packets_recv, io.errin, io.dropin)) f.write("\n outgoing: ") f.write("\tbytes=%s, pkts=%s, errs=%s, drops=%s" % (bytes2human( io.bytes_sent), io.packets_sent, io.errout, io.dropout)) for addr in addrs: f.write("\n %-4s" % af_map.get(addr.family, addr.family)) f.write("address : %s" % addr.address) if addr.broadcast: f.write("\n broadcast : %s" % addr.broadcast) if addr.netmask: f.write("\n netmask : %s" % addr.netmask) if addr.ptp: f.write("\n p2p : %s" % addr.ptp) f.close()
def netinit(self): self.netNameList=[] temp=ps.net_if_stats() for name in temp: if name !='lo' and temp[name][0]==True: self.netNameList.append(name) # print('working ') # print(self.netNameList) if len(self.netNameList)!=0: self.netWidgetList={} self.netstate1=[] self.netReceiveArray=[] self.netSendArray=[] self.numOfNets=len(self.netNameList) #number of internet adapters # print(self.numOfNets) for i in range(0,self.numOfNets): self.netWidgetList[i]=networkWidget() self.performanceStack.add_titled(self.netWidgetList[i],'netStack'+str(i),'Network'+str(i)) self.netWidgetList[i].nettextlabel.set_text(self.netNameList[i]) ##self.netWidgetList[i].netinfolabel.set_text(self.netsize[i]) ###change for the name nettemp=ps.net_io_counters(pernic=True) self.nett1=time() for adpts in nettemp: if adpts==self.netNameList[i]: self.netstate1.append(nettemp[adpts]) self.netReceiveArray.append([0]*100) self.netSendArray.append([0]*100) self.netWidgetList[i].givedata(self,i) # print('give dat') else: print("Net:No active network adapter found") self.numOfNets=0
def getnetworks(): """Endpoint to get information regarding netios Returns: json object of information containing packet transfers happening over the network """ if not check_auth(request): return "404", 404 try: data = [] oldnetio = psutil.net_io_counters(pernic=True) time.sleep(1) newnetio = psutil.net_io_counters(pernic=True) addrs = psutil.net_if_addrs() stats = psutil.net_if_stats() for key in oldnetio: ipv4 = '_' ipv6 = '_' try: for ad in addrs[key]: if str(ad.family) == 'AddressFamily.AF_INET': ipv4 = ad.address if str(ad.family) == 'AddressFamily.AF_INET6': ipv6 = ad.address isup = "yes" if stats[key].isup else "no" oldnetwork = oldnetio[key] newnetwork = newnetio[key] sent = (newnetwork.bytes_sent - oldnetwork.bytes_sent) / 1024 receive = (newnetwork.bytes_recv - oldnetwork.bytes_recv) / 1024 net = {"name": key, "sent": sent, "receive": receive, "isup": isup, "ipv4": ipv4, "ipv6": ipv6} data.append(net) except Exception as e: print('key' + str(e)) return jsonify(data=data), 200 except Exception as e: print(e) return "404", 404
def save_system_info(): # System Info Variables # CPU cpu_percent_overall = psutil.cpu_percent(percpu = False) cpu_percent_list = psutil.cpu_percent(percpu = True) cpu_stats = psutil.cpu_stats() cpu_load_tuple = [x / psutil.cpu_count() * 100 for x in psutil.getloadavg()] # Memory mem_virtual = psutil.virtual_memory() mem_virtual_total = mem_virtual.total mem_virtual_available = mem_virtual.available mem_virtual_used = mem_virtual.used # Disks disk_partitions = psutil.disk_partitions(all = False) disk_usage = [None] * len(disk_partitions) for i, partition in enumerate(disk_partitions): if os.name == 'nt': if 'cdrom' in partition.opts or partition.fstype == '': # skip cd-rom drives with no disk in it; they may raise # ENOENT, pop-up a Windows GUI error for a non-ready # partition or just hang. continue disk_usage[i] = psutil.disk_usage(partition.mountpoint) disk_io_counters = psutil.disk_io_counters(perdisk = True) # Network net_io_counters = psutil.net_io_counters(pernic = True) net_connections = psutil.net_connections() net_if_addrs = psutil.net_if_addrs() net_if_stats = psutil.net_if_stats() # Sensors # TODO: Add check if OS is Linux or FreeBSD # sensors_temperatures = psutil.sensors_temperatures(fahrenheit = False) # sensors_fans = psutil.sensors_fans() sensors_battery = psutil.sensors_battery() # Other boot_time = psutil.boot_time() users = psutil.users()
def getnetworks(): """Docstring. Returns: TYPE: Description """ try: data = [] oldnetio = psutil.net_io_counters(pernic=True) time.sleep(1) newnetio = psutil.net_io_counters(pernic=True) addrs = psutil.net_if_addrs() stats = psutil.net_if_stats() for key in oldnetio: ipv4 = '_' ipv6 = '_' try: for ad in addrs[key]: if str(ad.family) == 'AddressFamily.AF_INET': ipv4 = ad.address if str(ad.family) == 'AddressFamily.AF_INET6': ipv6 = ad.address isup = "yes" if stats[key].isup else "no" oldnetwork = oldnetio[key] newnetwork = newnetio[key] sent = (newnetwork.bytes_sent - oldnetwork.bytes_sent) / 1024 receive = (newnetwork.bytes_recv - oldnetwork.bytes_recv) / 1024 net = {"name": key, "sent": sent, "receive": receive, "isup": isup, "ipv4": ipv4, "ipv6": ipv6} data.append(net) except Exception as e: print('key' + str(e)) return jsonify(data=data), 200 except Exception as e: print(e) return "404", 404
def net(self): addrs = psutil.net_if_addrs() addrs_info = { k: [ dict(family=val.family.name, address=val.address, netmask=val.netmask, broadcast=val.broadcast) for val in v if val.family.name == 'AF_INET' ][0] for k, v in addrs.items() } io = psutil.net_io_counters(pernic=True) status = psutil.net_if_stats() data = { addrs_info[k]['address']: dict(name=k, bytes_sent=v.bytes_sent, bytes_recv=v.bytes_recv, packets_sent=v.packets_sent, packets_recv=v.packets_recv, **addrs_info[k]) for k, v in io.items() if status[k].isup == True } return data
def run(self): ignored_ifaces = self._conf.get('ignored', ['lo']) data = dict((k, v._asdict()) for k, v in psutil.net_io_counters(True).items() if k not in ignored_ifaces) ifaces_stats = dict((k, v._asdict()) for k, v in psutil.net_if_stats().items() if k not in ignored_ifaces) ifaces_down = [k for k, v in ifaces_stats.items() if not v['isup']] bad_interfaces = dict(filter(self._iface_is_bad, data.items())) problems = [] if ifaces_down: problems.append("The following interfaces are down: %s" % ",".join(ifaces_down)) if bad_interfaces: problems.append( "The following NICs appear to have issues: %s\n" "Please note that ifconfig counters need to be reset in order to avoid detecting old errors" % ", ".join(bad_interfaces.keys())) return dict(problem="\n".join(problems), extra_info=data)
def interfaces(): try: addrs = { to_unicode(x): [{ k: _tryint(getattr(z, k)) for k in dir(z) if not k.startswith('_') } for z in y] for x, y in psutil.net_if_addrs().iteritems() } except: addrs = None try: stats = { to_unicode(x): { k: _tryint(getattr(y, k)) for k in dir(y) if not k.startswith('_') } for x, y in psutil.net_if_stats().iteritems() } except: stats = None return {'addrs': addrs, 'stats': stats}
def _collect_network_default(self): net_info = dict() if_list = list() data_from_if_addrs = psutil.net_if_addrs() data_from_if_stats = psutil.net_if_stats() for if_name in data_from_if_addrs.keys(): if_info_dict = dict() if_stat = data_from_if_stats[if_name] if_info_dict["name"] = if_name if_info_dict["link_state"] = if_stat.__getattribute__("isup") if_info_dict["duplex_mode"] = if_stat.__getattribute__("duplex") if_info_dict["link_speed_gbps"] = if_stat.__getattribute__("speed") if_info_dict["mtu_size_byte"] = if_stat.__getattribute__("mtu") if_info_dict["address"] = self._get_addrs(if_name) if_list.append(if_info_dict) net_info["interface"] = if_list net_info["gateway"] = self._get_organized_gateways() self._logger.debug(net_info) return net_info