code to see who is listening to your device

Code:

import tkinter as tk
from tkinter import ttk, scrolledtext
import threading
import time
import sys
import subprocess
import platform

try:
import pyaudio
import numpy as np
except ImportError:
pyaudio = None
np = None

import psutil


class PrivacyGuardApp:
def __init__(self, root):
self.root = root
self.root.title(“Privacy Guard – No Listening”)
self.root.geometry(“700×600”)
self.root.resizable(True, True)

# Monitoring flags
self.mic_monitoring = False
self.mic_thread = None
self.audio = None
self.stream = None

# Build GUI
self.create_widgets()

# Start network monitoring (refreshes every 5 sec)
self.refresh_network()
self.root.after(5000, self.schedule_network_refresh)

def create_widgets(self):
# ———- Microphone section ———-
mic_frame = ttk.LabelFrame(self.root, text=”Microphone Listening Status”, padding=10)
mic_frame.pack(fill=tk.X, padx=10, pady=5)

self.mic_status_label = ttk.Label(mic_frame, text=”Status: Not monitoring”, font=(“Arial”, 10))
self.mic_status_label.pack(anchor=tk.W)

self.mic_level_label = ttk.Label(mic_frame, text=”Current level: — dB”, font=(“Arial”, 10))
self.mic_level_label.pack(anchor=tk.W, pady=(5,0))

self.mic_progress = ttk.Progressbar(mic_frame, length=400, mode=’determinate’, maximum=100)
self.mic_progress.pack(anchor=tk.W, pady=5)

btn_frame = ttk.Frame(mic_frame)
btn_frame.pack(anchor=tk.W, pady=5)

self.start_mic_btn = ttk.Button(btn_frame, text=”Start Mic Monitor”, command=self.start_mic_monitoring)
self.start_mic_btn.pack(side=tk.LEFT, padx=2)

self.stop_mic_btn = ttk.Button(btn_frame, text=”Stop Mic Monitor”, command=self.stop_mic_monitoring, state=tk.DISABLED)
self.stop_mic_btn.pack(side=tk.LEFT, padx=2)

self.mute_mic_btn = ttk.Button(btn_frame, text=”Mute Microphone (System)”, command=self.mute_microphone)
self.mute_mic_btn.pack(side=tk.LEFT, padx=2)

# Warning label for missing PyAudio
if pyaudio is None or np is None:
warn = ttk.Label(mic_frame, text=”⚠ PyAudio or numpy not installed – microphone monitoring disabled.”,
foreground=”red”)
warn.pack(anchor=tk.W)
self.start_mic_btn.config(state=tk.DISABLED)
self.mute_mic_btn.config(state=tk.DISABLED)

# ———- Network listening ports section ———-
net_frame = ttk.LabelFrame(self.root, text=”Network Ports Listening to Outside World”, padding=10)
net_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

self.net_text = scrolledtext.ScrolledText(net_frame, height=12, width=80, wrap=tk.WORD)
self.net_text.pack(fill=tk.BOTH, expand=True)

refresh_btn = ttk.Button(net_frame, text=”Refresh Now”, command=self.refresh_network)
refresh_btn.pack(pady=5)

# ———- Instructions ———-
info_frame = ttk.LabelFrame(self.root, text=”How to be sure”, padding=10)
info_frame.pack(fill=tk.X, padx=10, pady=5)

info_text = (
“• Microphone level near 0 dB → microphone is silent (no sound captured).\n”
“• Use ‘Mute Microphone’ to disable the mic at system level (Windows/macOS only).\n”
“• Network ports listening on 0.0.0.0 or :: are reachable from other devices.\n”
“• To close a listening port, stop the associated program (e.g., web server).\n”
“• For complete privacy: physically disconnect microphone or use hardware kill switch.”
)
ttk.Label(info_frame, text=info_text, justify=tk.LEFT).pack(anchor=tk.W)

# ———- Microphone monitoring ———-
def start_mic_monitoring(self):
if self.mic_monitoring:
return
if pyaudio is None or np is None:
return

try:
self.audio = pyaudio.PyAudio()
self.stream = self.audio.open(format=pyaudio.paInt16,
channels=1,
rate=44100,
input=True,
frames_per_buffer=1024,
stream_callback=None)
self.mic_monitoring = True
self.mic_thread = threading.Thread(target=self._mic_loop, daemon=True)
self.mic_thread.start()
self.start_mic_btn.config(state=tk.DISABLED)
self.stop_mic_btn.config(state=tk.NORMAL)
self.mic_status_label.config(text=”Status: Monitoring (listening for sound)”, foreground=”green”)
except Exception as e:
self.mic_status_label.config(text=f”Error: {e}”, foreground=”red”)

def stop_mic_monitoring(self):
self.mic_monitoring = False
if self.stream:
self.stream.stop_stream()
self.stream.close()
if self.audio:
self.audio.terminate()
self.start_mic_btn.config(state=tk.NORMAL)
self.stop_mic_btn.config(state=tk.DISABLED)
self.mic_status_label.config(text=”Status: Not monitoring”, foreground=”black”)
self.mic_level_label.config(text=”Current level: — dB”)
self.mic_progress[‘value’] = 0

def _mic_loop(self):
while self.mic_monitoring and self.stream.is_active():
try:
data = self.stream.read(1024, exception_on_overflow=False)
# Convert bytes to numpy int16 array
samples = np.frombuffer(data, dtype=np.int16)
if len(samples) > 0:
# RMS value as a rough sound level
rms = np.sqrt(np.mean(samples.astype(np.float64)**2))
# Convert to dB (0 dB = maximum possible for int16 = 32768)
if rms < 1e-5:
db = -100
else:
db = 20 * np.log10(rms / 32768.0)
# Clip and map to 0-100% for progress bar
percent = min(100, max(0, int((db + 100) / 50 * 100)))
self.root.after(0, self._update_mic_ui, db, percent)
else:
self.root.after(0, self._update_mic_ui, -100, 0)
except Exception:
pass
time.sleep(0.1)

def _update_mic_ui(self, db, percent):
self.mic_level_label.config(text=f”Current level: {db:.1f} dB”)
self.mic_progress[‘value’] = percent
# Color hint: if > -40 dB, there is significant sound
if db > -40:
self.mic_status_label.config(text=”Status: Monitoring – MIC IS CAPTURING SOUND”, foreground=”red”)
else:
self.mic_status_label.config(text=”Status: Monitoring – microphone appears silent”, foreground=”green”)

# ———- System microphone mute (platform specific) ———-
def mute_microphone(self):
sys_name = platform.system()
try:
if sys_name == “Windows”:
# Uses nircmd (small tool) or pycaw? Provide simple alternative: show warning
# For simplicity, we’ll open Windows Sound settings and instruct user.
subprocess.run(“start ms-settings:sound”, shell=True)
tk.messagebox.showinfo(“Mute Microphone”,
“Please mute the microphone in the Sound Settings window that opened.\n”
“Alternatively, use the physical mute button on your headset/mic.”)
elif sys_name == “Darwin”: # macOS
# Use osascript to set input volume to 0
script = ‘set volume input volume 0’
subprocess.run([“osascript”, “-e”, script])
tk.messagebox.showinfo(“Muted”, “Microphone input volume set to 0 (muted).”)
elif sys_name == “Linux”:
# Try using amixer
subprocess.run([“amixer”, “set”, “Capture”, “nocap”], check=False)
tk.messagebox.showinfo(“Muted”, “Attempted to mute microphone via amixer.”)
else:
tk.messagebox.showwarning(“Unsupported”, f”Automatic muting not implemented for {sys_name}.”)
except Exception as e:
tk.messagebox.showerror(“Error”, f”Could not mute microphone: {e}”)

# ———- Network monitoring (listening ports) ———-
def refresh_network(self):
self.net_text.delete(1.0, tk.END)
listening = []
try:
for conn in psutil.net_connections(kind=’inet’):
if conn.status == ‘LISTEN’:
# laddr = (ip, port)
ip = conn.laddr.ip
port = conn.laddr.port
# Determine if it listens on external interface
external = ip in (‘0.0.0.0’, ‘::’) or ip.startswith(‘::’)
pid = conn.pid
pname = “”
if pid:
try:
p = psutil.Process(pid)
pname = p.name()
except (psutil.NoSuchProcess, psutil.AccessDenied):
pname = “unknown”
listening.append((ip, port, external, pid, pname))
except (psutil.AccessDenied, Exception) as e:
self.net_text.insert(tk.END, f”Error reading network connections: {e}\n”)
self.net_text.insert(tk.END, “Run as administrator/root to see all ports.\n”)
self.root.after(5000, self.schedule_network_refresh)
return

if not listening:
self.net_text.insert(tk.END, “No listening ports found (or insufficient privileges).\n”)
else:
header = f”{‘IP Address’:<20} {‘Port’:<8} {‘External?’:<10} {‘PID’:<8} {‘Process’:<20}\n”
self.net_text.insert(tk.END, header)
self.net_text.insert(tk.END, “-” * 70 + “\n”)
for ip, port, external, pid, pname in listening:
ext_str = “YES (outside)” if external else “Loopback only”
self.net_text.insert(tk.END, f”{ip:<20} {port:<8} {ext_str:<14} {pid:<8} {pname:<20}\n”)
self.net_text.insert(tk.END, “\n⚠ Ports marked ‘YES (outside)’ are reachable from other devices.\n”)
self.net_text.insert(tk.END, “Close the associated program to stop listening.\n”)

self.root.after(5000, self.schedule_network_refresh)

def schedule_network_refresh(self):
if hasattr(self, ‘root’) and self.root.winfo_exists():
self.refresh_network()
self.root.after(5000, self.schedule_network_refresh)


if __name__ == “__main__”:
root = tk.Tk()
app = PrivacyGuardApp(root)
root.mainloop() ”

https://www.linkedin.com/in/kadiruludag19/?originalSubdomain=cn

Leave a Reply