Psutil: [Win10] psutil.net_connections return mixed object types (namedtuple and tuple)

Created on 21 May 2019  ·  5Comments  ·  Source: giampaolo/psutil

Platform

  • sys.getwindowsversion(major=6, minor=2, build=9200, platform=2, service_pack='')
  • '2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]'
  • Version: 5.6.2

Bug description
psutil.net_connections return mixed object types (namedtuple and tuple)
I think it should be return type with namedtuple instead of tuple,or mixed types.

print [sconn.raddr for sconn in sconn_list if sconn.raddr.port == 993 and sconn.status == 'ESTABLISHED']
import psutil

sconn_list = psutil.net_connections(kind='tcp')

print sconn_list[0].raddr.port
print [type(sconn.raddr) for sconn in sconn_list]
print [sconn.raddr for sconn in sconn_list if sconn.raddr.port == 993 and sconn.status == 'ESTABLISHED']

Test results

Traceback (most recent call last):
  File "C:/Users/Guodong/PycharmProjects/LinuxBashShellScriptForOps/functions/net/tcp/port/check-port-connection.py", line 33, in <module>
    print [sconn.raddr for sconn in sconn_list if sconn.raddr.port == 993 and sconn.status == 'ESTABLISHED']
AttributeError: 'tuple' object has no attribute 'port'

thanks.

bug windows

Most helpful comment

Hang on. =)
If you see a tuple instead of namedtuple then it's a bug.

All 5 comments

Besides, it can be fixed by using code as follows:

import psutil
from psutil._common import addr  # addr = namedtuple('addr', ['ip', 'port'])

sconn_list = psutil.net_connections(kind='tcp')

print sconn_list[0].raddr.port
print [sconn.raddr for sconn in sconn_list if
       isinstance(sconn.raddr, addr) and sconn.raddr.port == 993 and sconn.status == 'ESTABLISHED']

Mmm... this is weird. I can't see anything in the code which justifies what you see. Could try try to debug with pdb or something?

I'm sorry to make you confused, Maybe that's normal. item in psutil.net_connections(kind='tcp') can be in two python object types(and ). You will see it when execute those codes.

import psutil

sconn_list = psutil.net_connections(kind='tcp')

for sconn in sconn_list:
    print(type(sconn.raddr))
    print(sconn)

After I double check it, I think it is my own mistake, It will return tuple only when 'sconn.status='LISTEN''
now I will close it.

Many thanks. ;)

Hang on. =)
If you see a tuple instead of namedtuple then it's a bug.

:), OK, you are so nice that I very appreciate it.

I am using this code to avoid this issue.

new code:

my_sconn_list = [sconn for sconn in sconn_list if sconn.status == 'ESTABLISHED' and sconn.raddr.port == port]

old code:

from psutil._common import addr
my_sconn_list = [sconn for sconn in sconn_list if
                 isinstance(sconn.raddr,
                            addr) and sconn.raddr.port == port and sconn.status == 'ESTABLISHED']

__I think the location of sconn.status == 'ESTABLISHED' is key.__

Thanks~~~

Was this page helpful?
0 / 5 - 0 ratings