0
votes

I want to make a script, that will

  1. Determine which ports are running.
  2. Kill the process running on the port, will take a port number as an argument.

I completed the first task, but the 2nd task has some problems. This thread suggests that lsof is not cross-platform making this problem somewhat impossible to solve.

I then tried using netstat -b from python to list ut PIDs but it requires privileges, which am not sure how to do that by using the subprocess module.

tcpview and tcpvcon arent helpful either. Using tcpvcon -a 443 for some reason returns nothing.

I am not sure if psutil module can help either, I know how to find a PID using it, but not sure how to find PIDs according to a specific port.

Is there any cross-platfrom way to do that? Maybe call a Bash script from python?

1

1 Answers

1
votes

I found the solution, had to hardcode using psutil module.

import psutil
import sys

def get_pid():
    connections = psutil.net_connections()
    port = int(sys.argv[1])
    for con in connections:
        if con.raddr != tuple():
            if con.raddr.port == port:
                return con.pid, con.status
        if con.laddr != tuple():
            if con.laddr.port == port:
                return con.pid, con.status
    return -1

if __name__ == '__main__':
    if len(sys.argv) > 1:
        pid = get_pid()
        if pid == -1:
            print(":: Not Found :<")
        else:
            print(f"Found service on Port {sys.argv[1]}")
            print(f"[+] PID: {pid[0]}")
            print(f"[+] Status: {pid[1]}")
            ch = input("Wanna Close: (y/n) ")
            if ch.lower() == 'y':
                p = psutil.Process(pid[0])
                p.terminate()