How to block suspicious connections from CMD

  • Netstat allows you to identify open ports, associated processes, and suspicious connections from CMD or terminal.
  • Windows Firewall, UFW, firewalld and blackhole routes allow you to block IPs and ranges detected as malicious.
  • Advanced tools like Defender for Endpoint or FortiGate isolate compromised devices, VPNs, and users.
  • Good user management, SSH and audit logs are key to detecting and stopping network attacks.

How to block suspicious connections from CMD

When you start seeing strange connections, open ports that you don't know where they're coming from, or random failed login attempts, it's important to understand how block suspicious connections from CMD and the firewall It's no longer something "for experts" but a necessity. With a couple of well-used commands, you can stop attacks, reduce server load, and gain significant visibility into what's happening on your network.

On Windows, Linux, and even on security devices like FortiGate, you have native tools for monitor traffic, identify malicious processes, and block IPs, ranges, or protocolsThe trick is to combine them well: first you detect with netstat, logs and monitoring, then you respond by blocking from CMD, firewall or directly isolating the device if things have gotten out of hand.

Netstat and CMD: the first radar to detect suspicious connections

The command netstat is one of the classic tools for auditing connections In Windows, Linux, and other systems like macOS or Unix, and although it has been with us since the 90s, it is still very useful for knowing what is connecting to what on your computer or server.

Its name comes from Network and Statistics, and that pretty much sums up its function: it gives you network statistics, routing table, open ports, and active connectionsThis includes both incoming and outgoing connections. It's crucial if you want to pinpoint which process is keeping a port listening, where an unusual service is connecting, or if there's an unusually high volume of connections.

The tool has no graphical interface; it works from the command prompt or terminal, which is why it is widely used in server environments and in forensic incident analysisIn return, it offers a level of detail rarely found in "pretty" utilities and allows you to detect malware that depends on specific ports or connections to suspicious remote hosts.

Before drawing conclusions with netstat, it's advisable to close unnecessary programs or even restart and only open what's absolutely necessary, because that way You reduce noise from legitimate connections (browser, chat clients, etc.) and, if you need, Check how many devices are connected to end up with a cleaner photograph of what you're really interested in investigating.

In addition, netstat maintains a routing table and statistics per protocol that help to visualize errors, dropped packets, and congestionIf you're trying to understand a bottleneck or a partial service outage, it's an important piece of the puzzle.

More useful netstat options for hunting for unusual connections

On Windows you can run netstat from CMD or the modern Terminal, and on Linux from any console. The typical syntax on Windows is something like this: netstat , combining parameters according to what you want to see.

If you simply write netstat Pressing Enter will give you a basic list of active connections: protocol (TCP/UDP), local address with port, remote address, and status (LISTENING, ESTABLISHED, TIME_WAIT, etc.). With this information, you can start locating connections to unfamiliar IPs or ports you've never seen before.

To work in numeric mode (without attempting to resolve DNS names) you will usually use netstat -nThis displays untranslated IP addresses and port numbers. This makes the output faster and clearer when you're comparing suspicious IPs with blacklists or firewall logs.

If you want the information to refresh every X seconds, you can add a number at the end, for example netstat -n 7 so that it repeats the output every 7 seconds. It's a simple way to have a kind of "monitor" from CMD without using external tools.

Where netstat becomes especially useful for looking for strange activity is in the advanced parameters, which allow you to Filter by protocol, view associated PIDs, statistics, or routes:

  • netstat -a: shows all connections and listening ports (active and inactive).
  • netstat -e: displays traffic statistics (bytes sent/received, errors, discards).
  • netstat -f: resolves and displays the FQDN (fully qualified domain name) of remote hosts.
  • netstat -n: displays IPs and ports in numeric format.
  • netstat -o: indicates the PID of the process that uses each connection, key to cross-referencing with the Task Manager.
  • netstat -p X: filters by protocol (TCP, UDP, TCPv4, TCPv6...).
  • netstat -q: list of linked listening and non-listening ports.
  • netstat -sStatistics grouped by protocol (TCP, UDP, ICMP, IPv4, IPv6).
  • netstat -r: displays the current routing table.
  • netstat -t: focused on connections in the download process.
  • netstat -xInformation about NetworkDirect connections.

A very common use for checking basic security is netstat -anoThis combines several of these options: you see all active connections with IPs, ports, and process IDs. From there you can locate rare processes in the Task Manager or with tools like TCPView and decide whether you should block them via firewall or uninstall them.

It's also very practical to filter the state with findstr, for example netstat | findstr ESTABLISHED to see only established connections, or to change ESTABLISHED to LISTENING, CLOSE_WAIT, TIME_WAIT, etc., when Are you investigating resource leaks or zombie connections?.

Advantages, limitations, and performance impact of netstat

How to block suspicious connections from CMD

Netstat shines because it gives you a fairly direct visibility of which ports and connections are live On a computer, this is something that's pure gold for an administrator or analyst. It allows you to monitor traffic, track sessions, perform performance evaluations, and detect unauthorized connections or suspicious behavior relatively quickly.

Thanks to its statistics, you can detect abnormal spikes in specific protocols or an increase in errorsThis often points to congestion, port scans, brute-force attempts, or misconfigured malware. And because it's a native utility, you don't need to install anything on Windows or many Linux distributions.

However, it also has its drawbacks. To begin with, the The output can be quite dense and cryptic If you're not used to interpreting connections, states, and ports, the learning curve isn't exactly smooth for a non-technical user, and they're likely to end up using programs with a graphical interface.

Another point is that netstat, by itself, It doesn't encrypt anything, it doesn't block anything, and it doesn't do in-depth analysis.It simply displays information. To turn that data into a real defense, you need to complement it with firewalls, EDR systems, IDS/IPS, and other tools.

It doesn't scale particularly well. in huge networks or environments with thousands of simultaneous connections. In modern infrastructures, it is often relegated to a secondary role compared to solutions like advanced PowerShell, SNMP, ss in Linux, or more powerful graphical viewers.

In terms of performance, the command itself doesn't "break" the system, but if you run it continuously, with many parameters and on equipment with thousands of connectionsIt can consume CPU and memory significantly. It's recommended to use it only occasionally, with specific filters, and without constantly refreshing at very short intervals.

Thanks to its level of detail, netstat even helps you to detect malware that behaves like a rootkit or that hides processes behind unusual connections.

How to switch from detecting to blocking: Windows firewall and IP blocking

Once you've located suspicious connections or IPs using netstat or logs, the next logical step is to use the Use the Windows firewall to block those suspicious IPsThis cuts off traffic at the source and saves resources on the server or PC.

The typical process for blocking a specific IP address in Windows is to create a custom incoming rule:

  1. Open the Windows Firewall with Advanced Security and click on “New Rule”.
  2. Choose “Custom” to be able to properly define the traffic to block.
  3. Specify “All programs” if you want the rule to affect any application.
  4. In “Protocol and ports”, leave it as “Any” unless you want something very specific.
  5. In “Scope”, add the source IP address or IP range you want to block.
  6. Select “Block the connection” as the default action.
  7. Decide which profiles it applies to (domain, private and public, usually all three).
  8. Give it a recognizable name, for example Blocking_Suspicious_IPand save.

With this, any connection attempt from that IP address will be directly rejected. This is especially useful when an attacker repeatedly tries to access your website, or tries to exploit... small DDoS attacks or testing credentials against administration panels.

If instead of blocking from your system you want to directly block access to a website hosted on a server, another option is to use the file .htaccess in control panels like PleskThere you can add rules like:

Order Allow,Deny
Deny from 192.168.xx.x
Allow from all

and repeat the line Deny from for each additional IP address. This ensures that when people try to access your website from those IPs, they only see an error and don't consume application or database resources.

You can also play with country-specific geo-blocking via .htaccess when the server allows it, redirecting certain traffic (for example, from a country from which you only receive attacks) to an error page using RewriteCond rules with the GEOIP country code.

Blocking IP addresses and ranges from CMD and network tools

In some environments, especially on Linux servers or systems where work is almost always done in the console, it is more direct to use routing or firewall commands from the terminal to cut off traffic from a problematic IP address.

With the command road. In Unix-like systems, you can add routes that essentially "flood" traffic to a specific host. For example:

route add -host 24.92.120.34 reject

With this command, any attempt to reach that IP address is rejected. If you want to see what's blocked or what the routing table looks like, you can use route, which will show the active number routes.

If at any time you need reverse lockSimply run:

route del 24.92.120.34 reject

When we talk about full rangesYou can use something like:

ip route add blackhole 22.118.20.0/24

which creates a "blackhole" route for an entire subnetwork, causing Packets destined for those addresses are discarded without a response.It is very useful against massive attacks distributed from a specific range or to stop massive spam from groups of IPs.

To avoid going in blind, it is advisable to rely on IP range calculators to know exactly how many and which ones you are blocking, especially if you are dealing with subnets with masks that are somewhat more complex than /24.

Block VPN connections and remote access from suspicious IPs

SSL VPNs are a very tempting target for attackers because, if they manage to get in, you give them near-direct access to your internal networkDevices like FortiGate allow you to restrict which IPs can connect to the VPN, and that's a very interesting additional layer of defense.

A typical approach is to create a group of addresses of the “blacklist” type (for example, blacklistipp) on the FortiGate where you add public IPs that have attempted brute force attacks or strange behavior in the VPN logs.

Later, in the firewall consoleThe SSL VPN configuration is adjusted with:

  • config vpn ssl setting
  • set source-address “blacklistipp”
  • set source-address-negate enable
  • Show to verify the applied configuration.

With this setting, any connection attempt from an IP address included in that group will be rejected from the very beginningwithout even allowing the entry of a username and password, which greatly reduces resource consumption and the attack surface.

You can also work from the Graphic interface Configuring "Restrict access" and limiting it to specific hosts, although in that mode, the user enters credentials and the connection is then cut off, which is less efficient from an early mitigation point of view.

To verify that the lock is working, you can use diagnostic commands such as diagnose sniffer packet filtering by IP and VPN port, or checking get vpn ssl monitor to check which connections are established and which are left out.

Advanced defense: isolation of devices and identities

When the situation is truly serious (ransomware, lateral movement, data exfiltration), simply closing a port or blocking a specific IP address isn't enough: sometimes you need completely isolate the compromised device or even identity.

Microsoft Defender for Endpoints It integrates rapid response actions at the device level: you can tag devices, initiate automated investigations, open remote live response sessions, collect complete investigation packages, and launch in-depth antivirus scans from the central console.

The compilation of a research package in Windows includes information such as Registry startups, installed programs, active network connections, ARP cache, DNS, TCP/IP configuration, firewall logs, prefetch, processes, scheduled tasks, security log, services, SMB sessions, system information, and temporary directoriesAll of this is condensed into a folder structure and a summary report (CollectionSummaryReport.xls).

macOS and Linux collect something similar: installed applications, disk volumes, network connections, processes, services, security information, users and groups, etc., which allows reconstruct the attack scenario fairly good.

One particularly powerful action is the device isolationThe affected computer is disconnected from the network (except for necessary communication with the cloud security service) to prevent the attacker from further movement or data leaks. Complete isolation and selective isolation (allowing, for example, Outlook and Teams to continue functioning) are available on various versions of Windows, macOS, and Linux, subject to certain iptables and kernel requirements.

In parallel, there is the option of contain unmanaged devices via their IP: Defender-protected devices block any incoming or outgoing traffic to that address, slowing the spread from "islands" of the network where there is no security agent deployed yet.

It can also contain itself user or identity Suspicious: Network logins, RDP, SMB, and RPC are blocked; ongoing remote sessions are terminated; and lateral movement is prevented. This containment is typically triggered automatically using attack disruption logic and predictive shielding, and can be reversed from the Action Center once the incident has been resolved.

Firewall on Linux: UFW, firewalld and iptables to stop malicious traffic

On Linux servers, the key component for blocking unusual connections is the system firewall, usually based on iptables/nftables, with management layers such as UFW or firewalld to make it more friendly.

In Ubuntu and many compatible distributions, UFW (Uncomplicated Firewall) greatly simplifies things. You can install it with sudo apt install ufw, check its status with sudo ufw status and activate it with sudo ufw enableBy default, it usually denies all incoming traffic and allows outgoing traffic, which is already a fairly secure stance.

To define the basic policies, commands such as the following are used:

sudo ufw default deny incoming
sudo ufw default allow outgoing

Then, you can allow specific services: for example sudo ufw allow ssh to open port 22, or sudo ufw allow 2222/tcp If you're using a non-standard SSH port. To block a service, do something like sudo ufw deny 80 close the HTTP port.

If you have a trusted IP address or, conversely, want to block a specific address, you can use rules like sudo ufw allow from o sudo ufw deny fromand even fine-tune with “to any port” "to associate the block with a specific port."

The rules can be listed numbered with sudo ufw status numbered and remove with sudo ufw deleteThis makes it quite convenient to adjust the policy based on what you see in logs and in tools like netstat, ss or iftop.

Harden access: users, SSH, and authentication

Blocking suspicious connections is great, but it's just as important Reduce the attack surface by limiting who can enter and how.This is where user management, SSH, and strong authentication come into play.

In Linux, every user account with server access is a potential attack vector if not properly managed. Accounts are created with useraddThey are assigned a password with Passwd and permissions and groups are adjusted with tools like chown and chmod to prevent them from touching more than they should.

To strengthen SSH, the ideal is to use public/private keys instead of passwordsYou generate your pair with ssh-keygenYou accept or define the storage path and, if you want an additional layer, you add a passphrase. Then you send the public key to the server with ssh-copy-id user@host And from there, you can log in with ssh user@host using your key.

Once key authentication is working, it's a good practice disable password login in the /etc/ssh/sshd_config file, modifying the PasswordAuthentication directive to “no” and restarting the service with systemctl restart sshThis way, an attacker will not be able to brute-force password attempts, because the server will not even accept that method.

If you add to this two factor authentication In critical services, password rotation and accounts with minimal privileges drastically reduce the chances of a suspicious connection getting beyond a few failed attempts.

Logs and monitoring: without visibility there is no effective blocking

No blocking strategy works well if you don't have decent audit logs and minimal monitoringYou need to see what's happening in order to react in time and, if necessary, reconstruct what happened after an incident.

In Linux, most system logs are concentrated in / var / logKernel messages, authentication, network services, system daemons… It almost always controls the behavior and format rsyslog (or variants), configured in files such as /etc/rsyslog.conf or in files within /etc/rsyslog.d/.

From there you can adjust what types of events are logged, their severity level, and which file they end up in. It's also possible send logs to a centralized server to analyze them better and prevent an attacker from easily deleting them on the compromised computer.

Balance is important: recording absolutely everything can fill the disk and make it impossible to filter useful informationWhile logging very little leaves dangerous gaps. That's why many people combine detailed logging for critical services (SSH, firewall, authentication) with lighter logging for less sensitive components.

For analysis, you can use commands like grep, awk, or less, but in medium and large environments it's normal to use SIEM tools or stacks like ELK, Splunk or similarwhich allow correlating events, detecting attack patterns, and generating real-time alerts.

In Windows, something similar is done with the Event Viewer, Windows Defender logs, firewall, and, at a more advanced level, with solutions such as Microsoft Defender XDR that already integrate all that flow and cross-reference it with threat intelligence.

Combining netstat and other network utilities to detect suspicious traffic, strengthening the firewall (on Windows, Linux, or dedicated devices), effectively managing users and SSH, and leveraging advanced capabilities like device isolation or IP and account containment, puts you in a much stronger position: suspicious connections cease to be a recurring scare and become events you can control. Identify quickly, block from CMD or security panels, and analyze calmly. to gradually improve the defense of your entire infrastructure.

What is GlassWire?
Related article:
GlassWire tutorial to detect rare events and monitor your network