Real-time monitoring of active TCP ports used by a specific process (PID)
Project description
ProcessPortMonitor
ProcessPortMonitor is a Python package that allows you to monitor active TCP ports used by a specific process (PID) in real-time. It provides both a command-line interface (CLI) and an importable module for integration into your Python scripts. The package can asynchronously track port changes, trigger callbacks when changes occur, and maintain a history of port activity with timestamps.
Table of Contents
Features
- Real-Time Monitoring: Continuously monitors active TCP ports used by a specific PID.
- Asynchronous Operation: Runs in a separate thread to avoid blocking your main program.
- Callback Mechanism: Triggers a user-defined callback function when port changes are detected.
- Port History Tracking: Maintains a history of port additions and removals with timestamps.
- Command-Line Interface: Provides a convenient CLI for quick monitoring from the terminal.
- Python Module: Can be imported and used within your Python applications without terminal output.
Installation
Prerequisites
- Python 3.6 or higher
lsofcommand: Available on most Unix-like systems (macOS, Linux).jclibrary: JSON Convert library for parsing command output.
Install Using pip
pip3 install ProcessPortMonitor
Alternatively, you can install from source:
-
Clone the Repository
git clone https://github.com/yourusername/ProcessPortMonitor.git
-
Navigate to the Package Directory
cd ProcessPortMonitor
-
Install the Package
pip3 install .
Usage
Command-Line Interface
Basic Usage
Run ProcessPortMonitor followed by the PID of the process you wish to monitor. You may need to run the command with sudo to have the necessary permissions.
sudo ProcessPortMonitor <PID>
Options
--interval INTERVAL: Set the monitoring interval in seconds (default is 1.0 second).
sudo ProcessPortMonitor <PID> --interval 0.5
Example
sudo ProcessPortMonitor 16609 --interval 1
Output:
Monitoring active ports for PID 16609 every 1.0 second(s). Press Ctrl+C to stop.
New ports opened: {50260}
Active ports: {50260}
New ports opened: {50390}
Active ports: {50260, 50390}
Ports closed: {50260}
Active ports: {50390}
As a Python Module
Basic Usage (Module)
Import the ProcessPortMonitor class into your Python script and create an instance to monitor a specific PID.
from ProcessPortMonitor import ProcessPortMonitor
import time
def my_callback(new_ports, closed_ports, active_ports, port_history):
# Handle port changes here
if new_ports:
print(f"Ports added: {new_ports}")
if closed_ports:
print(f"Ports removed: {closed_ports}")
# You can also process active_ports and port_history as needed
pid_to_monitor = 16609 # Replace with the actual PID
monitor = ProcessPortMonitor(pid_to_monitor, interval=1.0, callback=my_callback)
monitor.start()
try:
while True:
# Your main program logic here
time.sleep(1)
except KeyboardInterrupt:
monitor.stop()
print("Stopped monitoring.")
Customizing the Callback Function
The callback function should accept four parameters:
new_ports: A set of ports that have been added since the last check.closed_ports: A set of ports that have been closed since the last check.active_ports: The current set of active ports.port_history: A list of dictionaries containing the history of port changes with timestamps.
Example of a callback function:
def my_callback(new_ports, closed_ports, active_ports, port_history):
if new_ports:
print(f"New ports opened: {new_ports}")
if closed_ports:
print(f"Ports closed: {closed_ports}")
print(f"Current active ports: {active_ports}")
# Optionally, process port_history
Accessing Port History
The port_history attribute of the ProcessPortMonitor instance stores the history of port changes.
# Access the port history
print(monitor.port_history)
Each entry in port_history is a dictionary:
{
'timestamp': '2023-10-03T12:00:00.000000',
'port': 50260,
'action': 'added' # or 'removed'
}
Examples
Example CLI Session
sudo ProcessPortMonitor 12345 --interval 0.5
Output:
Monitoring active ports for PID 12345 every 0.5 second(s). Press Ctrl+C to stop.
New ports opened: {8080}
Active ports: {8080}
Ports closed: {8080}
Active ports: set()
Example Python Script
from ProcessPortMonitor import ProcessPortMonitor
import time
def log_port_changes(new_ports, closed_ports, active_ports, port_history):
if new_ports:
print(f"[+] Ports opened: {new_ports}")
if closed_ports:
print(f"[-] Ports closed: {closed_ports}")
print(f"[=] Current ports: {active_ports}")
pid = 12345
monitor = ProcessPortMonitor(pid, interval=0.5, callback=log_port_changes)
monitor.start()
try:
while True:
# Main application logic
time.sleep(1)
except KeyboardInterrupt:
monitor.stop()
print("Monitoring stopped.")
Requirements
- Python 3.6 or higher
lsofcommand: The script useslsofto retrieve active TCP connections.jclibrary: Install viapip3 install jc.
Limitations
- Permissions: Monitoring processes other than your own may require root privileges.
- Platform Compatibility: Designed for Unix-like systems (macOS, Linux) with
lsofavailable. - System Resources: Frequent monitoring intervals may impact system performance due to repeated
lsofcalls. - TCP Connections Only: Currently monitors TCP connections in the
ESTABLISHEDstate.
License
ProcessPortMonitor is released under the MIT License.
Contributing
Contributions are welcome! Please submit a pull request or open an issue to discuss improvements or report bugs.
Contact
For questions or support, please open an issue on the GitHub repository or contact the maintainer at batu.bora.tech@gmail.com.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file processportmonitor-0.1.6.tar.gz.
File metadata
- Download URL: processportmonitor-0.1.6.tar.gz
- Upload date:
- Size: 6.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a580b292c629bd1f269e0e37e992fe7e25283dfd597cdb00709cec58289fe1eb
|
|
| MD5 |
ec434b27704f8053529eb473d2e567b8
|
|
| BLAKE2b-256 |
0aca9b38857cb6565de9f0a616fe6262d3709b149efa727e6999adde1934eac8
|
Provenance
The following attestation bundles were made for processportmonitor-0.1.6.tar.gz:
Publisher:
publish.yml on cenab/processportmonitor
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
processportmonitor-0.1.6.tar.gz -
Subject digest:
a580b292c629bd1f269e0e37e992fe7e25283dfd597cdb00709cec58289fe1eb - Sigstore transparency entry: 150983221
- Sigstore integration time:
-
Permalink:
cenab/processportmonitor@e64da26a19161944c1d0c9dbf1447fffcd999941 -
Branch / Tag:
refs/tags/v0.1.6 - Owner: https://github.com/cenab
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@e64da26a19161944c1d0c9dbf1447fffcd999941 -
Trigger Event:
release
-
Statement type:
File details
Details for the file processportmonitor-0.1.6-py3-none-any.whl.
File metadata
- Download URL: processportmonitor-0.1.6-py3-none-any.whl
- Upload date:
- Size: 7.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c65d8275939a21f6a311afc273905a877888f015abe226d2adb2e4d28c48f836
|
|
| MD5 |
9392063aab3e304acf090fef75e9835c
|
|
| BLAKE2b-256 |
45ba22d592e7def78d531a9ce3dbbe8f68eabc9bf06d0e89295456fa07a47949
|
Provenance
The following attestation bundles were made for processportmonitor-0.1.6-py3-none-any.whl:
Publisher:
publish.yml on cenab/processportmonitor
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
processportmonitor-0.1.6-py3-none-any.whl -
Subject digest:
c65d8275939a21f6a311afc273905a877888f015abe226d2adb2e4d28c48f836 - Sigstore transparency entry: 150983222
- Sigstore integration time:
-
Permalink:
cenab/processportmonitor@e64da26a19161944c1d0c9dbf1447fffcd999941 -
Branch / Tag:
refs/tags/v0.1.6 - Owner: https://github.com/cenab
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@e64da26a19161944c1d0c9dbf1447fffcd999941 -
Trigger Event:
release
-
Statement type: