syspy  0.1
syspy windows system information tool with python
network.py
Go to the documentation of this file.
1 __title__ = 'syspy'
2 __version__ = '0.1'
3 __author__ = 'Ali GOREN <goren.ali@yandex.com>'
4 __repo__ = 'https://github.com/aligoren/syspy'
5 __license__ = 'Apache v2.0 License'
6 
7 import socket
8 from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM
9 
10 import psutil
11 
12 
13 
14 AD = "-"
15 AF_INET6 = getattr(socket, 'AF_INET6', object())
16 proto_map = {
17  (AF_INET, SOCK_STREAM): 'tcp',
18  (AF_INET6, SOCK_STREAM): 'tcp6',
19  (AF_INET, SOCK_DGRAM): 'udp',
20  (AF_INET6, SOCK_DGRAM): 'udp6',
21 }
22 
23 
24 class Network:
25 
26  def __init__(self):
27  self.bytes2human
28  self.getNetIoCounters
30 
31  def bytes2human(self,n):
32  # http://code.activestate.com/recipes/578019
33  # >>> bytes2human(10000)
34  # '9.8K'
35  # >>> bytes2human(100001221)
36  # '95.4M'
37  symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
38  prefix = {}
39  for i, s in enumerate(symbols):
40  prefix[s] = 1 << (i + 1) * 10
41  for s in reversed(symbols):
42  if n >= prefix[s]:
43  value = float(n) / prefix[s]
44  return '%.1f%s' % (value, s)
45  return "%sB" % n
46 
47  def getNetIoCounters(self):
48  """
49 
50  Return system-wide network I/O statistics as a namedtuple including the following attributes:
51 
52  bytes_sent: number of bytes sent
53  bytes_recv: number of bytes received
54  packets_sent: number of packets sent
55  packets_recv: number of packets received
56  errin: total number of errors while receiving
57  errout: total number of errors while sending
58  dropin: total number of incoming packets which were dropped
59  dropout: total number of outgoing packets which were dropped (always 0 on OSX and BSD)
60  If pernic is True return the same information for every network interface installed on
61  the system as a dictionary with network interface names
62  as the keys and the namedtuple described above as the values.
63 
64  >>> import psutil
65  >>> ln = list(psutil.net_io_counters())
66  >>> ln
67  [11198193, 173143520, 95172, 148624, 0, 0, 0, 0]
68  >>> ln = list(psutil.net_io_counters(pernic=True))
69  >>> ln
70  ['Loopback Pseudo-Interface 1', 'Kablosuz A', 'Yerel A']
71  >>> psutil.net_io_counters(pernic=True)
72  {'Loopback Pseudo-Interface 1': snetio(bytes_sent=0, bytes_recv=0, packets_sent=
73  0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0), 'Kablosuz A': snetio
74  (bytes_sent=11286740, bytes_recv=176409663, packets_sent=96451, packets_recv=150
75  833, errin=0, errout=0, dropin=0, dropout=0), 'Yerel A': snetio(bytes_sent=0, by
76  tes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout
77  =0)}
78  >>> psutil.net_io_counters()
79  snetio(bytes_sent=11510800, bytes_recv=179194110, packets_sent=98058, packets_re
80  cv=153191, errin=0, errout=0, dropin=0, dropout=0)
81  >>>
82  """
83  lnic = list(psutil.net_io_counters())
84 
85  ret_byte_sent = self.bytes2human(lnic[0])
86  ret_byte_recv = self.bytes2human(lnic[1])
87  ret_packets_sent = self.bytes2human(lnic[2])
88  ret_packets_recv = self.bytes2human(lnic[3])
89  ret_errin = self.bytes2human(lnic[4])
90  ret_errout = self.bytes2human(lnic[5])
91  ret_dropin = self.bytes2human(lnic[6])
92  ret_dropout = self.bytes2human(lnic[7])
93 
94  return ret_byte_sent, ret_byte_recv, ret_packets_sent, ret_packets_recv, ret_errin, ret_errout, \
95  ret_dropin, ret_dropout
96 
97 
98  def getNetConnections(self):
99  """
100  Return system-wide socket connections as a list of namedutples. Every namedtuple provides 7 attributes:
101 
102  fd: the socket file descriptor, if retrievable, else -1.
103  If the connection refers to the current process this may be passed to socket.fromfd() to obtain a usable socket object.
104  family: the address family, either AF_INET, AF_INET6 or AF_UNIX.
105  type: the address type, either SOCK_STREAM or SOCK_DGRAM.
106  laddr: the local address as a (ip, port) tuple or a path in case of AF_UNIX sockets.
107  raddr: the remote address as a (ip, port) tuple or an absolute path in case of UNIX sockets.
108  When the remote endpoint is not connected you’ll get an empty tuple (AF_INET*) or None (AF_UNIX).
109  On Linux AF_UNIX sockets will always have this set to None.
110  status: represents the status of a TCP connection.
111  The return value is one of the psutil.CONN_* constants (a string).
112  For UDP and UNIX sockets this is always going to be psutil.CONN_NONE.
113  pid: the PID of the process which opened the socket, if retrievable, else None.
114  On some platforms (e.g. Linux) the availability of this field changes depending on process privileges (root is needed).
115  The kind parameter is a string which filters for connections that fit the following criteria:
116 
117  Kind value Connections using
118  “inet” IPv4 and IPv6
119  “inet4” IPv4
120  “inet6” IPv6
121  “tcp” TCP
122  “tcp4” TCP over IPv4
123  “tcp6” TCP over IPv6
124  “udp” UDP
125  “udp4” UDP over IPv4
126  “udp6” UDP over IPv6
127  “unix” UNIX socket (both UDP and TCP protocols)
128  “all” the sum of all the possible families and protocols
129  To get per-process connections use Process.connections().
130  """
131  templ = "%-5s %-30s %-30s %-13s %-6s %s"
132  print(templ % (
133  "Proto", "Local address", "Remote address", "Status", "PID",
134  "Program name"))
135  proc_names = {}
136  for p in psutil.process_iter():
137  try:
138  proc_names[p.pid] = p.name()
139  except psutil.Error:
140  pass
141  for c in psutil.net_connections(kind='inet'):
142  laddr = "%s:%s" % (c.laddr)
143  raddr = ""
144  if c.raddr:
145  raddr = "%s:%s" % (c.raddr)
146  print(templ % (
147  proto_map[(c.family, c.type)],
148  laddr,
149  raddr or AD,
150  c.status,
151  c.pid or AD,
152  proc_names.get(c.pid, '?')[:15],
153  ))
def bytes2human(self, n)
Definition: network.py:31