Как закрыть порты в windows 10 через cmd

Open ports in Windows 10 are often deemed dangerous because hackers can exploit them if the service or application the ports are associated with are unpatched or lack basic security protocols. Therefore, it is recommended to close any listening network ports that your system isn’t using.

Let us brief you on what ports are and why they can be dangerous.

Table of Contents

What are network ports?

Network ports are used by Windows services and applications to send and receive data over the network. If you wonder if this is what the IP address is used for, then you are absolutely correct. However, a unique IP address defines the path to a specific device, whereas a port defines what application or service on that particular device to send that information to.

Just like the IP addresses, a port is also unique within its ecosystem. Meaning, the same port cannot be used by two different services/applications. Therefore, both of these unique identifiers, the IP address, and the port number, are used to send and receive information from a computer.

A port number can be found suffixed to an IP address, as in the example below:

xxx.xxx.xxx.xxx:80

Here, the numbers followed by the colon denote the port number. Below are a few ports used by certain services and applications by default:

  • FTP – 21
  • SSH – 22
  • Telnet – 23
  • SMTP – 25
  • DNS – 53
  • DHCP – 67 & 68
  • HTTP – 80 & 8080
  • HTTPS – 443
  • SNMP – 161
  • RDP – 3389

A single IP address can have 65535 TCP and 65535 UDP ports in total.

Are open network ports dangerous?

Not all ports that are listening are dangerous. Sometimes an application opens the ports automatically without informing the users. If the application is poorly constructed and the security protocols lack the basic infrastructure, an attacker might exploit those and infiltrate your PC.

An open networking port is not always dangerous, but it is always better to keep your guard up and close any ports that are not required.

2 ways to check which ports are open/listening in Windows 10

You can figure out which ports are currently open on your computer, even if the installed applications did not inform you that they are using them. Here are 2 ways to check which ports are open and which service/application uses them on your local computer before you proceed to block them.

Here is a guide to check if a remote network port is open.

Determine open ports with process name using Command Prompt

Some applications give out the name of the application/service associated with a port number. You can use the below-given command in Command Prompt to determine which ports are open and what are the names of the associated applications.

  1. Open Command Prompt with administrative privileges.
  2. Enter the following command:
    netstat -ab
  3. Command Prompt will now display the output of open network ports with their associated application/service names, as in the image below:
    cmd 1 1

Since the IP address assigned to our computer is 10.0.0.31, it displays different ports used by various applications suffixed to the IP address. However, as you may notice, some of the names of the services and applications are unidentifiable. For that, we shall adopt the second method.

Determine open ports with process ID using Command Prompt

In this approach, we shall be comparing the process IDs of the running applications and services associated with the ports and then determining the name of the process using the Task Manager. Here is how to do so:

  1. Open Command Prompt with administrative privileges.
  2. Enter the following command:
    netstat -aon
  3. Command Prompt will now display a list of TCP and UDP ports currently listening on your computer. Note the associated PIDs to compare from the Task Manager.
    PID

  4. Now open the Task Manager by right-clicking on the Taskbar and clicking on Task Manager. Or, you may use the Ctrl + Shift + Esc shortcut keys.
  5. Now switch to the Details tab within the Task Manager and match the PID with the associated name of the process/application.
    task manager

Now you have sufficient information on the ports you would like to close, if any. Proceed to the next step to block/close any listening ports on your computer.

How to close an open port

If you have found a port that you are no longer using or are not sure if it is secure to keep open, you should preferably block it. If you wish to close an open port, you can do so with Windows Firewall  or Windows Defender in case of Windows 10.

  1. Open the Windows Firewall by going to Start –> Control Panel –> Windows Firewall. If you are using Windows 10, you can open the Windows Defender Firewall by going to Run –> firewall.cpl.
  2. From the left side menu, click on Advanced settings.
  3. From the right side menu of the new window, select Inbound Rules.
    New Rule

  4. Then click New rule in the right pane.
  5. On the Rule type screen in New inbound rule wizard, select Port and then click Next.
    port

  6. On the next screen, select the type of port as determined through the Command Prompt earlier, and then enter the port number you want to close in front of Specific local ports. Click Next when done.
    local port

  7. On the next screen, select Block the connection and then click Next.
  8. On the Profile screen, select All Profiles and click Next.
    profiles

  9. Now set a name for the rule and click Finish.

You have now successfully disabled the port. You can repeat the steps to block additional ports or delete this one by navigating to the Inbound rules and removing the respective rules.

How to quickly close ports using Command Prompt

A couple of commands can be used to identify the processes that have opened the ports and then close the ports by killing the process.

  1. Open Command Prompt and run the command: netstat -a -o -n. This will show all the open ports in your system along with their current state and the process ID that have opened the ports.
  2. If you want to find a specific port, you should run the command: netstat -a -o -n | findstr “993”. Replace 993 with the port number you want to find.
    Find open ports in cmd

  3. The last column on the list is the Process ID or PID number. Killing the process will automatically close the listening port. To kill the process, run the command: taskkill /pid 993.
    Kill the process to close ports

Please note that this is a quick and temporary way of closing the port using the command prompt. If you want to permanently block the port from opening again, you should follow the first method given above.

How to block network ports in Windows Firewall using Command Prompt

Block port in Windows Firewall using command line

You can also permanently block ports in Windows Defender Firewall using the Command Prompt.

To create a block port rule in Windows Firewall, run the following command in Command Prompt:

netsh advfirewall firewall add rule name="Rule Name" protocol=TCP dir=out remoteport=993 action=block

Replace Rule Name with your own rule name, for example, since I’m blocking IMAP port, I’ll name the rule as Block IMAP. Replace TCP with either RCP or UDP, whichever port you want to block. Replace 993 with the actual port number you want to block.

Unblock/Open port in Windows Firewall using command line

To open the port again, simply run the following command in CMD:

netsh advfirewall firewall delete rule name="Rule Name"

Replace Rule Name with the actual rule name, Block IMAP in my case. This will delete the rule that we created above.

Closing words

Listening ports are not always dangerous, as it is very much dependent on what application/service it is open through. Nonetheless, it is still important not to give the attacker any chance to exploit your system’s vulnerabilities and wise to close any ports that are not being used.

Способ 1: Штатный брандмауэр

Как правило, чаще всего для закрытия или открытия портов в Windows 10 используют встроенный в систему брандмауэр.

  1. Откройте штатный брандмауэр в режиме повышенной безопасности, для чего выполните команду wf.msc в диалоговом окошке, вызываемом клавишами Win + R.
  2. Как закрыть порты в Windows 10-1

  3. Если порт закрывается только для входящего трафика, в левой колонке файрвола необходимо выбрать «Правила для входящих подключений», а если только для исходящих — «Правила для исходящих подключений».
  4. Как закрыть порты в Windows 10-2

  5. В правой колонке нажмите «Создать правило».
  6. Как закрыть порты в Windows 10-3

  7. В открывшемся окошке мастера создания правила выберите пункт «Для порта» и нажмите «Далее».
  8. Как закрыть порты в Windows 10-4

  9. В следующем окне выберите тип протокола «Протокол TCP», включите радиокнопку «Определенные локальные порты» и укажите номер открываемого порта, например 445. Если портов несколько, укажите их через запятую. Нажмите «Далее».
  10. Как закрыть порты в Windows 10-5

  11. Выберите режим блокировки и нажмите «Далее».
  12. Как закрыть порты в Windows 10-6

  13. В следующем окне ничего менять не нужно, по умолчанию блокируются порты всех трех профилей: доменного, частного и публичного.
  14. Как закрыть порты в Windows 10-7

  15. Наконец, дайте новому правилу подходящее для данного случая имя. Описание давать не обязательно. Нажмите кнопку «Готово».
  16. Как закрыть порты в Windows 10-8

Аналогичным способом можно создать правило закрытия порта для исходящих подключений.

Способ 2: Консоль «PowerShell»

Закрыть порт можно также средствами консольной утилиты «netsh», работающей из интерфейса «PowerShell» или классической «Командной строки».

  1. Запустите «PowerShell» от имени администратора из контекстного меню кнопки «Пуск».
  2. Как закрыть порты в Windows 10-9

  3. Сформируйте и выполните команду следующего вида: netsh advfirewall firewall add rule dir=in action=block protocol=TCP localport=445 name="Блокировка порта 445".
  4. Как закрыть порты в Windows 10-10

В качестве значения параметра «localport» указывается номер блокируемого порта, значение «in» для параметра dir указывает на то, что правило создается для входящих подключений.

Закрыть порт в Windows 10 можно средствами любого стороннего файрвола, если таковой установлен. Что же касается узкоспециализированных утилит, от их использования желательно воздержаться, так как большинство из них устарело и работает некорректно в новых Windows.

Наша группа в TelegramПолезные советы и помощь

If you are a network engineer or a normal user, you may need to find, open or block a virtual port, such as a TCP or a UDP port for an application. Virtual ports help you manage your network hardware and software with respect to the information traffic. In a layman’s language, virtual ports serve as the dedicated lanes for particular traffic such as website traffic, receiving emails, transfer of files and so on.

There are basically two types of virtual ports, namely TCP and UDP. TCP stands for Transmission Control Protocol; while UDP stands for User Datagram Protocol. TCP and UDP ports use different network protocols when handling information traffic. Network protocols are nothing but the set of rules and regulations of how certain information should be sent and received. However, the basis of a TCP or UDP port is IP, i.e. Internet Protocol.

Let’s see how these two ports defer in their features and functions.

How does a TPC port work?

A TCP port requires users to establish a connection between the sender’s machine and the receiver’s machine. It is quite similar to making a phone call. Once the connection is established between the sender and the receiver, the information can be transmitted back and forth, until the connection is broken externally.

Though TCP is the most complex transport layer protocol, it is also the most reliable protocol when it comes to receiving error-free information. The protocol makes sure that the destination machine acknowledges the receipt of the datagram. Only then it transmits the information. Hence, TCP is more commonly used than UDP.

How does a UDP port work?

A UDP port, on the other hand, doesn’t need users to establish a connection between the sender and the receiver to send the information. However, unlike a TCP port, the information sent over the UDP port may not reach the receiver. It is similar to sending a letter. It is not necessary that the user has received the letter. Hence, the information that needs to be broadcasted is sent over a UDP port. The user tuned over or listening to the specified UDP port can receive information.

UDP has low latency and offers a constant stream of information. Thus, a UDP is the perfect choice for streaming broadcasts, online video games, and a voice-over-IP (VoIP) streaming. As a result, a UDP port is used only when there is a specific need regarding information being sent.

Identifying the right ports

There are many virtual ports available for any PC; which range from 0 to 65535. However, each of these ports has a certain standard and is dedicated to a certain application. Out of these, some of the following ports use TCP and UDP.

  • 20 (TCP): FTP (File Transfer Protocol)
  • 22 (TCP): Secure Shell (SSH)
  • 25 (TCP): Simple Mail Transfer Protocol (SMTP)
  • 53 (TCP and UDP): Domain Name System (DNS)
  • 80 (TCP): Hypertext Transfer Protocol (HTTP)
  • 110 (TCP): Post Office Protocol (POP3)
  • 143 (TCP): Internet Message Access Protocol (IMAP)
  • 443 (TCP): HTTP Secure (HTTPS).

It is possible to check which of the ports on your Windows PC are open or close. If you wish to block or open a certain TCP or UDP port, then here is the process.

Finding an open TCP or UDP port

Open the Start Menu. (For Windows 10, press the Windows button) and type CMD. Now click on Run as Administrator option.

UDP port

When the Command Prompt window opens, type Netstat -ab and press Enter. A list of TCP and UDP ports starts appearing along with the IP address and other details.

UDP port

The longer you wait, the bigger the list of open ports becomes. Wait until the complete list has appeared in the window. Once the list fully appeared, Press CTRL+C and CTRL+V to copy and paste the information into Notepad or any other text editor.

As you can see in the above image, the information in the brackets refers to the name of the program that is using an open TCP or UDP port. Next to the protocol name, you can see the IP address and the port number after the colon. For example, in 192.168.0.107: 50741, the numbers 192.168.0.107 are the IP address, while the number 50741 is the port number.

Read: How to check what Ports are open?

Finding a blocked TCP or UDP port

To know which of the ports are blocked by Windows Firewall, follow the next steps.

The first step is the same as finding an open TCP or UDP port. Open Start Menu by pressing the Windows button and type CMD. Now click on Run as Administrator option.

When the Command Prompt window opens, type following command: netsh firewall show state

UDP Port

Some ports may be blocked by the router or ISP and those may not be listed in the above list. To find those ports, type the following command: netstat -ano | findstr -i SYN_SENT

UDP Port

If this command doesn’t return any list, it means none of the ports are blocked by the router or ISP.

Now since you have identified the TCP and UDP ports on your Windows PC, here comes the most important part.

First of all, you may need to open a port for an application to run smoothly. On the other hand, you may need to block certain ports as they are no longer being used and may pose as a gateway for threats. Hence, such ports are blocked by the firewall.

Follow the next steps to open or block a TCP or UDP port.

Open the Start Menu by pressing the Windows-key. Type Windows Defender Firewall, and select Windows Defender Firewall with Advanced Security from the results.

UDP Port

The following window opens.

UDP Port

Click on the Inbound Rules tab on the left side menu.

UDP Port

Click on the New Rule… tab from the Actions pane on the right side menu. When this window opens, select the Port radio button and click Next.

UDP Port

When pressed Next tab, the following window of New Inbound Rule Wizard opens. In this window, you can select the type of port you want to open or block. You can also select whether you want to open or block all the ports of the selected type or a specific local port. Specify the number or a range of the local ports that you wish to open or block. And click Next.

UDP Port

The following window opens when you click Next. Here you can open the ports by selecting Allow the connection or Allow the connection if it is secure radio buttons. Select the third radio button Block the connection to block the specified ports.

UDP Port

Now select whether the rule applies to Domain, Private or Public or all of these. Click Next.

UDP Port

The following window opens when you click Next. In this window, specify a Name for this new Inbound Rule. You can also specify which ports have been blocked or opened in the Description section.

UDP Port

Click Finish to create this new Inbound Rule.

Please note that sometimes after blocking a certain port, apps may not work properly. You may also face issues while connecting to certain resources. This means the port you blocked may be required to be open. You can undo the blocking of ports at any time following the same process.

Read next: How to monitor TCP, UDP Communication in Windows with PortExpert.

Осуществляем закрытие портов?

Смотрю открытые порты:

cb5e07a393fc40d09db812b21bc6a47e.png

Закрывал все способами и программами и через cmd и в реестре чистил и в через диспетчер устройств..
1.Через cmd(писал, например):
netsh advfirewall firewall add rule name=»Block port 445″ dir=in action=block protocol=TCP localport=445
2. Через regedit…
3. Может я не туда смотрю, но ввел ведь команду для всех открытых портов, значит что-то не так — помогите разобраться :)


  • Вопрос задан

  • 5307 просмотров

Пригласить эксперта

Firewall блокирует соединение с указанным адресом и/или портом.
Порт при этом может оставаться открытым — ему ничего не мешает быть открытым.
Попробуйте telnet localhost:445 без правила и с правилом.
Что вы делали через regedit?

Александр Михеев
Закрыть порт — это значит запретить к нему доступ из определенной сети.
Это делается с помощью файервола.
Нет доступа из внешней сети значит порт закрыт!

На приведенном вами скриншоте показан список портов, которые прослушиваются на этом компьютере.
Они могут быть открыты или закрыты. Их просто слушают.

Поэтому вопрос — вы что собственно хотите сделать?

Закрыть порт можно закрыв программу, его открывшую. В случае виндовых процессов это означает выключить комп :)
Открытый порт, который необходимо закрыть от доступа снаружи, лишь зафильтровывается фаерволом. Он остаётся открытым, но доступ к нему становится невозможным снаружи, и это проверяется сомо собой именно снаружи. С помощью портсканнеров,, например с сайта https://2ip.ru/check-port/

А вот не вы#$ывался бы, и вместо демонических консольных утилит юзал вкладку Прослушиваемые порты в штатном Мониторе Ресурсов — и вопроса бы не возникло. Ибо там отдельное поле есть «Состояние брандмауэра».

Войдите, чтобы написать ответ


  • Показать ещё
    Загружается…

Минуточку внимания

Cover image for How to properly close a port?

This is a thing I need to google every now and then so here’s a simple recipe for closing neglected ports on MacOS, Windows and Linux.


Mac OS

Here are the steps:

1. Find the process ID (PID) of the port (replace the ‘portNumber’ with the number)

sudo lsof -i :portNumber

This will give you a response as follows — copy the PID number for the next step:

2. Kill the process

First, try this (replace PID with the number you copied above):

kill PID

Now, test if it’s closed by connecting to the port (replace portNumber with the actual port number):

nc localhost portNumber

If it returns immediately with no output, the port isn’t open. However, if it returns some input, try to kill it with:

kill -9 PID

Again, try to connect. If it’s still running, try this:

sudo kill -9 PID


Windows

Here are the steps for Windows:

1. Find the process ID (PID) of the port (replace the ‘portNumber’ with the number)

netstat -ano | findstr :portNumber

Copy the PID number for the next step.

2. Kill the process

First, try this (replace typeyourPIDhere with the number you copied above):

taskkill /PID typeyourPIDhere /F

Run the first command again to see if it’s closed.


Linux

Here are the steps for Linux (courtesy of mayankjoshi)

1. Get a list of all open processes

$top

2. Kill a process

kill pid kills the process by process id
killall pname kills the process by name
-9 for forceful killing in both kill and killall
Use sudo if it’s a root process.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Трансляция экрана windows 10 на android tv
  • Windows 8 живая плитка
  • Windows 7 home basic минимальные требования
  • Редактор томов жесткого диска windows 10
  • Пойдет ли mafia 2 на windows 10