Friday, July 29, 2022

Python: A simple script to closed Ports in Windows 10

Any open port in Windows can be used by hackers to either upload malware, trojan, or may be used to control the machine  so it is important to close ports that are opened and not being used by the system.

I have prepared a simple python script to automate the process. I only closed those ports that are in "LISTENING" status, I also checked that certain ports are being used by the system and identified them in Task Manager via PID and tried to end the task. I also tried to killed the tasks associated with the port but not forcefully. The simple script is self explanatory because it is very short and simple.

To manually close a port, follow this path:

Start->Control Panel -> Windows Firewall -> Advance Settings -> Inbound Rules -> New Rule -> Port -> UDP/TCP -> Port Number -> Block Connection -> Rule Name 

Type the following at command prompt(Run as Admin) to display list of TCP and UDP ports currently listening on the computer with PID:

netstat -a -o -n


 

You must have admin rights to run the program or if you run it in command prompt, you should run it as Administrator.

Here is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import os

cmd = 'netstat -a -o -n > ports.txt'
os.system('cmd /c "'+ cmd + '"')
message=open(r'C:\temp\ports.txt', 'r')
lines =message.readlines()
message.close()
i=0
eports = '135 445 139'
pid = '4'
iport=[]
for line in lines:
   line = line.strip()
   if i>3:
     x = line.split(':')
     if line.find('[::]') != -1 and line.find('LISTENING') != -1:
        x = line.split(':')
        x[1]=x[3]
        x[2]=x[6]
     
     if x[2].find('LISTENING') != -1:
          y = x[1]          
          y = y[0:5]
          y = y.strip()
          
          z = x[2].split()
          a=z[-1]
          #print(a)
          if a != pid or eports.find(y) == -1:
             iport.append(y)
             os.system('taskkill /pid ' + a)
   i+=1 
iport = list(dict.fromkeys(iport))
for ports in iport:
   os.system('netsh advfirewall firewall add rule name="' + ports + 'port' + '" protocol=TCP dir=out remoteport=' + ports + ' action=block')
    
      
     

No comments:

Post a Comment