Improve code styling and performance in proc.py

Previously was O(N), now only O(N) in worst case
This commit is contained in:
adisbladis 2017-05-21 15:36:15 +08:00
parent 2e4b91ceea
commit f19ce5c9a7
Failed to generate hash of commit

View file

@ -16,40 +16,41 @@
# program. If not, go to http://www.gnu.org/licenses/gpl.html
# or write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
import logging
import psutil
import os
def get_pid_by_connection( procmon, src_addr, src_p, dst_addr, dst_p, proto = 'tcp' ):
connections_list = [ connection for connection in psutil.net_connections(kind=proto) \
if connection.laddr==( src_addr, int(src_p) ) and \
connection.raddr==( dst_addr, int(dst_p) ) ]
# We always take the first element as we assume it contains only one, because
# it should not be possible to keep two connections which are exactly the same.
if connections_list:
pid = connections_list[0][-1]
def get_pid_by_connection(procmon, src_addr, src_p, dst_addr,
dst_p, proto='tcp'):
pids = (connection.pid for connection in psutil.net_connections(kind=proto)
if connection.laddr == (src_addr, int(src_p)) and
connection.raddr == (dst_addr, int(dst_p)))
# We always take the first element as we assume it contains only one
# It should not be possible to keep two connections which are the same.
for pid in pids:
try:
appname = None
if procmon.running:
appname = procmon.get_app_name(pid)
if appname is None:
appname = os.readlink( "/proc/%s/exe" % pid )
appname = os.readlink("/proc/%s/exe" % pid)
if procmon.running:
logging.debug( "Could not find pid %s with ProcMon, falling back to /proc/%s/exe -> %s" % ( pid, pid, appname ) )
logging.debug("Could not find pid %s with ProcMon, falling back to /proc/%s/exe -> %s", pid, pid, appname) # noqa
else:
logging.debug( "ProcMon(%s) = %s" % ( pid, appname ) )
logging.debug("ProcMon(%s) = %s", pid, appname)
return ( pid, appname )
return (pid, appname)
except OSError:
return (None, "Unknown")
else:
logging.warning( "Could not find process for %s connection %s:%s -> %s:%s" % (
proto,
src_addr,
src_p,
dst_addr,
dst_p) )
return ( None, "Unknown" )
logging.warning("Could not find process for %s connection %s:%s -> %s:%s",
proto,
src_addr,
src_p,
dst_addr,
dst_p)
return (None, "Unknown")