Python psutil.net_io_counters() Examples

The following are 30 code examples of psutil.net_io_counters(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module psutil , or try the search function .
Example #1
Source File: system_status.py    From Paradrop with Apache License 2.0 12 votes vote down vote up
def getSystemInfo(cls):
        system = {
            'boot_time': psutil.boot_time(),
            'cpu_count': psutil.cpu_count(),
            'cpu_stats': psutil.cpu_stats().__dict__,
            'cpu_times': [k.__dict__ for k in psutil.cpu_times(percpu=True)],
            'disk_io_counters': psutil.disk_io_counters().__dict__,
            'disk_usage': [],
            'net_io_counters': psutil.net_io_counters().__dict__,
            'swap_memory': psutil.swap_memory().__dict__,
            'virtual_memory': psutil.virtual_memory().__dict__
        }

        partitions = psutil.disk_partitions()
        for p in partitions:
            if p.mountpoint in cls.INCLUDED_PARTITIONS:
                usage = psutil.disk_usage(p.mountpoint)
                system['disk_usage'].append({
                    'mountpoint': p.mountpoint,
                    'total': usage.total,
                    'used': usage.used
                })

        return system 
Example #2
Source File: status.py    From hapi with GNU General Public License v3.0 6 votes vote down vote up
def update(self):
        """Function to update the entire class information."""
        self.cpu["percentage"] = psutil.cpu_percent(interval=0.7)
        self.boot = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime(
            "%Y-%m-%d %H:%M:%S")
        virtual_memory = psutil.virtual_memory()
        self.memory["used"] = int(virtual_memory.used/1024)
        self.memory["free"] = int(virtual_memory.free/1024)
        self.memory["cached"] = int(virtual_memory.cached/1024)
        net_io_counters = psutil.net_io_counters()
        self.network["packet_sent"] = net_io_counters.packets_sent
        self.network["packet_recv"] = net_io_counters.packets_recv
        disk_usage = psutil.disk_usage('/')
        self.disk["total"] = int(disk_usage.total/1024)
        self.disk["used"] = int(disk_usage.used/1024)
        self.disk["free"] = int(disk_usage.free/1024)
        self.timestamp = time.time() 
Example #3
Source File: monitor.py    From Server-Monitoring-Script with Apache License 2.0 6 votes vote down vote up
def get_bandwidth():
    # Get net in/out
    net1_out = psutil.net_io_counters().bytes_sent
    net1_in = psutil.net_io_counters().bytes_recv

    time.sleep(1)

    # Get new net in/out
    net2_out = psutil.net_io_counters().bytes_sent
    net2_in = psutil.net_io_counters().bytes_recv

    # Compare and get current speed
    if net1_in > net2_in:
        current_in = 0
    else:
        current_in = net2_in - net1_in

    if net1_out > net2_out:
        current_out = 0
    else:
        current_out = net2_out - net1_out

    network = {"traffic_in" : current_in, "traffic_out" : current_out}
    return network 
Example #4
Source File: webapp.py    From pyrocore with GNU General Public License v2.0 6 votes vote down vote up
def json_charts(self, req):
        """ Return charting data.
        """
        disk_used, disk_total, disk_detail = 0, 0, []
        for disk_usage_path in self.cfg.disk_usage_path.split(os.pathsep):
            disk_usage = self.guarded(psutil.disk_usage, os.path.expanduser(disk_usage_path.strip()))
            if disk_usage:
                disk_used += disk_usage.used
                disk_total += disk_usage.total
                disk_detail.append((disk_usage.used, disk_usage.total))

        data = dict(
            engine      = self.json_engine(req),
            uptime      = time.time() - psutil.BOOT_TIME,  # pylint: disable=no-member
            fqdn        = self.guarded(socket.getfqdn),
            cpu_usage   = self.guarded(psutil.cpu_percent, 0),
            ram_usage   = self.guarded(psutil.virtual_memory),
            swap_usage  = self.guarded(psutil.swap_memory),
            disk_usage  = (disk_used, disk_total, disk_detail) if disk_total else None,
            disk_io     = self.guarded(psutil.disk_io_counters),
            net_io      = self.guarded(psutil.net_io_counters),
        )
        return data 
Example #5
Source File: test_misc.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_cache_clear_public_apis(self):
        psutil.disk_io_counters()
        psutil.net_io_counters()
        caches = wrap_numbers.cache_info()
        for cache in caches:
            self.assertIn('psutil.disk_io_counters', cache)
            self.assertIn('psutil.net_io_counters', cache)

        psutil.disk_io_counters.cache_clear()
        caches = wrap_numbers.cache_info()
        for cache in caches:
            self.assertIn('psutil.net_io_counters', cache)
            self.assertNotIn('psutil.disk_io_counters', cache)

        psutil.net_io_counters.cache_clear()
        caches = wrap_numbers.cache_info()
        self.assertEqual(caches, ({}, {}, {}))


# ===================================================================
# --- Example script tests
# =================================================================== 
Example #6
Source File: test_misc.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_serialization(self):
        def check(ret):
            if json is not None:
                json.loads(json.dumps(ret))
            a = pickle.dumps(ret)
            b = pickle.loads(a)
            self.assertEqual(ret, b)

        check(psutil.Process().as_dict())
        check(psutil.virtual_memory())
        check(psutil.swap_memory())
        check(psutil.cpu_times())
        check(psutil.cpu_times_percent(interval=0))
        check(psutil.net_io_counters())
        if LINUX and not os.path.exists('/proc/diskstats'):
            pass
        else:
            if not APPVEYOR:
                check(psutil.disk_io_counters())
        check(psutil.disk_partitions())
        check(psutil.disk_usage(os.getcwd()))
        check(psutil.users()) 
Example #7
Source File: test_linux.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_procfs_path(self):
        tdir = self.get_testfn()
        os.mkdir(tdir)
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            # self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc" 
Example #8
Source File: test_linux.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir) 
Example #9
Source File: resource.py    From mars with Apache License 2.0 6 votes vote down vote up
def net_io_usage():
    global _last_net_io_meta

    net_counters = psutil.net_io_counters()
    tst = time.time()

    send_bytes = net_counters.bytes_sent
    recv_bytes = net_counters.bytes_recv
    if _last_net_io_meta is None:
        _last_net_io_meta = (send_bytes, recv_bytes, tst)
        return None

    last_send_bytes, last_recv_bytes, last_time = _last_net_io_meta
    delta_time = tst - last_time
    recv_speed = (recv_bytes - last_recv_bytes) / delta_time
    send_speed = (send_bytes - last_send_bytes) / delta_time

    _last_net_io_meta = (send_bytes, recv_bytes, tst)
    return recv_speed, send_speed 
Example #10
Source File: views.py    From docker-box with MIT License 6 votes vote down vote up
def stream_host_stats():
    while True:
        net = psutil.net_io_counters(pernic=True)
        time.sleep(1)
        net1 = psutil.net_io_counters(pernic=True)
        net_stat_download = {}
        net_stat_upload = {}
        for k, v in net.items():
            for k1, v1 in net1.items():
                if k1 == k:
                    net_stat_download[k] = (v1.bytes_recv - v.bytes_recv) / 1000.
                    net_stat_upload[k] = (v1.bytes_sent - v.bytes_sent) / 1000.
        ds = statvfs('/')
        disk_str = {"Used": ((ds.f_blocks - ds.f_bfree) * ds.f_frsize) / 10 ** 9, "Unused": (ds.f_bavail * ds.f_frsize) / 10 ** 9}
        yield '[{"cpu":"%s","memory":"%s","memTotal":"%s","net_stats_down":"%s","net_stats_up":"%s","disk":"%s"}],' \
              % (psutil.cpu_percent(interval=1), psutil.virtual_memory().used, psutil.virtual_memory().free, \
                 net_stat_download, net_stat_upload, disk_str) 
Example #11
Source File: sysinfo.py    From RTask with GNU General Public License v3.0 6 votes vote down vote up
def get_network():
    network = psutil.net_io_counters(pernic=True)
    ifaces = psutil.net_if_addrs()
    networks = list()
    for k, v in ifaces.items():
        ip = v[0].address
        data = network[k]
        ifnet = dict()
        ifnet['ip'] = ip
        ifnet['iface'] = k
        ifnet['sent'] = '%.2fMB' % (data.bytes_sent/1024/1024)
        ifnet['recv'] = '%.2fMB' % (data.bytes_recv/1024/1024)
        ifnet['packets_sent'] = data.packets_sent
        ifnet['packets_recv'] = data.packets_recv
        ifnet['errin'] = data.errin
        ifnet['errout'] = data.errout
        ifnet['dropin'] = data.dropin
        ifnet['dropout'] = data.dropout
        networks.append(ifnet)
    return networks 
Example #12
Source File: test_misc.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_serialization(self):
        def check(ret):
            if json is not None:
                json.loads(json.dumps(ret))
            a = pickle.dumps(ret)
            b = pickle.loads(a)
            self.assertEqual(ret, b)

        check(psutil.Process().as_dict())
        check(psutil.virtual_memory())
        check(psutil.swap_memory())
        check(psutil.cpu_times())
        check(psutil.cpu_times_percent(interval=0))
        check(psutil.net_io_counters())
        if LINUX and not os.path.exists('/proc/diskstats'):
            pass
        else:
            if not APPVEYOR:
                check(psutil.disk_io_counters())
        check(psutil.disk_partitions())
        check(psutil.disk_usage(os.getcwd()))
        check(psutil.users()) 
Example #13
Source File: test_misc.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_cache_clear_public_apis(self):
        if not psutil.disk_io_counters() or not psutil.net_io_counters():
            return self.skipTest("no disks or NICs available")
        psutil.disk_io_counters()
        psutil.net_io_counters()
        caches = wrap_numbers.cache_info()
        for cache in caches:
            self.assertIn('psutil.disk_io_counters', cache)
            self.assertIn('psutil.net_io_counters', cache)

        psutil.disk_io_counters.cache_clear()
        caches = wrap_numbers.cache_info()
        for cache in caches:
            self.assertIn('psutil.net_io_counters', cache)
            self.assertNotIn('psutil.disk_io_counters', cache)

        psutil.net_io_counters.cache_clear()
        caches = wrap_numbers.cache_info()
        self.assertEqual(caches, ({}, {}, {}))


# ===================================================================
# --- Example script tests
# =================================================================== 
Example #14
Source File: system_status.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
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 
Example #15
Source File: test_misc.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_serialization(self):
        def check(ret):
            if json is not None:
                json.loads(json.dumps(ret))
            a = pickle.dumps(ret)
            b = pickle.loads(a)
            self.assertEqual(ret, b)

        check(psutil.Process().as_dict())
        check(psutil.virtual_memory())
        check(psutil.swap_memory())
        check(psutil.cpu_times())
        check(psutil.cpu_times_percent(interval=0))
        check(psutil.net_io_counters())
        if LINUX and not os.path.exists('/proc/diskstats'):
            pass
        else:
            if not APPVEYOR:
                check(psutil.disk_io_counters())
        check(psutil.disk_partitions())
        check(psutil.disk_usage(os.getcwd()))
        check(psutil.users()) 
Example #16
Source File: test_misc.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_cache_clear_public_apis(self):
        psutil.disk_io_counters()
        psutil.net_io_counters()
        caches = wrap_numbers.cache_info()
        for cache in caches:
            self.assertIn('psutil.disk_io_counters', cache)
            self.assertIn('psutil.net_io_counters', cache)

        psutil.disk_io_counters.cache_clear()
        caches = wrap_numbers.cache_info()
        for cache in caches:
            self.assertIn('psutil.net_io_counters', cache)
            self.assertNotIn('psutil.disk_io_counters', cache)

        psutil.net_io_counters.cache_clear()
        caches = wrap_numbers.cache_info()
        self.assertEqual(caches, ({}, {}, {}))


# ===================================================================
# --- Example script tests
# =================================================================== 
Example #17
Source File: net.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def _get_net_io_counters(self):
        """
        Fetch io counters from psutil and transform it to
        dicts with the additional attributes defaulted
        """
        counters = psutil.net_io_counters(pernic=self.pernic)

        res = {}
        for name, io in counters.iteritems():
            res[name] = io._asdict()
            res[name].update({'tx_per_sec': 0, 'rx_per_sec': 0})

        return res 
Example #18
Source File: health.py    From openwhisk-package-kafka with Apache License 2.0 5 votes vote down vote up
def generateHealthReport(consumers, lastCanaryTime):
    healthReport = {}
    healthReport['last_db_canary'] = secondsSince(lastCanaryTime)
    healthReport['uptime'] = getUpdateTime()
    healthReport['cpu_times'] = getCPUTimes()
    healthReport['cpu_percent'] = getCPUPercent()
    healthReport['virtual_memory'] = getVirtualMemory()
    healthReport['swap_memory'] = getSwapMemory()
    healthReport['disk_usage'] = getDiskUsage()
    healthReport['disk_io_counters'] = getDiskIOCounters()
    healthReport['net_io_counters'] = getNetworkIOCounters()
    healthReport['consumers'] = getConsumers(consumers)

    return healthReport 
Example #19
Source File: client_psutil_plugin.py    From hubblemon with Apache License 2.0 5 votes vote down vote up
def collect_network(self, stat):
		n = psutil.net_io_counters(pernic=False)
		stat['psutil_net'] = {	'bytes_sent':n.bytes_sent,
				'bytes_recv':n.bytes_recv,
				'packets_sent':n.packets_sent,
				'packets_recv':n.packets_recv,
				'errin':n.errin,
				'errout':n.errout,
				'dropin':n.dropin,
				'dropout':n.dropout,
				} 

		ns = psutil.net_io_counters(pernic=True)
		for k, n in ns.items():
			if k == 'lo': # skip loopback
				continue

			stat['psutil_net-%s' % k] = {	'bytes_sent':n.bytes_sent,
						'bytes_recv':n.bytes_recv,
						'packets_sent':n.packets_sent,
						'packets_recv':n.packets_recv,
						'errin':n.errin,
						'errout':n.errout,
						'dropin':n.dropin,
						'dropout':n.dropout,
						} 
Example #20
Source File: sys_monitor.py    From news_spider with MIT License 5 votes vote down vote up
def _network(speed=True):
    snetio = psutil.net_io_counters()
    contents = [_format_info('bytes_sent', bytes2human(snetio.bytes_sent)),
                _format_info('bytes_recv', bytes2human(snetio.bytes_recv))]

    if speed:
        time.sleep(1)
        snetio_after = psutil.net_io_counters()
        contents.append(_format_info('speed_sent', '%s/S' % bytes2human(snetio_after.bytes_sent - snetio.bytes_sent)))
        contents.append(_format_info('speed_recv', '%s/S' % bytes2human(snetio_after.bytes_recv - snetio.bytes_recv)))
    _print_info(contents, 'Network') 
Example #21
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def ip_addresses():
            arr = []
            for iface in psutil.net_io_counters(pernic=True):
                ip = psutil.net_if_addrs()[str(iface)][0][1]
                if re.match(r'^((\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])$', ip) and str(
                        ip) != 'localhost' and str(ip) != '127.0.0.1':
                    arr.append(ip)
            return arr 
Example #22
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def mac_addresses():
                mac = get_mac()
                ':'.join(("%012X" % mac)[i:i + 2] for i in range(0, 12, 2))
                arr = []
                for iface in psutil.net_io_counters(pernic=True):
                    try:
                        addr_list = psutil.net_if_addrs()
                        mac = addr_list[str(iface)][2][1]
                        if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()) and str(
                                mac) != '00:00:00:00:00:00':
                            arr.append(mac.lower())
                    except Exception as e:
                        pass

                return arr 
Example #23
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def interfaces():
                arr = []
                for iface in psutil.net_io_counters(pernic=True):
                    arr.append(str(iface))
                return arr 
Example #24
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def io_counter_detail():
                return psutil.net_io_counters(pernic=True) 
Example #25
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def ip_addresses():
            arr = []
            for iface in psutil.net_io_counters(pernic=True):
                ip = psutil.net_if_addrs()[str(iface)][0][1]
                if re.match(r'^((\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])$', ip) and str(
                        ip) != 'localhost' and str(ip) != '127.0.0.1':
                    arr.append(ip)
            return arr 
Example #26
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def mac_addresses():
                mac = get_mac()
                ':'.join(("%012X" % mac)[i:i + 2] for i in range(0, 12, 2))
                arr = []
                for iface in psutil.net_io_counters(pernic=True):
                    try:
                        addr_list = psutil.net_if_addrs()
                        mac = addr_list[str(iface)][2][1]
                        if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()) and str(
                                mac) != '00:00:00:00:00:00':
                            arr.append(mac.lower())
                    except Exception as e:
                        pass

                return arr 
Example #27
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def interfaces():
                arr = []
                for iface in psutil.net_io_counters(pernic=True):
                    arr.append(str(iface))
                return arr 
Example #28
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def io_counter_detail():
                return psutil.net_io_counters(pernic=True) 
Example #29
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def interface_size():
                return len(psutil.net_io_counters(pernic=True)) 
Example #30
Source File: resource_monitoring.py    From distributed_framework with Apache License 2.0 5 votes vote down vote up
def get_os_net_info(self):
        result1 = psutil.net_io_counters(pernic=False)
        time.sleep(1)
        result2 = psutil.net_io_counters(pernic=False)
        speed_dict = dict()
        speed_dict['up_speed'] = self.divide_1m(result2[0] - result1[0])
        speed_dict['down_speed'] = self.divide_1m(result2[1] - result1[1])
        speed_dict['packet_sent_speed'] = result2[2] - result1[2]
        speed_dict['packet_recv_speed'] = result2[3] - result1[3]
        self.logger.debug(result1)
        return speed_dict