Platform
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.
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(
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~~~
Most helpful comment
Hang on. =)
If you see a tuple instead of namedtuple then it's a bug.