コード例 #1
0
ファイル: utils.py プロジェクト: AlphaX-IBS/raiden
def get_free_port(address: str, initial_port: int):
    """Find an unused TCP port in a specified range. This should not
      be used in misson-critical applications - a race condition may
      occur if someone grabs the port before caller of this function
      has chance to use it.
      Parameters:
          address : an ip address of interface to use
          initial_port : port to start iteration with
      Return:
          Iterator that will return next unused port on a specified
          interface
    """

    try:
        # On OSX this function requires root privileges
        psutil.net_connections()
    except psutil.AccessDenied:
        return count(initial_port)

    def _unused_ports():
        for port in count(initial_port):
            # check if the port is being used
            connect_using_port = (
                conn
                for conn in psutil.net_connections()
                if hasattr(conn, 'laddr') and
                conn.laddr[0] == address and
                conn.laddr[1] == port
            )

            # only generate unused ports
            if not any(connect_using_port):
                yield port

    return _unused_ports()
コード例 #2
0
ファイル: procinfo.py プロジェクト: mike01/ifi
def get_procinfo_by_address(ip_src, ip_dst, port_src=None, port_dst=None):
	"""
	Gets Infos about the Prozess associated with the given address information
	Both port_src and port_dst must be not None or None at the same time.

	return -- [pid, "/path/to/command", "user", "hash"] or []
	"""
	result = []

	if port_src is not None:
		pids = [c.pid for c in net_connections()
			if len(c.raddr) != 0 and c.pid is not None and
				(c.laddr[0], c.raddr[0], c.laddr[1], c.raddr[1]) == (ip_src, ip_dst, port_src, port_dst)]
	else:
		pids = [c.pid for c in net_connections()
			if len(c.raddr) != 0 and c.pid is not None and (c.laddr[0], c.raddr[0]) == (ip_src, ip_dst)]

	try:
		if len(pids) > 1:
			logger.warning("more than 1 matching process: %r", pids)
		proc = Process(pids[0])
		cmd = [pids[0], proc.cmdline(), proc.username()]
		hash_input = "%d%s%s" % (cmd[0], cmd[1], cmd[2])
		procinfo_hash = hashlib.sha256(hash_input.encode("UTF-8"))
		cmd.append(procinfo_hash)
		logger.debug("process info: %r", cmd)
		return cmd
	except IndexError:
		pass
	return []
コード例 #3
0
ファイル: _linux.py プロジェクト: dpavlenkov/psutil
 def test_connections_ipv6_not_supported(self, supports_ipv6, inet_ntop):
     # see: https://github.com/giampaolo/psutil/issues/623
     try:
         s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
         self.addCleanup(s.close)
         s.bind(("::1", 0))
     except socket.error:
         pass
     psutil.net_connections(kind='inet6')
コード例 #4
0
ファイル: picocmd.py プロジェクト: AlessandroZ/pupy
    def __init__(self, cpu=None, users=None, mem=None, listen=None, remote=None, idle=None):
        if cpu is None:
            try:
                self.cpu = int(psutil.cpu_percent())
            except:
                self.cpu = 0
        else:
            self.cpu = int(cpu)

        if users is None:
            try:
                self.users = len(set([ x.name for x in psutil.users()]))
            except:
                self.users = 0
        else:
            self.users = int(users)

        if self.users > 255:
            self.users = 255

        if mem is None:
            try:
                self.mem = int(psutil.virtual_memory().percent)
            except:
                self.mem = 0
        else:
            self.mem = int(mem)

        if listen is None:
            try:
                self.listen = len(set([
                    x.laddr[1] for x in psutil.net_connections() if x.status=='LISTEN'
                ]))
            except:
                self.listen = 0
        else:
            self.listen = int(listen)

        if self.listen > 255:
            self.listen = 255

        if remote is None:
            try:
                self.remote = len(set([
                    x.raddr for x in psutil.net_connections() \
                    if x.status=='ESTABLISHED' and x.raddr[0] not in (
                        '127.0.0.1', '::ffff:127.0.0.1'
                    )
                ]))

            except Exception, e:
                self.remote = 0
コード例 #5
0
ファイル: histstat.py プロジェクト: crazykid199/histstat
    def histout(self):
        connections_A = net_connections()
        for c in connections_A:
            self.process_conn(c)

        while True:
            sleep(self.interval)

            connections_B = net_connections()
            for c in connections_B:
                if c not in connections_A:
                    self.process_conn(c)

            connections_A = connections_B
コード例 #6
0
ファイル: main.py プロジェクト: FedericoCeratto/dns-firewall
def fetch_pid(port):
    assert isinstance(port, int)
    for c in psutil.net_connections(kind='udp'):
        # if not c.raddr and c.laddr == ('0.0.0.0', port):
        if c.raddr in ((), ('127.0.0.1', 53)) \
            and c.laddr in (('0.0.0.0', port), ('127.0.0.1', port)):
            return c.pid

    log.error('No pid found %d', port)
    for c in psutil.net_connections(kind='udp'):
        if c.pid:
            name = fetch_process_name(c.pid)
            log.error('repr %r name %s', c, name)
        else:
            log.error('repr %r', c)
コード例 #7
0
ファイル: views.py プロジェクト: deadbok/server-hud
def connections():
    '''
    Return a JSON object with number of connections on a port.
    '''
    current_app.logger.debug("Getting active connections.")

    if request.method == 'OPTIONS':
        return cors_answer_options()

    active = 0
    # Get connections on port 80
    conn = psutil.net_connections('inet')
    if current_app.config['PORT'][0] == 'all':
        current_app.logger.debug("Counting all active connections.")
        for connection in conn:
            active += 1
    else:
		for port in current_app.config['PORT']:
			current_app.logger.debug("Counting connections on port: " +
						port + ".")
			for connection in conn:
				if connection.laddr[1] == int(port):
					active += 1
    # Return JSON
    current_app.logger.debug("Connections: " + str(active))
    return add_cors_headers(jsonify(connections=active))
コード例 #8
0
ファイル: netkiller.py プロジェクト: nola-radar/netkiller
def listProcesses(devices):

    # dear god this is hackish
    devices["0.0.0.0"] = "lo"
    devices["127.0.1.1"] = "lo"
    devices["::"] = "lo"
    devices["::1"] = "lo"

    import psutil

    la = psutil.net_connections()
    retval = []
    for i in la:
        ####
        #
        # The IP and port are stored as a tuple in the psutil._common.sconn namedtouple at
        # psutil._common.sconn[3] with the IP at [0] and the port at [1]
        #
        # The PID is stored at psutil._common.sconn[6]
        #
        ##
        # print i[3][0] + " " + str(i[3][1])
        # procs.append([i[3][0], str(i[3][1])])
        ####
        if i[6] is not None:
            retval.append((i[6], devices[i[3][0]]))

    # God, I am so sorry. I can feel my Data Structures prof judging me from somewhere
    # ... among other people...
    return list(set(retval))
コード例 #9
0
 def net_connect_info(self):
     '''
     Note: Get system network connections.
     net_connect_dict:
     :return: dict type
     {
         'fd':values,
         'family':values,
         'type':values,
         'laddr':values,     # It's tuple
         'raddr':values,     # It's tuple
         'status':values,
         'pid':values
     }
     '''
     flag = 0
     net_connect_dict = defaultdict(list)
     net_connect = psutil.net_connections()
     for i in net_connect:
         net_connect_dict[flag].append(i.fd)
         net_connect_dict[flag].append(i.family)
         net_connect_dict[flag].append(i.type)
         net_connect_dict[flag].append(i.laddr)
         net_connect_dict[flag].append(i.raddr)
         net_connect_dict[flag].append(i.status)
         net_connect_dict[flag].append(i.pid)
         flag += 1
     return net_connect_dict
コード例 #10
0
ファイル: collector.py プロジェクト: o/metric-agent
    def collect_connections(self):
        try:
            results = {
                'connections/tcp4': len(psutil.net_connections("tcp4")),
                'connections/tcp6': len(psutil.net_connections("tcp6")),
                'connections/udp4': len(psutil.net_connections("udp4")),
                'connections/udp6': len(psutil.net_connections("udp6")),
                'connections/unix': len(psutil.net_connections("unix"))
            }

            results['connections/total'] = (results['connections/unix'] + results['connections/udp6'] +
                                            results['connections/udp4'] + results['connections/tcp4'] +
                                            results['connections/tcp6'])
            return results
        except psutil.AccessDenied:  # BSD / OSX needs root access for that
            return {}
コード例 #11
0
ファイル: gui-mod.py プロジェクト: Sunplace/biyesheji-myPF
 def refreshconnections(self):
     current_layout_lock.acquire()
     if(self.sourcemodel.current_layout != "conn"):
         print ("refreshconnections error")
         current_layout_lock.release()
         return
     self.sourcemodel.layoutAboutToBeChanged.emit()
     self.sourcemodel.removeRows(0, self.sourcemodel.rowCount())
     for conn in psutil.net_connections("inet4"):
         if(conn.type == socket.SOCK_STREAM):
             proto = QStandardItem("tcp")
         else:
             proto = QStandardItem("udp")
         laddr = QStandardItem(conn.laddr[0])
         lport = QStandardItem(str(conn.laddr[1]))
         if(len(conn.raddr) == 0):
             continue
         raddr = QStandardItem(conn.raddr[0])
         rport = QStandardItem(str(conn.raddr[1]))
         status = QStandardItem(conn.status)
         pid = QStandardItem(str(conn.pid))
         if(conn.pid != None):
             p = psutil.Process(conn.pid)
             name = QStandardItem(p.name())
         else:
             name = QStandardItem("None")
         family = QStandardItem("ipv4")
         self.sourcemodel.appendRow( (family, proto, laddr, lport, raddr, rport, status, pid, name))
     self.sourcemodel.layoutChanged.emit()
     current_layout_lock.release()
コード例 #12
0
    def get_connections(self):

        my_connections = psutil.net_connections()
        conn_len = len(my_connections)
        connections_list = []

        for i in range(0, conn_len):

            if my_connections[i].status == 'ESTABLISHED' and  \
                my_connections[i].laddr[0] <> '0.0.0.0' and \
                (not '::' in my_connections[i].laddr[0] or not '::' in my_connections[i].raddr[0]) and \
                (len(my_connections[i].laddr[0]) <= 16):

                try:
                    conn_loc_address = my_connections[i].laddr[0]
                    conn_loc_port = my_connections[i].laddr[1]
                except Exception:
                    conn_loc_address = 'FAIL'
                    conn_loc_port = 'FAIL'

                try:
                    conn_rem_address = my_connections[i].raddr[0]
                    conn_rem_port = my_connections[i].raddr[1]
                except Exception:
                    conn_rem_address = 'FAIL'
                    conn_rem_port = 'FAIL'

                conn_family = my_connections[i].family
                conn_status = my_connections[i].status

                connections_list.append((conn_loc_address,conn_loc_port,conn_rem_address,conn_rem_port,conn_family,conn_status))

        connections_list.sort()
        return {'LIST': connections_list, 'CONNECTIONS':len(connections_list)}
コード例 #13
0
ファイル: util.py プロジェクト: 1resu/letsencrypt
def already_listening(port, renewer=False):
    """Check if a process is already listening on the port.

    If so, also tell the user via a display notification.

    .. warning::
        On some operating systems, this function can only usefully be
        run as root.

    :param int port: The TCP port in question.
    :returns: True or False.

    """
    try:
        net_connections = psutil.net_connections()
    except psutil.AccessDenied as error:
        logger.info("Access denied when trying to list network "
                    "connections: %s. Are you root?", error)
        # this function is just a pre-check that often causes false
        # positives and problems in testing (c.f. #680 on Mac, #255
        # generally); we will fail later in bind() anyway
        return False

    listeners = [conn.pid for conn in net_connections
                 if conn.status == 'LISTEN' and
                 conn.type == socket.SOCK_STREAM and
                 conn.laddr[1] == port]
    try:
        if listeners and listeners[0] is not None:
            # conn.pid may be None if the current process doesn't have
            # permission to identify the listening process!  Additionally,
            # listeners may have more than one element if separate
            # sockets have bound the same port on separate interfaces.
            # We currently only have UI to notify the user about one
            # of them at a time.
            pid = listeners[0]
            name = psutil.Process(pid).name()
            display = zope.component.getUtility(interfaces.IDisplay)
            extra = ""
            if renewer:
                extra = (
                    " For automated renewal, you may want to use a script that stops"
                    " and starts your webserver. You can find an example at"
                    " https://letsencrypt.org/howitworks/#writing-your-own-renewal-script"
                    ". Alternatively you can use the webroot plugin to renew without"
                    " needing to stop and start your webserver.")
            display.notification(
                "The program {0} (process ID {1}) is already listening "
                "on TCP port {2}. This will prevent us from binding to "
                "that port. Please stop the {0} program temporarily "
                "and then try again.{3}".format(name, pid, port, extra),
                height=13)
            return True
    except (psutil.NoSuchProcess, psutil.AccessDenied):
        # Perhaps the result of a race where the process could have
        # exited or relinquished the port (NoSuchProcess), or the result
        # of an OS policy where we're not allowed to look up the process
        # name (AccessDenied).
        pass
    return False
コード例 #14
0
ファイル: db.py プロジェクト: netkraken/minion
def fetch(db):
    counted = 0
    connections = psutil.net_connections(kind="inet4")

    listening = set([connection.laddr[1] for connection in connections
                     if connection.status == psutil.CONN_LISTEN])

    for connection in connections:
        if connection.status in (psutil.CONN_NONE, psutil.CONN_LISTEN):
            continue
        local_host, local_port = connection.laddr
        if local_port in listening:
            continue  # ignore incoming connections completely
        source = connection.laddr
        target = connection.raddr

        try:
            source_host = source[0]
            target_host = target[0]
            if source_host in ("127.0.0.1") or target_host in ("127.0.0.1"):
                continue
            db.count(" ".join([source_host, target_host, str(target[1])]))
            counted += 1
        except:
            print("ERROR parsing: %s" % str(connection))
            raise
    print("%i connections counted" % counted)
コード例 #15
0
def main():

    hostname = getfqdn()
    data = ''

    for k, v in psutil.cpu_times_percent(interval=0.5)._asdict().iteritems():
        data += '{0}.cpu.{1} value={2}\n'.format(hostname, k, v)

    for k, v in psutil.virtual_memory()._asdict().iteritems():
        data += '{0}.mem.{1} value={2}\n'.format(hostname, k, v)

    for k, v in psutil.swap_memory()._asdict().iteritems():
        data += '{0}.swap.{1} value={2}\n'.format(hostname, k, v)

    du = { mp.mountpoint: psutil.disk_usage(mp.mountpoint).percent for mp in psutil.disk_partitions() }
    for k, v in du.iteritems():
        data += '{0}.du_percent.{1} value={2}\n'.format(hostname, k, v)

    for k, v in psutil.disk_io_counters(perdisk=True).iteritems():
        for m, p in v._asdict().iteritems():
            data += '{0}.io.{1}.{2} value={3}\n'.format(hostname, k, m, p)

    for k, v in psutil.net_io_counters(pernic=True).iteritems():
        for m, p in v._asdict().iteritems():
            data += '{0}.net.{1}.{2} value={3}\n'.format(hostname, k, m, p)

    connections = map(lambda x: x.status.lower(), psutil.net_connections())
    connections = map( lambda x: 'unknown_state' if x == 'none' else x, connections )
    for conn in set(connections):
        data += '{0}.netstat.{1} value={2}\n'.format(hostname, conn, connections.count(conn))

    if DEBUG: print data
    sendData(data)
コード例 #16
0
ファイル: proc.py プロジェクト: BrieflyX/pwntools
def pidof(target):
    """pidof(target) -> int list

    Get PID(s) of `target`.  The returned PID(s) depends on the type of `target`:

    - :class:`str`: PIDs of all processes with a name matching `target`.
    - :class:`pwnlib.tubes.process.process`: singleton list of the PID of `target`.
    - :class:`pwnlib.tubes.sock.sock`: singleton list of the PID at the
      remote end of `target` if it is running on the host.  Otherwise an
      empty list.

    Arguments:
        target(object):  The target whose PID(s) to find.

    Returns:
        A list of found PIDs.
    """
    if isinstance(target, tubes.sock.sock):
         local  = target.sock.getsockname()
         remote = target.sock.getpeername()

         def match(p):
             return (c.raddr, c.laddr, c.status) == (local, remote, 'ESTABLISHED')

         return [c.pid for c in psutil.net_connections() if match(c)]

    elif isinstance(target, tubes.process.process):
         return [target.proc.pid]

    else:
         return pid_by_name(target)
コード例 #17
0
def network():
    global netconns
    if not netconns:
        netconns = psutil.net_connections()
        if not netconns:
            return "Empty"

    result = netconns.pop()

    while result.laddr[0].startswith("::") or result.status == "NONE":
        result = netconns.pop()
    if result.status == "ESTABLISHED":
        return "{} {:16} {:16}".format(
            result.status[0],
            result.laddr[0]+":"+str(result.laddr[1]),
            result.raddr[0]+":"+str(result.raddr[1]))
    elif result.status == "LISTEN":
        if result.laddr[0] == "127.0.0.1":
            # We are not interested in local running services.
            return network()

        return "{} {:16} {:16}".format(
            result.status[0],
            result.laddr[0],
            "NA")
    else:
        return "ERROR IN network()"
コード例 #18
0
ファイル: server.py プロジェクト: mkolar/pyblish-qml
    def find_available_port(self, start=first_port):
        """Return the next available port at which a client may listen

        If module "psutil" is available, this also takes into
        account any externally used ports such that no occupied
        port is accidentally used. This is generally recommended.

        Arguments:
            start (int, optional): Port from which to start
                looking, defaults to 6001

        """

        print("Finding available port..")
        occupied_ports = list(self.app.clients)

        try:
            import psutil
            occupied_ports += list(
                c.laddr[-1] for c in psutil.net_connections())
        except ImportError:
            pass

        available = start
        while available in occupied_ports:
            available += 1

        print("Distributing new port %i" % available)
        return available
コード例 #19
0
ファイル: netutils.py プロジェクト: Leone27/netmonitor
def get_pid():
    """Format:
            info = {"192.168.1.244:37176 183.61.87.9:13034":"18277/chrome"}
    """
    info = {}
    proc_names = {}
    proto_map = {
            (2, 1): 'tcp',
            (10, 1): 'tcp6',
            (2, 2): 'udp',
            (10, 2): 'udp6'
    }

    # get process name and pid
    for p in psutil.process_iter():
        try:
            proc_names[p.pid] = p.name()
        except psutil.Error:
            pass

    for c in psutil.net_connections():
        laddr = '%s:%s' % (c.laddr)
        raddr = ''

        if c.raddr:
            raddr = "%s:%s" % (c.raddr)

        if c.pid == None or raddr == '': continue
        info[laddr + " " + raddr] = proto_map.get((c.family, c.type)) + "/" + str(c.pid) + "/" + proc_names.get(c.pid)
        info[raddr + " " + laddr] = proto_map.get((c.family, c.type)) + "/" + str(c.pid) + "/" + proc_names.get(c.pid)
    return info
コード例 #20
0
ファイル: bgp_status.py プロジェクト: lorenzop/Py
def check_BGP():
    '''
    Checks bgp.conf for up / down, and the sockets for v4 and v6 BGP established.
    Returns in the format of:
    bgp.status <time> <0|1> protocol=<IPv4|IPv6>
    '''
    thyme = int(time.time())
    v6_up = 0
    v4_up = 0
    proc_names = {}
    if os.readlink(BGP_CONF) != BGP_UP:
        print 'bgp.status %d %d protocol=IPv6' % (thyme, v6_up)
        print 'bgp.status %d %d protocol=IPv4' % (thyme, v4_up)
    else:
        for p in psutil.process_iter():
            try:
                proc_names[p.pid] = p.name()
            except psutil.Error:
                pass
        for c in psutil.net_connections(kind='inet'):
            if c.raddr:
                if c.raddr[1] == PUERTO:
                    if c.status == 'ESTABLISHED':
                        if ':' in c.raddr[0]:
                            v6_up = 1
                        else:
                            v4_up = 1
                    else:
                        continue
                else:
                    continue
            else:
                continue
        print 'bgp.status %d %d protocol=IPv6' % (thyme, v6_up)
        print 'bgp.status %d %d protocol=IPv4' % (thyme, v4_up)
コード例 #21
0
ファイル: test_units.py プロジェクト: BitBaron/brozzler
def test_find_available_port():
    x = brozzler.chrome.Chrome(None, None)
    try:
        psutil.net_connections(kind='tcp')
    except psutil.AccessDenied:
        logging.warn(
                'skipping _find_available_port() test because '
                'psutil.net_connections(kind="tcp") raised AccessDenied')
        return
    assert x._find_available_port(9800) == 9800
    sock = socket.socket()
    sock.bind(('localhost', 9800))
    sock.listen(0)
    assert x._find_available_port(9800) == 9999
    sock.close()
    assert x._find_available_port(9800) == 9800
コード例 #22
0
ファイル: test_contracts.py プロジェクト: jomann09/psutil
 def test_net_connections(self):
     with unix_socket_path() as name:
         with closing(bind_unix_socket(name)):
             cons = psutil.net_connections(kind='unix')
             assert cons
             for conn in cons:
                 self.assertIsInstance(conn.laddr, str)
コード例 #23
0
    def GET(self):
        PortList = {
            'ErrStat' : 0,
            'ErrMsg'  : "OK",
            'Lists'   : [],
            'Totle'   : 0,
        }
        
        param = web.input()
        if param.has_key('Length') == False:
            ConfigData['ErrStat'] = -1
            ConfigData['ErrMsg'] = u'缺少参数 param:Length=Length'
            return render.port_list(json.dumps(PortList))
        if param.has_key('Start') == False:
            ConfigData['ErrStat'] = -1
            ConfigData['ErrMsg'] = u'缺少参数 param:Start=Start'
            return render.port_list(json.dumps(PortList))
        
        start  = int(param['Start'])
        length = int(param['Length'])

        # 获取所有连接
        Lists = []
        cons = psutil.net_connections('inet')
        for c in cons:
            dic = {}
            if c.type == 1:
                dic['Type'] = 'TCP'
            elif c.type == 2:
                dic['Type'] = 'UDP'
            # sip sport 
            if len(c.laddr) > 0:
                dic['Sip']   = c.laddr[0]
                dic['Sport'] = str(c.laddr[1])
            else:
                dic['Sip']   = 'NULL'
                dic['Sport'] = '0'
            # dip dport
            if len(c.raddr) > 0:
                dic['Dip']   = c.raddr[0]
                dic['Dport'] = str(c.raddr[1])
            else:
                dic['Dip']   = 'NULL'
                dic['Dport'] = '0'
            dic['Status'] = c.status
            dic['Pid'] = str(c.pid)

            #print c.raddr
            p = psutil.Process(c.pid)
            # name
            dic['Process'] = p.exe()
            # 加入数组
            Lists.append(dic)

        # 排序
        Lists.sort(CmpPid)
        PortList['Lists'] = Lists[start : start + length]
        PortList['Totle'] = len(Lists)
        return render.port_list(json.dumps(PortList))
コード例 #24
0
ファイル: dash_service.py プロジェクト: sheffters/clusterDash
        def exposed_get_network(self):
            netifs = self.get_network_interface()
            netifs.sort(key=lambda x: x.get("bytes_sent"), reverse=True)

            conns = psutil.net_connections()
            conns.sort(key=lambda x: x.status)

            return pickle.dumps((netifs, conns))
コード例 #25
0
ファイル: workflow.py プロジェクト: emilybache/gocddash
def get_free_port():
    # There is a potential for a race condition here, but I think it works ok in practice.
    port_used = True
    while port_used:
        port = random.randrange(4545, 9999)
        port_used = port in [x.laddr[1] for x in psutil.net_connections()]
    # noinspection PyUnboundLocalVariable
    return port
コード例 #26
0
ファイル: machine_status.py プロジェクト: kennethchioa/my_py
 def get_network_info(self):
     conns = ps.net_connections()
     self.network['count'] = len(conns)
     count = 0
     for conn in conns:
        if conn.status is 'ESTABLISHED':
            count = count + 1
     self.network['established'] = count
コード例 #27
0
ファイル: tcpProxy.py プロジェクト: vladikr/spicetcpproxy
 def refresh_ports():
     active_ports = [entry for entry in psutil.net_connections()
                     if entry.status != 'NONE']
     for item in self.__cached_ports.iteritems():
         socc_obj = [entry for entry in active_ports
          if entry.laddr == (str(item[1].getsockname()[0]), item[0])]
         if not socc_obj:
             self.remove_port(item[0])
コード例 #28
0
ファイル: nGle_sys_mon.py プロジェクト: dejavuwing/ngle
    def get_net_port_counter(self, *args):
        port_counter = 0
        for c in psutil.net_connections(kind='inet'):
            if c.status == "ESTABLISHED":
                if c.laddr[1] in args:
                    port_counter += 1

        return port_counter
コード例 #29
0
ファイル: testtools.py プロジェクト: justinclayton/flocker
def _find_process_name(port_number):
    """
    Get the name of the process using the given port number.
    """
    for connection in psutil.net_connections():
        if connection.laddr[1] == port_number:
            return psutil.Process(connection.pid).name()
    return None
コード例 #30
0
    def __type_counter(self, pids):
        """
        Build the STATE_DICT based on the number of connection types
        """

        for p in psutil.net_connections():
            if p.pid in pids:
                self.state_dict[p.status] += 1
コード例 #31
0
def beacon(config):
    '''
    Monitor the number of sockets open on the minion

    Specify thresholds for number of sockets and only emit a beacon if it is
    exceeded.

    .. code-block:: yaml

        beacons:
          network_sockets_open:
            sockets: 1
    '''
    try:
        num_conns = len(psutil.net_connections())
    except Exception as err:
        log.error('{0}'.format(err[0]))
        exit(1)

    ret = []
    if num_conns > config['sockets']:
        log.debug('{0}: {1}'.format(__virtualname__, num_conns))
        ret.append({__virtualname__: num_conns})
    return ret
コード例 #32
0
    def get_connections(self):

        my_connections = psutil.net_connections()
        conn_len = len(my_connections)
        connections_list = []

        for i in range(0, conn_len):

            if my_connections[i].status == 'ESTABLISHED' and  \
                my_connections[i].laddr[0] <> '0.0.0.0' and \
                (not '::' in my_connections[i].laddr[0] or not '::' in my_connections[i].raddr[0]) and \
                (len(my_connections[i].laddr[0]) <= 16):

                try:
                    conn_loc_address = my_connections[i].laddr[0]
                    conn_loc_port = my_connections[i].laddr[1]
                except Exception:
                    conn_loc_address = 'FAIL'
                    conn_loc_port = 'FAIL'

                try:
                    conn_rem_address = my_connections[i].raddr[0]
                    conn_rem_port = my_connections[i].raddr[1]
                except Exception:
                    conn_rem_address = 'FAIL'
                    conn_rem_port = 'FAIL'

                conn_family = my_connections[i].family
                conn_status = my_connections[i].status

                connections_list.append(
                    (conn_loc_address, conn_loc_port, conn_rem_address,
                     conn_rem_port, conn_family, conn_status))

        connections_list.sort()
        return {'LIST': connections_list, 'CONNECTIONS': len(connections_list)}
コード例 #33
0
ファイル: process_processor.py プロジェクト: fedeb95/netplot
 def process(self, packet):
     if self.config.incoming:
         ip = packet[IP].src
         port = packet[IP].dport
     else:
         ip = packet[IP].dst
         port = packet[IP].sport
     connections = psutil.net_connections()
     pid = list(
         filter(lambda item: filter_conn(item, ip, port), connections))
     if self.config.verbose_extra:
         print("PID info: " + str(pid))
     # pids should only listen on one port at a time... or not?
     if len(pid) > 0 and len(pid[0]) > 6:
         pname = psutil.Process(pid[0][6]).name()
         if self.config.show_port:
             port = str(pid[0].laddr.port)
             pidd = str(pid[0].pid)
             pname += f" PID:{pidd} PORT:{port}"
     else:
         pname = f"unknown call to {ip}"
     self.data.append(pname)
     if self.config.verbose or self.config.verbose_extra:
         print("Process " + pname)
コード例 #34
0
ファイル: tcp.py プロジェクト: yyclvps/SSTAP_ip_crawl_tool
def tcp_crawl(exe_list):
    ip_temp = []
    for name in exe_list:
        for conn in net_connections('all'):
            laddr, raddr, status, pid = conn[3:]
            if not raddr:
                continue
            try:
                filename = basename(Process(pid).exe())
            except:
                pass
            else:
                if filename == name:
                    #print('远程地址:'+str(raddr))
                    if raddr.ip != '127.0.0.1' and ':' not in raddr.ip:  #判断是否为本机地址以及剔除ipv6
                        if is_internal_ip(raddr.ip) != True:  #判断是否为内网ip
                            f_conf = open('config.txt', 'r')
                            ip_list = f_conf.read()
                            if raddr.ip not in ip_list:
                                ip_temp.append(raddr.ip)
                                print('发现新ip {}--tcp'.format(name))
                                print(raddr.ip)
                            f_conf.close()
    return (ip_temp)
コード例 #35
0
ファイル: node.py プロジェクト: imfht/flaskapps
    def get_connections(self, filters=None):
        filters = filters or {}
        connections = []

        for c in psutil.net_connections('all'):
            conn = {
                'fd': c.fd,
                'pid': c.pid,
                'family': socket_families[c.family],
                'type': socket_types[c.type],
                'local_addr_host': c.laddr[0] if c.laddr else None,
                'local_addr_port': c.laddr[1] if c.laddr else None,
                'remote_addr_host': c.raddr[0] if c.raddr else None,
                'remote_addr_port': c.raddr[1] if c.raddr else None,
                'state': c.status
            }

            for k, v in filters.iteritems():
                if v and conn.get(k) != v:
                    break
            else:
                connections.append(conn)

        return connections
コード例 #36
0
    async def netstat(self, ctx):
        """Information about the networking subsystem"""

        AD = "-"
        AF_INET6 = getattr(socket, 'AF_INET6', object())
        proto_map = {
            (AF_INET, SOCK_STREAM): 'tcp',
            (AF_INET6, SOCK_STREAM): 'tcp6',
            (AF_INET, SOCK_DGRAM): 'udp',
            (AF_INET6, SOCK_DGRAM): 'udp6',
        }
        template = "{0:<5} {1:<30} {2:<30} {3:<13} {4:<6} {5}\n"
        msg = template.format(
            "Proto", "Local address", "Remote address", "Status", "PID",
            "Program name")
        proc_names = {}
        for p in psutil.process_iter():
            try:
                proc_names[p.pid] = p.name()
            except psutil.Error:
                pass
        for c in psutil.net_connections(kind='inet'):
            laddr = "%s:%s" % c.laddr
            raddr = ""
            if c.raddr:
                raddr = "%s:%s" % c.raddr
            msg += template.format(
                proto_map[(c.family, c.type)],
                laddr,
                raddr or AD,
                c.status,
                c.pid or AD,
                proc_names.get(c.pid, '?')[:15],
            )
        await self._say(ctx, msg)
        return
コード例 #37
0
ファイル: proxy_stats.py プロジェクト: Pilarbrist/appscale
    async def get_current():
        """ Method which parses haproxy stats and returns detailed
    proxy statistics for all proxies.

    Returns:
      An instance of ProxiesStatsSnapshot.
    """
        start = time.time()

        net_connections = psutil.net_connections()
        proxy_stats_list = []
        for haproxy_process_name, info in HAPROXY_PROCESSES.items():
            logger.debug(
                "Processing {} haproxy stats".format(haproxy_process_name))
            proxy_stats_list += await get_stats_from_one_haproxy(
                info['socket'], info['configs'], net_connections)

        stats = ProxiesStatsSnapshot(utc_timestamp=time.mktime(
            datetime.now().timetuple()),
                                     proxies_stats=proxy_stats_list)
        logger.info(
            "Prepared stats about {prox} proxies in {elapsed:.1f}s.".format(
                prox=len(proxy_stats_list), elapsed=time.time() - start))
        return stats
コード例 #38
0
ファイル: psutilexample.py プロジェクト: mike-bales/dotfiles
def net_connection_memory_info(ports=[80, 443]):
    """
    Print psutil.Process.memory_info for processes with sockets open to
    the specified ports.

    Keyword Arguments:
        ports (list): list of port numbers to match

    Returns:
        None
    """
    try:
        connections = psutil.net_connections()
    except psutil.AccessDenied as e:
        logging.error("Must have permissions")
        logging.exception(e)
        raise
    pids = [cnx.pid for cnx in connections
            if cnx.raddr and cnx.raddr[-1] in ports]
    print(pids)
    pids_dict = dict.fromkeys(pids)
    processes = [x for x in psutil.process_iter() if x.pid in pids_dict]
    for p in processes:
        print(p, p.memory_info())
コード例 #39
0
ファイル: test_connections.py プロジェクト: RebortBoss/psutil
def compare_procsys_connections(pid, proc_cons, kind='all'):
    """Given a process PID and its list of connections compare
    those against system-wide connections retrieved via
    psutil.net_connections.
    """
    from psutil._common import pconn
    try:
        sys_cons = psutil.net_connections(kind=kind)
    except psutil.AccessDenied:
        # On OSX, system-wide connections are retrieved by iterating
        # over all processes
        if OSX:
            return
        else:
            raise
    # exclude PIDs from syscons
    sys_cons = [c[:-1] for c in sys_cons if c.pid == pid]
    if FREEBSD:
        # On FreeBSD all fds are set to -1 so exclude them
        # for comparison.
        proc_cons = [pconn(*[-1] + list(x[1:])) for x in proc_cons]
    proc_cons.sort()
    sys_cons.sort()
    assert proc_cons == sys_cons, (proc_cons, sys_cons)
コード例 #40
0
ファイル: os_utils.py プロジェクト: Blaze-AOSP/system_bt
def make_ports_available(ports: Container[int], timeout_seconds=10):
    """Make sure a list of ports are available
    kill occupying process if possible
    :param ports: list of target ports
    :param timeout_seconds: number of seconds to wait when killing processes
    :return: True on success, False on failure
    """
    if not ports:
        logging.warning("Empty ports is given to make_ports_available()")
        return True
    # Get connections whose state are in LISTEN only
    # Connections in other states won't affect binding as SO_REUSEADDR is used
    listening_conns_for_port = filter(
        lambda conn: (conn and conn.status == psutil.CONN_LISTEN and conn.laddr
                      and conn.laddr.port in ports), psutil.net_connections())
    success = True
    for conn in listening_conns_for_port:
        logging.warning("Freeing port %d used by %s" %
                        (conn.laddr.port, str(conn)))
        if not conn.pid:
            logging.error(
                "Failed to kill process occupying port %d due to lack of pid" %
                conn.laddr.port)
            success = False
            continue
        logging.warning("Killing pid %d that is using port port %d" %
                        (conn.pid, conn.laddr.port))
        process = psutil.Process(conn.pid)
        process.kill()
        try:
            process.wait(timeout=timeout_seconds)
        except psutil.TimeoutExpired:
            logging.error("SIGKILL timeout after %d seconds for pid %d" %
                          (timeout_seconds, conn.pid))
            continue
    return success
コード例 #41
0
ファイル: pupyps.py プロジェクト: tugdualnicolas/pupy
def connections():
    connections = []

    net_connections = psutil.net_connections()

    for connection in net_connections:
        obj = {
            k: getattr(connection, k)
            for k in ('family', 'type', 'laddr', 'raddr', 'status')
        }
        try:
            if connection.pid:
                obj.update({
                    k: to_unicode(v)
                    for k, v in psutil.Process(connection.pid).as_dict(
                        {'pid', 'exe', 'name', 'username'}).iteritems()
                })
                set_relations(obj)
        except:
            pass

        connections.append(obj)

    return connections
コード例 #42
0
 def GetNetWorkList(self, get):
     import psutil
     netstats = psutil.net_connections()
     networkList = []
     for netstat in netstats:
         tmp = {}
         if netstat.type == 1:
             tmp['type'] = 'tcp'
         else:
             tmp['type'] = 'udp'
         tmp['family'] = netstat.family
         tmp['laddr'] = netstat.laddr
         tmp['raddr'] = netstat.raddr
         tmp['status'] = netstat.status
         p = psutil.Process(netstat.pid)
         tmp['process'] = p.name()
         tmp['pid'] = netstat.pid
         networkList.append(tmp)
         del (p)
         del (tmp)
     networkList = sorted(networkList,
                          key=lambda x: x['status'],
                          reverse=True)
     return networkList
コード例 #43
0
 def _report_system_info(self):
     """
        Create the system-info.log artifact file, containing a variety of
        system information that might be useful in diagnosing test failures.
     """
     try:
         import psutil
         dir = self.query_abs_dirs()['abs_blob_upload_dir']
         self.mkdir_p(dir)
         path = os.path.join(dir, "system-info.log")
         with open(path, "w") as f:
             f.write("System info collected at %s\n\n" % datetime.now())
             f.write("\nBoot time %s\n" % datetime.fromtimestamp(psutil.boot_time()))
             f.write("\nVirtual memory: %s\n" % str(psutil.virtual_memory()))
             f.write("\nDisk partitions: %s\n" % str(psutil.disk_partitions()))
             f.write("\nDisk usage (/): %s\n" % str(psutil.disk_usage(os.path.sep)))
             if not self._is_windows():
                 # bug 1417189: frequent errors querying users on Windows
                 f.write("\nUsers: %s\n" % str(psutil.users()))
             f.write("\nNetwork connections:\n")
             try:
                 for nc in psutil.net_connections():
                     f.write("  %s\n" % str(nc))
             except Exception:
                 f.write("Exception getting network info: %s\n" % sys.exc_info()[0])
             f.write("\nProcesses:\n")
             try:
                 for p in psutil.process_iter():
                     ctime = str(datetime.fromtimestamp(p.create_time()))
                     f.write("  PID %d %s %s created at %s\n" %
                             (p.pid, p.name(), str(p.cmdline()), ctime))
             except Exception:
                 f.write("Exception getting process info: %s\n" % sys.exc_info()[0])
     except Exception:
         # psutil throws a variety of intermittent exceptions
         self.info("Unable to complete system-info.log: %s" % sys.exc_info()[0])
コード例 #44
0
def get_next_port(typ=None):
    import psutil
    try:
        conns = psutil.net_connections()
        typ = typ or socket.SOCK_STREAM
        occupied = set(sc.laddr.port for sc in conns
                       if sc.type == typ and LOW_PORT_BOUND <= sc.laddr.port <= HIGH_PORT_BOUND)
    except psutil.AccessDenied:
        import subprocess
        p = subprocess.Popen('netstat -a -n -p tcp'.split(), stdout=subprocess.PIPE)
        p.wait()
        occupied = set()
        for line in p.stdout:
            line = to_str(line)
            if '.' not in line:
                continue
            for part in line.split():
                if '.' in part:
                    _, port_str = part.rsplit('.', 1)
                    if port_str == '*':
                        continue
                    port = int(port_str)
                    if LOW_PORT_BOUND <= port <= HIGH_PORT_BOUND:
                        occupied.add(int(port_str))
                    break
        p.stdout.close()

    randn = struct.unpack('<Q', os.urandom(8))[0]
    idx = int(randn % (1 + HIGH_PORT_BOUND - LOW_PORT_BOUND - len(occupied)))
    for i in irange(LOW_PORT_BOUND, HIGH_PORT_BOUND + 1):
        if i in occupied:
            continue
        if idx == 0:
            return i
        idx -= 1
    raise SystemError('No ports available.')
コード例 #45
0
ファイル: system.py プロジェクト: johnjsb/zircon
    def read(self):

        data = []
        timestamp = int(time.time() * 1e6)

        cpu = psutil.cpu_percent(interval=self.dt, percpu=True)

        [
            data.append((timestamp, 'CPU_{}_USAGE'.format(i), val))
            for i, val in enumerate(cpu)
        ]

        connections = len(psutil.net_connections())
        data.append((timestamp, 'NUM_CONNECTIONS', connections))

        net_io = psutil.net_io_counters(True)
        disk_io = psutil.disk_io_counters(True)
        [
            data.append(
                (timestamp, '{}_SENT'.format(c.upper()), net_io[c].bytes_sent))
            for c in net_io
        ]
        [
            data.append(
                (timestamp, '{}_RECV'.format(c.upper()), net_io[c].bytes_recv))
            for c in net_io
        ]
        [
            data.append((timestamp, '{}_READ'.format(d.upper()),
                         disk_io[d].read_bytes)) for d in disk_io
        ]
        [
            data.append((timestamp, '{}_WRITE'.format(d.upper()),
                         disk_io[d].write_bytes)) for d in disk_io
        ]
        return data
コード例 #46
0
 def test_net_connections(self):
     with create_sockets():
         ret = psutil.net_connections('all')
         self.assertEqual(len(ret), len(set(ret)))
         for conn in ret:
             assert is_namedtuple(conn)
コード例 #47
0
import psutil
import platform
version = platform.python_version()

sport = 80
status_list = [
    "LISTEN", "ESTABLISHED", "TIME_WAIT", "CLOSE_WAIT", "LAST_ACK", "SYN_SENT"
]

status_temp = []
net_connections = psutil.net_connections()
for key in net_connections:
    if key.laddr[1] == sport:
        status_temp.append(key.status)

for status in status_list:
    print(status, status_temp.count(status))
コード例 #48
0
 def test_system(self):
     with create_sockets():
         for conn in psutil.net_connections(kind='all'):
             self.check_connection_ntuple(conn)
コード例 #49
0
    def get_ip_addresses(family):
        for interface, snics in psutil.net_if_addrs().items():
            for snic in snics:
                if snic.family == family:
                    yield snic.address

    hostnames = list(get_ip_addresses(socket.AF_INET))
    hostname = hostnames[0]

if param.get("ssh_server"):
    print("Installing SSH Server on {} [{}]".format(hostname, hostnames))
    ssh_password = param.get("ssh_password", "training")
    # noinspection PyBroadException
    try:
        used_ports = [i.laddr.port for i in psutil.net_connections()]
        port = [i for i in range(10022, 15000) if i not in used_ports][0]

        result = os.system(
            "apt-get install -y openssh-server && "
            "mkdir -p /var/run/sshd && "
            "echo 'root:{password}' | chpasswd && "
            "echo 'PermitRootLogin yes' >> /etc/ssh/sshd_config && "
            "sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config && "
            "sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd && "  # noqa: W605
            'echo "export VISIBLE=now" >> /etc/profile && '
            'echo "export TRAINS_CONFIG_FILE={trains_config_file}" >> /etc/profile && '
            "/usr/sbin/sshd -p {port}".format(
                password=ssh_password,
                port=port,
                trains_config_file=os.environ.get("TRAINS_CONFIG_FILE"),
コード例 #50
0
ファイル: corenlp.py プロジェクト: memray/OpenNMT-kpg-release
    def __init__(self,
                 path_or_host,
                 port=None,
                 memory='4g',
                 lang='en',
                 timeout=1500,
                 quiet=True,
                 logging_level=logging.WARNING):
        self.path_or_host = path_or_host
        self.port = port
        self.memory = memory
        self.lang = lang
        self.timeout = timeout
        self.quiet = quiet
        self.logging_level = logging_level

        logging.basicConfig(level=self.logging_level)

        # Check args
        self._check_args()

        if path_or_host.startswith('http'):
            self.url = path_or_host + ':' + str(port)
            logging.info('Using an existing server {}'.format(self.url))
        else:

            # Check Java
            if not subprocess.call(['java', '-version'],
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.STDOUT) == 0:
                raise RuntimeError('Java not found.')

            # Check if the dir exists
            if not os.path.isdir(self.path_or_host):
                raise IOError(str(self.path_or_host) + ' is not a directory.')
            directory = os.path.normpath(self.path_or_host) + os.sep
            self.class_path_dir = directory

            # Check if the language specific model file exists
            switcher = {
                'en':
                'stanford-corenlp-[0-9].[0-9].[0-9]-models.jar',
                'zh':
                'stanford-chinese-corenlp-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-models.jar',
                'ar':
                'stanford-arabic-corenlp-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-models.jar',
                'fr':
                'stanford-french-corenlp-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-models.jar',
                'de':
                'stanford-german-corenlp-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-models.jar',
                'es':
                'stanford-spanish-corenlp-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-models.jar'
            }
            jars = {
                'en': 'stanford-corenlp-x.x.x-models.jar',
                'zh': 'stanford-chinese-corenlp-yyyy-MM-dd-models.jar',
                'ar': 'stanford-arabic-corenlp-yyyy-MM-dd-models.jar',
                'fr': 'stanford-french-corenlp-yyyy-MM-dd-models.jar',
                'de': 'stanford-german-corenlp-yyyy-MM-dd-models.jar',
                'es': 'stanford-spanish-corenlp-yyyy-MM-dd-models.jar'
            }
            if len(glob.glob(directory + switcher.get(self.lang))) <= 0:
                raise IOError(
                    jars.get(self.lang) +
                    ' not exists. You should download and place it in the ' +
                    directory + ' first.')

            # If port not set, auto select
            if self.port is None:
                for port_candidate in range(9000, 65535):
                    if port_candidate not in [
                            conn.laddr[1] for conn in psutil.net_connections()
                    ]:
                        self.port = port_candidate
                        break

            # Check if the port is in use
            # if self.port in [conn.laddr[1] for conn in psutil.net_connections()]:
            #     raise IOError('Port ' + str(self.port) + ' is already in use.')

            # Start native server
            logging.info('Initializing native server...')
            cmd = "java"
            java_args = "-Xmx{}".format(self.memory)
            java_class = "edu.stanford.nlp.pipeline.StanfordCoreNLPServer"
            class_path = '"{}*"'.format(directory)

            args = [
                cmd, java_args, '-cp', class_path, java_class, '-port',
                str(self.port), '-maxCharLength', '2000000'
            ]

            args = ' '.join(args)

            logging.info(args)

            # Silence
            with open(os.devnull, 'w') as null_file:
                out_file = None
                if self.quiet:
                    out_file = null_file

                self.p = subprocess.Popen(args,
                                          shell=True,
                                          stdout=out_file,
                                          stderr=subprocess.STDOUT)
                logging.info('Server shell PID: {}'.format(self.p.pid))

            self.url = 'http://localhost:' + str(self.port)

        # Wait until server starts
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host_name = urlparse(self.url).hostname
        time.sleep(1)  # OSX, not tested
        while sock.connect_ex((host_name, self.port)):
            logging.info('Waiting until the server is available.')
            time.sleep(1)
        logging.info('The server is available.')
コード例 #51
0
    client.close()


def send(request, ip, port):
    print(request, ip, port)
    client = Client()
    client.open()
    client.send(request, ip, port)
    client.close()


#首先给服务端发一个消息,让他知道已经连上

port_list = [12378, 12346, 12349]

net_list = psutil.net_connections()
for net in net_list:
    if net.laddr.port in net_list:
        pid = net.pid
        if psutil.pid_exists(pid):
            process = psutil.Process(12378)
            print("即将杀死", 12378, "进程")
            process.kill()

print("ok!")

data = "sdfs"
ip = None
while True:
    sayHello()
    client = Client()
コード例 #52
0
ファイル: core.py プロジェクト: raul1991/ucx-py
    def create_listener(self,
                        callback_func,
                        port,
                        guarantee_msg_order,
                        endpoint_error_handling=False):
        """Create and start a listener to accept incoming connections

        callback_func is the function or coroutine that takes one
        argument -- the Endpoint connected to the client.

        In order to call ucp.reset() inside callback_func remember to
        close the Endpoint given as an argument. It is not enough to

        Also notice, the listening is closed when the returned Listener
        goes out of scope thus remember to keep a reference to the object.

        Parameters
        ----------
        callback_func: function or coroutine
            A callback function that gets invoked when an incoming
            connection is accepted
        port: int, optional
            An unused port number for listening
        guarantee_msg_order: boolean, optional
            Whether to guarantee message order or not. Remember, both peers
            of the endpoint must set guarantee_msg_order to the same value.
        endpoint_error_handling: boolean, optional
            Enable endpoint error handling raising exceptions when an error
            occurs, may incur in performance penalties but prevents a process
            from terminating unexpectedly that may happen when disabled.

        Returns
        -------
        Listener
            The new listener. When this object is deleted, the listening stops
        """
        self.continuous_ucx_progress()
        if port in (None, 0):
            # Get a random port number and check if it's not used yet. Doing this
            # without relying on `socket` allows preventing UCX errors such as
            # "none of the available transports can listen for connections", due
            # to the socket still being in TIME_WAIT state.
            try:
                with open("/proc/sys/net/ipv4/ip_local_port_range") as f:
                    start_port, end_port = [int(i) for i in next(f).split()]
            except FileNotFoundError:
                start_port, end_port = (32768, 60000)

            used_ports = set(conn.laddr[1]
                             for conn in psutil.net_connections())
            while True:
                port = randint(start_port, end_port)

                if port not in used_ports:
                    break

        logger.info("create_listener() - Start listening on port %d" % port)
        ret = Listener(
            ucx_api.UCXListener(
                worker=self.worker,
                port=port,
                cb_func=_listener_handler,
                cb_args=(
                    callback_func,
                    port,
                    self,
                    guarantee_msg_order,
                    endpoint_error_handling,
                ),
            ))
        return ret
コード例 #53
0
def get_http_connections():
    container = 0
    for item in psutil.net_connections(kind='tcp'):
        if item[3][1] == 80 and item[3][0] != '0.0.0.0':
            container += 1
    return container
コード例 #54
0
ファイル: socket-mon.py プロジェクト: sayalimore8722/CMPE273
import psutil
from collections import defaultdict
from collections import OrderedDict

addr = {}
countdict = {}
process = psutil.net_connections(kind='tcp')

addr = defaultdict(list)
for i in range(len(process)):

    if process[i].laddr and process[i].raddr:
        laddr = "%s@%s" % (process[i].laddr)
        raddr = "%s@%s" % (process[i].raddr)
        addr[process[i].pid].append([laddr, raddr, process[i].status])
i = i + 1

for mykey in addr.keys():

    countdict[mykey] = len(addr[mykey])

desc = OrderedDict(
    sorted(countdict.items(), key=lambda kv: kv[1], reverse=True))

print 'PID      ,laddr          ,raddr          ,status'
for i in desc.keys():

    for n in addr[i]:
        print "\"%s\", \"%s\", \"%s\", \"%s\"" % (i, n[0], n[1], n[2])
コード例 #55
0
ファイル: util.py プロジェクト: grenzi/ctakes_exploration
def is_port_taken(port):
    for conn in psutil.net_connections(kind='tcp'):
        if conn.laddr[1] == port and conn.status == psutil.CONN_LISTEN:
            return True
    return False
コード例 #56
0
import psutil
import socket

rede_cabeada = psutil.net_if_addrs()
socket_connections = psutil.net_connections(kind='inet')


# específica para eth0
def ip_adress():
    return rede_cabeada['enp2s0'][0][1]


# qualquer tipo de interface de rede
def get_ip_address():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    return s.getsockname()[0]
コード例 #57
0
ファイル: netstat.py プロジェクト: riag/pybee
def net_connections():
    return psutil.net_connections()
コード例 #58
0
ファイル: conftest.py プロジェクト: vyomkeshj/rsds
def check_free_port(port):
    assert isinstance(port, int)
    for conn in psutil.net_connections('tcp'):
        if conn.laddr.port == port and conn.status == "LISTEN":
            return False
    return True
コード例 #59
0
import psutil
#获取cpu信息
print(psutil.cpu_count())
print(psutil.cpu_count(logical=False))
#统计cpu用户/系统/空闲时间
print(psutil.cpu_times())
for x in range(10):
    print(psutil.cpu_percent(interval=1, percpu=True))

#获取内存信息
print(psutil.virtual_memory())
print(psutil.swap_memory())

#获取磁盘的信息
print(psutil.disk_partitions())  #磁盘分区信息
print(psutil.disk_usage('/'))  #磁盘使用情况
print(psutil.disk_io_counters())  #磁盘io

#获取网络信息
print(psutil.net_io_counters())  #获取网络读写字节/包的个数
print(psutil.net_if_addrs())  #获取网络接口信息
print(psutil.net_if_stats())  #获取网络接口状态
print(psutil.net_connections())  #获取当前网络连接信息

#获取进程信息
print(psutil.pids())  #获取所有的进程id
p = psutil.Process(7576)
print(p)
p.exe  #进程exe路径
p.cwd  #进程工作目录
コード例 #60
0
ファイル: Pmon.py プロジェクト: Unam3dd/Train-2018-2020
    def get_network_process(self, iface=None, filter_=None):
        if iface == None:
            if filter_ == None:
                table = []
                headers = [
                    "PID/NAME", "PPID/PNAME", "Address Family", "Socket Type",
                    "Listening Address:Port", "Remote Address:Port", "Status"
                ]
                p = psutil.net_connections()
                for instance in p:
                    pid = instance[6]
                    if psutil.Process(int(pid)).parent():
                        ppid = psutil.Process(int(pid)).parent().pid
                    else:
                        ppid = 0

                    laddr_section = instance[3]
                    raddr_section = instance[4]
                    pid_name = self.get_pid_name(pid)
                    if ppid != 0:
                        ppid_name = psutil.Process(int(pid)).parent().name()
                    else:
                        ppid_name = "System"
                    spid = "%d/%s" % (pid, pid_name)
                    sppid = "%d/%s" % (ppid, ppid_name)
                    family_addr = instance[1].name
                    socket_type = instance[2].name

                    if laddr_section:
                        laddr = laddr_section[0]
                        lport = laddr_section[1]
                        saddr_port = "%s:%s" % (laddr, lport)
                    else:
                        laddr = "NULL"
                        lport = "NULL"
                        saddr_port = "%s:%s" % (laddr, lport)

                    if raddr_section:
                        raddr = raddr_section[0]
                        rport = raddr_section[1]
                        taddr_port = "%s:%s" % (raddr, rport)
                    else:
                        raddr = "NULL"
                        rport = "NULL"
                        taddr_port = "%s:%s" % (raddr, rport)

                    status = instance[5]
                    table.append([
                        spid, sppid, family_addr, socket_type, saddr_port,
                        taddr_port, status
                    ])

                print(tabulate(table, headers=headers, tablefmt="fancy_grid"))
            else:
                f = filter_
                table = []
                headers = [
                    "PID/NAME", "PPID/PNAME", "Address Family", "Socket Type",
                    "Listening Address:Port", "Remote Address:Port", "Status"
                ]
                p = psutil.net_connections()
                for instance in p:
                    pid = instance[6]
                    if psutil.Process(int(pid)).parent():
                        ppid = psutil.Process(int(pid)).parent().pid
                    else:
                        ppid = 0

                    laddr_section = instance[3]
                    raddr_section = instance[4]
                    pid_name = self.get_pid_name(pid)
                    if ppid != 0:
                        ppid_name = psutil.Process(int(pid)).parent().name()
                    else:
                        ppid_name = "System"

                    spid = "%d/%s" % (pid, pid_name)
                    sppid = "%d/%s" % (ppid, ppid_name)
                    family_addr = instance[1].name
                    socket_type = instance[2].name

                    if laddr_section:
                        laddr = laddr_section[0]
                        lport = laddr_section[1]
                        saddr_port = "%s:%s" % (laddr, lport)
                    else:
                        laddr = "NULL"
                        lport = "NULL"
                        saddr_port = "%s:%s" % (laddr, lport)

                    if raddr_section:
                        raddr = raddr_section[0]
                        rport = raddr_section[1]
                        taddr_port = "%s:%s" % (raddr, rport)
                    else:
                        raddr = "NULL"
                        rport = "NULL"
                        taddr_port = "%s:%s" % (raddr, rport)

                    status = instance[5]
                    if pid_name == f:
                        table.append([
                            spid, sppid, family_addr, socket_type, saddr_port,
                            taddr_port, status
                        ])
                    else:
                        pass

                print(tabulate(table, headers=headers, tablefmt="fancy_grid"))

        else:
            if filter_ == None:
                table = []
                headers = [
                    "PID/NAME", "PPID/PNAME", "Address Family", "Socket Type",
                    "Listening Address:Port", "Remote Address:Port", "Status"
                ]
                p = psutil.net_connections(iface)
                for instance in p:
                    pid = instance[6]
                    if psutil.Process(int(pid)).parent():
                        ppid = psutil.Process(int(pid)).parent().pid
                    else:
                        ppid = 0
                    ppid = psutil.Process(int(pid)).parent().pid
                    laddr_section = instance[3]
                    raddr_section = instance[4]
                    pid_name = self.get_pid_name(pid)
                    if ppid != 0:
                        ppid_name = psutil.Process(int(pid)).parent().name()
                    else:
                        ppid_name = "System"
                    spid = "%d/%s" % (pid, pid_name)
                    sppid = "%d/%s" % (ppid, ppid_name)
                    family_addr = instance[1].name
                    socket_type = instance[2].name

                    if laddr_section:
                        laddr = laddr_section[0]
                        lport = laddr_section[1]
                        saddr_port = "%s:%s" % (laddr, lport)
                    else:
                        laddr = "NULL"
                        lport = "NULL"
                        saddr_port = "%s:%s" % (laddr, lport)

                    if raddr_section:
                        raddr = raddr_section[0]
                        rport = raddr_section[1]
                        taddr_port = "%s:%s" % (raddr, rport)
                    else:
                        raddr = "NULL"
                        rport = "NULL"
                        taddr_port = "%s:%s" % (raddr, rport)

                    status = instance[5]
                    table.append([
                        spid, sppid, family_addr, socket_type, saddr_port,
                        taddr_port, status
                    ])

                print(tabulate(table, headers=headers, tablefmt="fancy_grid"))

            else:
                f = filter_
                table = []
                headers = [
                    "PID/NAME", "PPID/PNAME", "Address Family", "Socket Type",
                    "Listening Address:Port", "Remote Address:Port", "Status"
                ]
                p = psutil.net_connections()
                for instance in p:
                    pid = instance[6]
                    if psutil.Process(int(pid)).parent():
                        ppid = psutil.Process(int(pid)).parent().pid
                    else:
                        ppid = 0
                    ppid = psutil.Process(int(pid)).parent().pid
                    laddr_section = instance[3]
                    raddr_section = instance[4]
                    pid_name = self.get_pid_name(pid)
                    if ppid != 0:
                        ppid_name = psutil.Process(int(pid)).parent().name()
                    else:
                        ppid_name = "System"

                    spid = "%d/%s" % (pid, pid_name)
                    sppid = "%d/%s" % (ppid, ppid_name)
                    family_addr = instance[1].name
                    socket_type = instance[2].name

                    if laddr_section:
                        laddr = laddr_section[0]
                        lport = laddr_section[1]
                        saddr_port = "%s:%s" % (laddr, lport)
                    else:
                        laddr = "NULL"
                        lport = "NULL"
                        saddr_port = "%s:%s" % (laddr, lport)

                    if raddr_section:
                        raddr = raddr_section[0]
                        rport = raddr_section[1]
                        taddr_port = "%s:%s" % (raddr, rport)
                    else:
                        raddr = "NULL"
                        rport = "NULL"
                        taddr_port = "%s:%s" % (raddr, rport)

                    status = instance[5]
                    if pid_name == f:
                        table.append([
                            spid, sppid, family_addr, socket_type, saddr_port,
                            taddr_port, status
                        ])
                    else:
                        pass

                print(tabulate(table, headers=headers, tablefmt="fancy_grid"))