Настройка сети в консоли windows

Любой системный администратор сталкивается с настройкой сетевых интерфейсов. Большинство для этой цели используют графический интерфейс Windows, что не всегда удобно. В этой статье я расскажу, как настроить сеть с помошью интерфейса командной строки cmd, используя встроенную утилиту netsh.

В операционных системах Windows есть специальная утилита netsh для настройки сетевого адаптера из командной строки cmd.

netsh.exe (network shell) — сетевая оболочка (программа) для ОС Windows, которая позволяет настраивать сетевые параметры, в том числе и удаленно. Данная утилита доступна на всех версиях Windows, начиная с Windows 2000.

Запуск командной строки:

Пуск —> Выполнить —> в строку вводим cmd.exe

Откроется черное окно с мигающим курсором. Тут мы и будем вводить перечисленные ниже команды (ну это для тех, кто никогда не работал с командной строкой).

Конфигурирование сетевых параметров (ip-адреса, сетевой маски и шлюза)

Уснановка ip-адреса, маски и шлюза.

netsh interface ip set address name="Local Area Connection" static 192.168.1.15 255.255.255.0 192.168.1.1

где
Local Area Connection — название вашего сетевого интерфейса.
192.168.1.15 — сетевой адрес (ip address).
255.255.255.0 — сетевая маска (network mask).
192.168.1.1 — шлюз (default gateway).

Установка дополнительного ip-адреса.

netsh interface ip add address name="Local Area Connection" 192.168.1.20 255.255.255.0

Включение автоматического получения ip-адреса, сетевой маски и шлюза от DHCP-сервера.

netsh interface ip set address "Local Area Connection" dhcp

Конфигурирование DNS и WINS серверов

Добавить предпочитаемый DNS сервер.

netsh interface ip set dns "Local Area Connection" static 8.8.8.8

Добавить альтернативный DNS сервер.

netsh interface ip add dns "Local Area Connection" 8.8.4.4

Добавить 3-й DNS сервер.

netsh interface ip add dns "Local Area Connection" 192.168.1.30 index=3

Установка автоматического получения предпочитаемого и альтернативного dns-сервера от DHCP-сервера.

netsh interface ip set dns "Local Area Connection" dhcp

Установка WINS.

netsh interface ip set wins "Local Area Connection" static 192.168.1.240

Включение и отключение сетевых интерфейсов

Отключение интерфеса

netsh interface set interface name="Local Area Connection" admin=DISABLED

Включение интерфеса

netsh interface set interface name="Local Area Connection" admin=ENABLED

Просмотр сетевых настроек

Расширеный вывод конфигурации сетевых интерфейсов.

netsh interface ip show config

Просмотр состояния интерфейсов (connected/disconnected).

C:\Windows\System32>netsh interface ip show interface
Инд  Мет         MTU         Состояние     Имя
---  ----------  ----------  ------------  ---------------------------
  1          50  4294967295  connected     Loopback Pseudo-Interface 1
 12          10        1300  disconnected  Local Area Connection

Просмотр таблицы маршрутизации.

netsh interface ip show route

Просмотр конфигурации IP-адресов.

netsh interface ip show addresses

Просмотр адресов DNS-сервера.

netsh interface ip show dnsservers

Просмотр адресов WINS-сервера.

netsh interface ip show winsservers

Сохранение и восстановление конфигурации сетевых интерфейсов

Ну а теперь самое интересное. Поговорим о том, как сохранить сетевые настройки в виде файла конфигурации и восстановить из файла конфигурации. Это может пригодиться тем, кто постоянно меняет сетевые настройки.

Сохранить сетевые настройки в виде файла.

C:\Windows\System32>netsh -c interface dump > C:\my-config.txt

Восстановить сетевые настройки из файла конфигурации.

C:\Windows\System32>netsh -f C:\my-config.txt

Вот и все. Мы рассмотрели далеко не все возможности утилиты Netsh.exe, а лишь самые часто используемые. Используя коммандную строку Windows и утилиту netsh можно намного облегчить себе жизнь.

Windows Command Prompt, or CMD, can be a handy tool for tweaking network settings. It lets you change IP addresses and DNS settings with commands like “netsh interface ip set address” and “netsh interface ip set dns“. This guide will show you how to do just that in Windows 11 or 10 using either CMD or PowerShell.

Also see: How to Check IP Address in Windows 11

Netsh Interface IP Set Address DNS Windows 11

Getting to know the “Netsh Interface IP” command

Netsh, or “network shell,” is a command-line tool in Windows that helps you manage network settings. It’s great for working with IP addresses and DNS settings. You can use netsh interface ip to handle IP addresses and netsh interface ip set dns for DNS configuration.

Related concern: What is Netsh.exe & its Popup and Crashing issues in Windows 11

Why use the command line?

Although many would argue that it would be more convenient to just adjust things through the GUI available like the network adapter’s properties to configure things like IP addresses and DNS, using command line, particularly the Netsh tool, will give you more freedom and some benefits:

  • It’s quick. Commands run faster than navigating through menus.
  • Great for automation. You can script these commands to set up many computers at once.
  • Handy for remote management. Manage settings on computers across your network from anywhere.
  • Helpful for troubleshooting. Get detailed info that can help fix network problems.

Pro tip: How to Find The IP Address of a Website in Windows 10 / 11

How to assign a Static IP Address

Setting a static IP address is useful for devices that need a constant address, like servers. Here’s how to do it with CMD:

First up, open Command Prompt as an admin

Hit the Win key, search for cmd or Command Prompt, right-click the result, and pick Run as administrator. PowerShell works too.

Command Prompt Run as Administrator

Next, see your network interfaces

Type this to list them:

netsh interface ipv4 show interfaces

Find the one you’re working with and remember its index number.

Netsh interface ipv4 show interfaces Windows 11

Now, set your IP, subnet mask, and gateway

Use this template, swapping in your own values:

netsh interface ipv4 set address name=<index> source=static address=<ip_address> mask=<subnet_mask> gateway=<gateway>

For instance, to assign 192.168.1.10 to interface number 3, you’d type:

netsh interface ipv4 set address name=3 source=static address=192.168.1.10 mask=255.255.255.0 gateway=192.168.1.1

Netsh interface IP set address CMD

Lastly, make sure it worked

Type ipconfig to see if your new settings are listed.

IPConfig to check Netsh interface IP changes

Related issue: Windows 11 Ethernet “Unidentified Network” (How to Fix)

Switching to a Dynamic IP Address

Dynamic IP addresses, given out by a DHCP server, are the go-to for most networks. Here’s how to set one up:

Step 1: Open Command Prompt as an administrator

Just like before.

Step 2: View the list of network interfaces

Run netsh interface ipv4 show interfaces to see your options and pick one.

Step 3: Switch to DHCP

Here’s the command, don’t forget to use your interface’s index:

netsh interface ipv4 set address name=<index> source=dhcp

For example, for interface 3, it’s:

netsh interface ipv4 set address name=3 source=dhcp

Netsh Interface IP Set address DHCP CMD

Step 4: Verify the changes

Run ipconfig to see if it’s set to get an IP address by itself.

Additional resource: Find MAC Address on Windows 11/10 with or without CMD

Setting up DNS Settings

DNS settings are what turn website names into IP addresses. Here’s how to tweak them:

See also: Change DNS to Google or Cloudflare in Windows 11/10

Step 1: Open Command Prompt as an administrator

As mentioned earlier.

Step 2: View the list of network interfaces

Use netsh interface ipv4 show interfaces to find the one to configure.

Step 3: Pick a primary DNS server

Replace the placeholders with your actual details:

netsh interface ipv4 set dns name=<index> static <primary_dns> primary

To use 8.8.8.8 as your primary DNS on interface 3:

netsh interface ipv4 set dns name=3 static 8.8.8.8 primary

Netsh interface IP set DNS using Command Prompt

Step 4: Add a backup DNS server (if you want)

Here’s how, just change <index> and <secondary_dns> to fit your setup:

netsh interface ipv4 add dns name=<index> addr=<secondary_dns> index=2

To set 8.8.4.4 as a backup for interface 3:

netsh interface ipv4 add dns name=3 addr=8.8.4.4 index=2

Step 5: Double-check everything

Run ipconfig /all to make sure your DNS settings are spot on.

Netsh interface IP set DNS to Google

Going back to default DNS Settings

If you want your DNS settings to go back to automatic, here’s what to do:

Step 1: Open Command Prompt as an administrator

Same process as before.

Step 2: View the list of network interfaces

Check your interfaces again with netsh interface ipv4 show interfaces.

Step 3: Reset your DNS settings

Here’s how, remember to swap in your interface index:

netsh interface ipv4 set dns name=<index> source=dhcp

To reset interface 3‘s DNS:

netsh interface ipv4 set dns name=3 source=dhcp

Restore DNS to default using Netsh in CMD Windows 11

Step 4: Make sure it’s all set

Run ipconfig /all to see if your computer is back to getting DNS settings on its own.

My two cents

Using the “netsh interface ip set address” and “netsh interface ip set dns” in CMD to adjust IP and DNS settings on Windows is especially useful when you need to manage a big network. If you are looking to automate stuffs like setting IP and DNS for a lot of computers in the network, this will certainly be one of the best ways.

Anyone who works with Windows network configurations will sooner or later come across the Network Shell (Netsh). The term refers to an interface between users and the operating system, which enables the administration and configuration of local, and remote network settings.

The range of applications includes settings for the Windows firewall and LAN/WLAN management as well as IP and server configuration. Moreover, networked infrastructure can also be protected from external attack. Using the command line tool, it’s also possible to diagnose problems and carry out repairs in the network. A big advantage of Netsh is that network-related administration tasks can be performed quickly and conveniently, and can be automated with scripts.

Netsh commands: starting the command prompt

It’s necessary to access the command line in order to use Netsh. There, you can open the “Run” menu as follows:

  1. Press the key combination [Windows] + [R]
  2. Enter “cmd” in the entry field (1)
  3. Click the “OK” button (2)
Opening the “Run” menu

Opening the command line (cmd.exe) on Windows.

The command prompt will then launch. The service program will open after you enter “netsh” and confirm with [Enter].

Command prompt for Netsh commands

Windows command prompt with a Netsh command; here USERNAME is a placeholder for the active user account.

If Netsh commands and scripts aren’t run or if more fundamental interventions in the network configuration are planned, you’ll need to start Network Shell with administrator rights. These steps are required on Windows 10:

  1. Right-click on the Windows symbol on the left side of the task bar or press the key combination [Windows] + [X].
  2. Choose the entry “Command Prompt (Admin)” in the context menu that appears:
Starting command prompt with administrator rights.

Netsh includes the program file netsh.exe located in the Windows system folder (%windir%\system32). Directly opening the file streamlines the Netsh command entry procedure. You can enter the path C:\Windows\System32\netsh.exe into the address line of Windows Explorer and press [Enter]. You can then enter Netsh commands straight away in the entry window that appears.

Launching the file is even faster by using a shortcut. Once created, a simple mouse click will be enough to launch the command entry:

  1. Right-click on the Windows desktop. Click on the menu entry “New” (1) and then click on “Shortcut” in the next context menu (2):
Creating a context menu shortcut

Creating a Netsh shortcut via the Windows desktop.

  1. In the shortcut assistant, enter the path C:\Windows\System32\netsh.exe (1) and click on “Next” (2):
Path entry for the Netsh shortcut

Entering the program path for a Netsh shortcut.

  1. You should give the shortcut a suitable name (1); the shortcut will then be placed on the desktop after clicking “Finish” (2):
Entering a name for the Netsh shortcut

Entering a suitable name for the Netsh shortcut.

How Netsh works

The service program Netsh provides an extensive command syntax. If you want to complete certain tasks, you’ll need to familiarize yourself with the specific structure of the Network Shell. The structure of the service program is based on contexts that represent various administration levels. Each context encompasses a certain network functionality (e.g. IP, LAN and firewall configuration). The program uses the files of the Dynamic-Link Library (DLL) for context-bound interaction with other Windows components. For instance, Netsh utilizes Dhcpmon.dll to change and manage DHCP settings.

To use a context, it’s necessary to switch to it in the command prompt of Windows. For example, the “LAN administration” context is accessed as follows:

  1. After opening the command prompt, enter “netsh” and confirm with [Enter].
  2. Then enter “lan” and confirm with [Enter].
  3. The command prompt will now show the context change: netsh lan>
Context changes in Netsh

Netsh in the command prompt: switching levels to the “LAN” context.

After changing to the “LAN” context, a number of context-specific and cross-context commands will be available. The context-specific commands include “set” (which configures settings at interfaces). An example for a general and cross-context Netsh command is the help command “/?”, which lists the available sub-contexts and commands in each section. Entering it in the “LAN” section will produce the following list of context-specific and cross-context commands:

Commands in the “LAN” Netsh context

Netsh in the command prompt: calling up the command overview for the “LAN” context.

For instance, if you switch to the firewall context, the associated command reference will look like this:

Commands in the “firewall” Netsh context

Netsh in the command prompt: calling up the command overview for the “firewall” context.

Besides the context-bound structure, there are other special points to consider when using the program. Netsh can either be used in a non-interactive or interactive mode. In the non-interactive mode, for example, important network settings are exported to a text file and reimported for subsequent recovery.

In the interactive mode, direct requests can be initiated. If you enter “netsh interface ip show address”, the current IP address of the computer will be displayed. The interactive mode can be used online or offline. The online model directly implements operations, while the offline mode saves actions and runs them later. The saved actions are activated at the desired time via the Netsh command “commit”.

Netsh commands and their contexts

We’ve summarized the main Netsh commands with a short explanation of the contexts in the table below. In the case of general, cross-context commands, additional explanations are not necessary (right-hand column). Depending on the operating system version and the role in the network (client or server), the available commands may vary in some instances. The command entry on a computer with a Windows Server 2016 data center is as follows:

Command Implementation Netsh context managed
.. Switches to a context level higher  
? Displays a list of commands  
abort Discards changes made in offline mode  
add Adds a configuration entry to the list  
advfirewall Switches to the “netsh advfirewall” context Firewall (policies and configuration)
alias Adds an alias  
branchcache Switches to the “netsh branchcache” context Branch cache settings
bridge Switches to the “netsh bridge” context Network bridge
bye Ends the program  
commit Applies changes made in offline mode  
delete Deletes a configuration entry from the list of entries  
dhcpclient Switches to the “netsh dhcpclient” context DHCP client
dnsclient Switches to the “netsh dnsclient” context DNS client settings
dump Displays a configuration script  
exec Runs a script file  
exit Ends the program  
firewall Switches to the “netsh firewall” context Firewall (policies and configuration)
help Displays a list of commands  
http Switches to the “netsh http” context HTTP server driver (http.sys)
interface Switches to the “netsh interface” context IP configuration (v4, v6)
ipsec Switches to the “netsh ipsec” context IPSEC policies
ipsecdosprotection Switches to the “netsh ipsecdosprotection” context Protection against IPSEC denial-of-service attacks
lan Switches to the “netsh lan” context Wired network interfaces
namespace Switches to the “netsh namespace” context DNS client policies
netio Switches to the “netsh netio” context Commitment filters
offline Sets the current mode to offline  
online Sets the current mode to online  
popd Switches to the context saved via pushd in the stack  
pushd Applies the current context to the stack  
quit Ends the program  
ras Switches to the “netsh ras” context Remote-access server
rpc Switches to the “netsh rpc” context RPC service configuration
set Updates the configuration settings  
show Displays information  
trace Switches to the “netsh trace” context  
unalias Deletes an alias name  
wfp Switches to the “netsh wfp” context Windows filtering platform
winhttp Switches to the “netsh winhttp” context Proxy and tracing settings of the Windows HTTP client
winsock Switches to the “netsh winsock” context Winsock configuration
wlan Switches to the “netsh wlan” context Wireless network interfaces

Syntax parameters for Netsh – what do they mean?

To implement specific actions and tasks, Netsh commands can be given optional parameters. The syntax scheme for the combination of Netsh commands and parameters is as follows:

netsh [-a AliasFile] [-c Context] [-r RemoteComputer] [-u [DomainName\]UserName] [-p Password | *] [command | -f ScriptFile]

The following parameters are all optional, so they can be added and used where needed.

-a Return to Netsh command prompt after running the alias file
AliasFile Specifies the name of the text file that contains at least one Netsh command
-c Switches to the specified Netsh context
Context Placeholder for the context to be entered (e.g. WLAN)
-r Causes the command to be run on a remote computer; the remote registration service must be executed there.
RemoteComputer Name of the remote computer that is configured
-u Indicates that the Netsh command is run under a user account
DomainName\ Designates the user account domain (the standard value is the local domain if no special domain is specified)
UserName Name of the user account
-p A password can be entered for the user account
Password Specifies the password for the user account that is stated with -u UserName
NetshCommand Netsh command to be run
-f Ends Netsh after running the script file
ScriptFile Script to be run

Resetting the TCP/IP Stack with Netsh

A common use for Netsh commands is to reset the TCP/IP stack, which provides for the exchange of data packages in networks. In the event of network and internet issues, this measure can help to remove defective or incorrectly configured TCP/IP protocols for example. The following repair command executes a reset and re-installs TCP/IPv4:

A protocol file can also be created that logs the changes made:

netsh int ip reset c:\tcpipreset.txt

After running the reset, the computer will need to be restarted.

Netsh commands can also be used in batch files (*.bat) to automate routine tasks. Find out more in our guide “Removing Batch Files”.

Importing and exporting network settings

Netsh allows you to export current network settings into a plain text file. In case of network problems, a functioning and error-free configuration can then be quickly restored.

In the first step (export), the network configuration is read out, written into a text file (netcnfig.txt)), and saved in the example directory “Network Configuration” on the C:\ drive. Before the first export, you’ll need to manually create the “Network Configuration” folder on the destination drive (Netsh does not perform this step automatically). Then, switch to the command prompt and enter the code below:

netsh -c interface dump>c:\Network Configuration\netcnfig.txt

The following command entry is required for subsequently importing the settings:

netsh -f c:\Network Configuration\netcnfig.txt

Windows 10 also supports copy and paste in the command prompt. You can simply copy the command syntax from this article and insert it into the entry window.

IP configuration with Netsh

A prevalent use case for Netsh is changing IP settings. If a computer in the network doesn’t contain a static IP address but an automatically assigned one, the Dynamic Host Configuration Protocol (DHCP) is used. This communication protocol automatically assigns IP addresses to clients in a network, and other required configuration data. This process takes multiple steps:

In the first step, the current settings and names of the available network adapters are requested:

netsh interface ipv4 show interface
Display of network adapters

Calling up the available network adapters with Netsh.

Now a certain LAN adapter (in this case: Ethernet) is determined as the addressee for the IP assignment via DHCP.

netsh interface ipv4 set address name="Ethernet" source=dhcp

Next, DHCP applies the dynamic administration for network settings that relate to the Ethernet adapter.

Activating and deactivating Windows firewall

If you wish to activate or deactivate the Windows firewall, all you need is a simple Netsh command syntax. A firewall is activated as follows:

netsh firewall set opmode enable

Firewall deactivation requires the following command:

netsh firewall set opmode disable

In some contexts, Windows will recommend alternatives to network administration with Netsh. Here, Windows PowerShell is often suggested and you can find an introduction to it in our Digital Guide.

Was this article helpful?

The netsh command is a Windows command that enables you to display and modify the network configuration of Windows computers.

We can run the netsh command in both CMD and PowerShell. To get a list of the available contexts, run the following command:

netsh help

Netsh has multiple command contexts (subcommands). Each command context has multiple subcommands you can use. For example, to get a list of the available commands under the advfirewall context, run the help command as follows:

netsh advfirewall help

You can run the help command for each context to see the different sets of available subcommands.

netsh command

Configuring Network Interfaces

In the following section, we will be learning how to use the netsh command to configure Windows networking.

To list all network interfaces on your computer, run the following command:

netsh interface show interface

Use the name parameter to show the status of a specific interface:

netsh interface show interface name="Ethernet"

To check IP Addresses, use ipv4 and ipv6 contexts as follows:

netsh interface ipv4 show addresses
netsh interface ipv6 show addresses

To find the IP Address of a specific interface, use the name parameter:

netsh interface ipv4 show addresses name="Wi-Fi"
Configuring Network Interfaces using netsh command

The show addresses command shows the IP Address, Subnet Mask, Default Gateway, and DHCP status.

Configuring IP Addresses

The following example shows how to assign a static IP Address to a network interface named Ethernet:

netsh interface ipv4 set address "Ethernet" static 192.168.1.10 255.255.255.0 192.168.1.1

In the above example, 192.168.1.1 is the default gateway. The following is the long format of the same command:

netsh interface ipv4 set address name="Ethernet" source=static address=192.168.1.10 mask=255.255.255.0 gateway=192.168.1.1

The following example shows how to configure a network interface to receive its IP configuration from the DHCP server:

netsh interface ipv4 set address name="Ethernet" source=dhcp

Configuring Name Servers

You can check DNS server addresses with the following two commands for IPV4 and IPv6, respectively:

netsh interface ipv4 show dnsservers
netsh interface ipv6 show dnsservers

Configure the NIC to receive DNS server address assignment from the DHCP server:

netsh interface ipv4 set dnsservers "Ethernet" source=dhcp

The following example shows how to set the primary DNS server address on the NIC named Ethernet:

netsh interface ipv4 set dnsservers name="Ethernet" static 192.168.1.1 primary

It will remove any existing DNS server IP addresses. To add a name server without removing existing IP addresses, use the add dnsservers command:

netsh interface ipv4 add dnsservers "Ethernet" 192.168.1.1 index=1

The above command sets the primary DNS server. If other IP addresses exist, they will move down on the list.

The following command sets the secondary DNS server:

netsh interface ipv4 add dnsservers "Ethernet" 192.168.1.2 index=2

Configuring Windows Firewall

In the following section, we will be learning how to use netsh to configure Windows Defender Firewall.

First of all, you can check Windows Firewall status with the following command:

netsh advfirewall show allprofiles

The command will show the status for all Firewall profiles. To check a specific Firewall profile (public, for example), run the netsh command as follows:

netsh advfirewall show publicprofile

The netsh advfirewall show help command will show you the list of all Firewall profiles.

Configuring Windows Firewall using netsh command

The following two commands turn on and off Windows Firewall, respectively:

netsh advfirewall set allprofile state off
netsh advfirewall set allprofile state on

The following examples show how to open ports, block ports, and allow programs through Windows Firewall.

Add an inbound Firewall rule to open port 80:

netsh advfirewall firewall add rule name="allow80" dir=in protocol=tcp localport=80 action="allow"

Disable the above rule:

netsh advfirewall firewall set rule name="allow80" new enable=no

Allow port 80 to IP Address 192.168.1.10 only:

netsh advfirewall firewall add rule name="allow80" dir=in protocol=tcp localport=80 remoteip="192.168.1.10" action=allow

Block port 80 from IP Address 192.168.1.10:

netsh advfirewall firewall add rule name="block80" dir=in protocol=tcp localport=80 remoteip="192.168.1.10" action=block

Allow a program through the Firewall:

netsh advfirewall firewall add rule name="netcat" dir=in program="C:\program files (x86)\nmap\ncat.exe" action=allow

List all Firewall rules:

netsh advfirewall firewall show rule all

List all inbound rules:

netsh advfirewall firewall show rule all dir=in

Display all the settings for inbound rules called netcat:

netsh advfirewall firewall show rule name="netcat" verbose

When using the netsh command, always use the help option to see the list of subcommands you can use. The help page also includes examples showing you how to use netsh to manage Windows networking and Firewall.

Have you ever run into an issue on a Windows machine with network connectivity? Maybe it was some rogue software installer making unknown changes to registry keys, or perhaps you suspect a virus is installed and need to track down its activity. Luckily Network Shell (netsh) utility is just around to help.

Netsh is a command-line utility that allows you to configure and display the status of various network configurations of Windows machines or servers. And in this tutorial, you’ll learn just about every command-line feature Netsh provides.

Ready? Read on and keep your network connectivity at its peak!

Prerequisites

This tutorial comprises hands-on demonstrations. But so long as you have a Windows PC or server, you’re good to go – This tutorial uses Windows 2019 Datacenter Edition, but Netsh works in all modern Windows editions.

What is Network Shell (Netsh)?

Before you dive into executing your first netsh command, kick-off this tutorial by getting a high-level overview of Netsh. So, what is Netsh anyway?

You might have worked with dozens of networking command-line tools such as ping, tracert, telnet, etc., but they are bound for a specific purpose.

With the Netsh command-line utility, you can configure and work with various network components. These network components are not limited to network interfaces, Windows firewalls, server roles, etc., on computers running Windows Server.

Running Netsh Commands

You now have a basic idea of Netsh and its usefulness for monitoring and configuring your network. But how do you actually execute netsh commands?

You can execute netsh commands on command-line consoles like PowerShell or the command prompt on a Windows machine. But as the command prompt’s successor, this tutorial demonstrates running the netsh commands on PowerShell.

1. Log in to your Windows Server using your RDP client. Windows has a default RDP client installed.

2. After you log in, open PowerShell as administrator, and run the netsh command below to access the netsh command-line session.

Accessing netsh Command-line Session

Accessing netsh Command-line Session

3. In the netsh prompt, run the help command to see all commands you can use inside your netsh command-line session. help

Pick one command you’d like to run, but this tutorial uses the interface command.

Help

Help

4. Lastly, run the interface command below to show all available network interfaces. interface show interface

Showing All Available Network Interfaces

Showing All Available Network Interfaces

Using Netsh Utility Commands

You now have access to the netsh prompt, and you’re almost ready to manage your network connectivity. But before you dive deeper into Netsh, you’ll be running basic Netsh utility commands to familiarize yourself with how Netsh works.

There are two ways you can run Nesh utility commands as follows:

  • Run the netsh command alone to access the netsh prompt, then run the Netsh utility command.
  • Running the netsh command followed by the Netsh utility command.

Like the help command you learned in step three of the “Running Netsh Commands” section, run some other Netsh utility commands below that Netsh offers:

  • /? – Similar to help but commonly used for most of the commands you can use within Netsh utility.
Displaying all the display all the commands and context using netsh /?

Displaying all the display all the commands and context using netsh /?
  • show – This command displays the commands available with each context.
Showing Available Commands in a Context

Showing Available Commands in a Context

popd allows you to restore a context from a first-in-last-out (FILO) stack, while pushd pushes the current context on a stack.

Both commands don’t have outputs, but you can append the help command to see how these commands function, as shown below.

Popping and Pushing Stack
  • The commit command commits changes made to the running configuration while in offline mode. In contrast, the abort command discards changes made in the running configuration while in offline mode.

These commands don’t have output, but appending the help command lets you view the command’s usage.

Committing and Aborting Changes to the Running Configuration

Committing and Aborting Changes to the Running Configuration
  • quit and bye – Lets you exit out of Netsh utility.
Quitting the Netsh Utility (quit)
Quitting the Netsh Utility (bye)

Fetching and Executing Netsh Utility Commands from a Text File

Like every other command, the netsh command allows you to declare parameters while executing tasks for simplicity and flexibility.

When working with Windows network configurations, you’ll find yourself dealing with Netsh. And using parameters in your netsh commands comes in handy. One good example is calling upon commands from a dedicated source, like a text file.

Create a file named myfile.txt on your desktop and add the help command in the file.

Now, run the netsh command below with the -a flag to specify the file’s path containing the netsh command.

netsh -a C:\Users\Administrator\Desktop\myfile.txt

Below, you can see the netsh command called and executed the help command from the myfile.txt file.

If you wish to run the command on a remote windows machine, consider using the -r flag, as shown below. But make sure the Remote Registry service runs on the remote computer. netsh -r shanky

Fetching a Netsh Command from a Text File

Fetching a Netsh Command from a Text File

Executing Netsh Commands Under a User Account

If you like to keep track of changes you make to your network configuration, run Netsh commands under a user account. How? By using the -u parameter followed by the account’s username.

Run the following netsh command to list available network interfaces under a user account (-u) named shanky.

To specify the user’s password, append the -p parameter followed by the password.

netsh -u shanky -p hellopass interface show interface
Running netsh Commands Under a Different User Account

Running netsh Commands Under a Different User Account

If you need to run the netsh command under a user account from a specific domain, consider using the DomainName\\username parameter.

Listing Available Network Interfaces

A network interface connects your computer and a private or public network. And knowing which interface your machine uses and the network configurations to troubleshoot is crucial.

This information helps resolve issues or provide your network configurations to third-party vendors for support.

1. Execute the netsh interface command below to show all available interfaces currently present on your machine.

Running netsh Commands Under a Different User Account

As you can see below, only one interface (Ethernet) takes care of all the network flow (in/out) from your machine.

Listing All Network Interfaces

Listing All Network Interfaces

2. Now, click the start menu, type ncpa.cpl, as shown below, and press Enter to open the Network Connections window (step three).

Opening Network Connections

3. Finally, verify if the netsh command returned the correct details of interfaces. Below, you can see the name of the active interface is Ethernet.

Verifying Network Interfaces

Verifying Network Interfaces

Gathering Information on Network Interfaces

What other good things come with listing available network interfaces on your system? Dig deeper to get comprehensive information from your network interfaces. Why? In a large organization, other departments require those details if they need to host applications on your network.

Run the following command that works the same as listing (show) each network interface available. But this time, you’ll get more details about each network interface configuration (config), such as DHCP status, IP address, etc.

netsh interface ipv4 show config
Checking Information on Available Network Interfaces

Checking Information on Available Network Interfaces

The Loopback Pseudo-Interface is used mainly for troubleshooting purposes and allows you to connect to servers running on the local machine for testing. But note that the loopback interface does not represent any actual hardware.

Setting a Static IPv4 Address and DNS Server

From the detailed listing of available interfaces, one of the most important concepts is the IP address of the Windows machine. The IP address for the Ethernet network interface is Dynamic. As a result, the IP address is allocated by itself from the pool of available IP addresses of the subnet.

But at times, you need to have a static IP address allocated to your machine, such as to test applications where a reboot of the machine is required. So change the dynamic IP address settings to manual type where IPs remain persistent.

1. Open the Network Connections window to see available network interfaces.

2. Next, right-click on the Ethernet interface and select properties, opening Ethernet’s Properties window.

Ethernet Properties

Ethernet Properties

3. Select Internet Protocol Version 4 (TCP/IPv4), as shown below, and click on Properties to open the IPV4’s properties window.

Checking the IPv4 Properties

As you can see below, the IP settings are set to obtain an IP address automatically.

Click on Cancel to close the Properties window, and you’ll manually change the IP address in the following step.

Viewing IPv4 Address Settings

Viewing IPv4 Address Settings

4. Now, run the below netsh interface command to manually set the following IP address settings:

  • IP Address – 10.0.0.100
  • Subnet mask – 255.255.0.0
  • Default gateway – 10.0.0.1
netsh interface ip set address "Ethernet" static 10.0.0.100 255.255.0.0 10.0.0.1 

To change the IPv6 address of the Ethernet interface, you will need to use netsh int ipv6 set to address 7 2001::2

To roll back to using a dynamic IP address, run the following command: netsh interface ip set address "Ethernet" dhcp

5. Run the following command to define a DNS server. Doing so allows your Windows machine to communicate to other networks.

netsh interface ip set address "Ethernet" static 10.0.0.100 255.255.0.0 10.0.0.1 

To disable the Ethernet interface on your Windows system, consider running the following command: netsh interface set interface name="Ethernet" admin=disabled

6. Lastly, as shown below, open the IPv4 settings again as you did in steps two to three to verify the interface’s IP address settings changed.

Verifying IPv4 Address and DNS Settings

Verifying IPv4 Address and DNS Settings

Managing Wired Network Interfaces

You previously managed the Ethernet network interface, but there could be multiple interfaces, such as wireless, wired, and Bluetooth-based network interfaces. What if you need information only for wired network interfaces as they are most important?

Consider using Netsh commands for wired LAN that provide methods to configure connectivity and security settings. The Netsh lan commands configure the local computer or multiple computers using a logon script.

Run the netsh lan command below to list all the wired network interfaces available on your Windows machine.

netsh lan show interfaces
Listing All Wired Network Interfaces

Listing All Wired Network Interfaces

Now, run the below command if you need to display the list of wired profiles configured on the computer.

If the interface parameter is defined, only the profile contents for the specified interface are displayed. Otherwise, all profiles will be displayed with their name and description.

netsh lan show profiles interface ="Ethernet"
Displaying the List of Wired Profiles

Displaying the List of Wired Profiles

Managing the Windows Firewall

Securing your network is a top priority achievable by managing your Windows firewall. How? By adding firewall rules with the Netsh advfirewall command. The advfirewall command allows you to control and manage your Windows firewall.

The advfirewall context works mainly on three profile settings; domain, private and public

Run the below command to enable (action=allow) the ping protocol (icmpv4) from your Windows firewall by setting a rule named ALL ICMP V4.

netsh advfirewall firewall add rule name="All ICMP V4" dir=in action=allow protocol=icmpv4
Adding Firewall Rule to Allow Ping Protocol

Adding Firewall Rule to Allow Ping Protocol

Now, run the below command to add a rule named Open Port 80 on your machine.

You can choose any port that you’d like to open. But this command opens port 80, allowing traffic to flow in and out.

netsh advfirewall firewall add rule name= "Open Port 80" dir=in action=allow protocol=TCP localport=80
Opening Ports by Adding Firewall Rule

Opening Ports by Adding Firewall Rule

The advfirewall context provides the same functionality that the netsh firewall context gives. But the netsh firewall context might be deprecated in the future.

Capturing Network Traces

Trace is another crucial context to troubleshoot and collect event information regarding network connections. You can use the trace context to collect event information using Event Tracing for Windows (ETW) to log network events.

But first, you’ll have to identify scenarios you can trace your network connections.

You can use Netsh to collect a packet capture without installing third-party tools like Wireshark.

Run the command below to help you find available scenarios where tracing your network connections would work based on the issue you’re dealing with in your network.

netsh trace show scenarios

As you can see below, multiple scenarios are available to work with trace.

Checking Scenarios Available in Netsh Trace Context

Checking Scenarios Available in Netsh Trace Context

Now, execute the below netsh trace start command to capture (capture=yes) all network details to a specified ETL file (tracefile) called ata_trace.etl. The persistent parameter permanently stores the file in the specified location when the value is true (yes).

netsh trace start capture=yes tracefile=c:\ata_trace.etl persistent=yes maxsize=4096

If you wish to stop the traces from getting captured, run the below command instead: netsh trace stop

Fetching the Traces of the Network to Store in a File

Fetching the Traces of the Network to Store in a File

As you can see below, the file (ata_trace) has been created and stored in the C:\ drive.

Viewing the Trace Log File

Viewing the Trace Log File

Diagnosing the Windows Firewall and IPsec Events

Nowadays, monitoring alerts is crucial for any organization running applications or microservices. Perhaps you’ve decided to spin up some new Windows machine or Virtual host and check filtered data about the connectivity and firewall settings. If so, consider using the Windows Filtering Platform (WFP).

The Netsh commands for the WFP allow you to conduct checks and filtration on the firewall for systems that support Windows firewall and IPsec.

Run the following command to save the current operational state of the WFP and IPsec to an XML file (wfpstate.xml) on the working directory by default.

With a copy of the state file (wfpstate.xml), you can further examine the WFP and IPsec state to find the root cause of a problem.

Saving Windows Firewall and IPsec Events State File

Saving Windows Firewall and IPsec Events State File

Perhaps you like to save the XML file to another location. If so, append the file flag and specify a save location, as shown below. Replace location with the actual save location and statefile.xml with your preferred file name.

netsh wfp show state file="location\statefile.xml"
Saving Windows Firewall and IPsec Events State File on Specified Location

Saving Windows Firewall and IPsec Events State File on Specified Location

Now, run the below command to save a list of network traffic events (netevents) to a file called netevents.xml in the working directory by default.

Like with the wfpstate.xml file, you can also specify a save location and file name for the network traffic events XML file (netevents.xml).

Saving List of Network Traffic Events

Saving List of Network Traffic Events

If you need to diagnose a specific protocol only, use the protocol parameter below.

The below command saves a list of network traffic events only for the TCP/IP protocol in XML format, where 6 is TCP/IP’s protocol number.

netsh wfp show netevents protocol=6
Saving a list of Network Events for a Specific Protocol

Saving a list of Network Events for a Specific Protocol

Validating Incoming and Outgoing Traffic

If you’re working with many applications where traffic comes in and leaves your network, you need to validate that traffic. How? Winsock is an interface that allows you to handle all the input/output requests for internet applications in a Windows system.

Execute the following netsh winsock command to show all the stored Windows sockets installed on your machine.

netsh winsock show catalog

Below, you can see all the Windows sockets entries and details of each one.

Viewing Windows Sockets Entries

Viewing Windows Sockets Entries

The Winsock catalog tends to contain incorrect entries or becomes corrupt. In that case, run the netsh command below to perform a Winsock reset. This command sets the Winsock catalog and associated registry settings to their defaults

Resetting the Winsock Catalog to Default

Resetting the Winsock Catalog to Default

Working with Alias and Unalias Using Netsh Command

Alias is an essential concept in networking. An alias instructs the shell to replace one string with another while executing the commands. Similarly, Netsh also uses Alias, a user-defined character string, which Netsh treats as a look-alike to another character string.

The syntaxes to add and delete an alias are below:

# Adds an alias
netsh add alias
# Deletes an alias
netsh delete alias

Reserving a Uniform Resource Locator (URL)

Reserving a URL properly in your system is crucial to defining the syntax of a URL endpoint to a web application. A reserved URL is defined for both the Web service and the web portal when configuring the applications on a server.

Three options are used along with the netsh command, add urlacl, show urlacl, and delete urlacl.

1. Run the below command to reserve a URL entry in the system where, url specifies the fully qualified URL, and user specifies the user or user-group name (DOMAIN).

netsh http add urlacl url=https://127.0.0.1:80/ user=\Everyone
reserve a URL entry in the system

reserve a URL entry in the system

Next, run the below command to show the list of all access control lists for a particular reserve URL (https://127.0.0.1:80/)

netsh http show urlacl url=https://127.0.0.1:80/
Listing Access Controls

Listing Access Controls

3. Finally, execute the command below to delete reserved URLs.

netsh http delete urlacl url=https://127.0.0.1:80/
Deleting Reserved URLs

Deleting Reserved URLs

Managing Netsh Configuration and Query Commands

Nowadays, broadband and networking are crucial on laptops, computers, and mobiles. And knowing how to query and configure mobile broadband settings and parameters comes in handy.

But first, you must ensure the WWAN AutoConfig service is running.

1. Run the below command to start the wwanSvc service. net start wwanSvc

Starting the WWAN AutoConfig Service

Starting the WWAN AutoConfig Service

2. Next, run the netsh add command below to add a network profile (Wi-Fi-Marriott Bonvoy.xml) in the mobile broadband interface’s profile data store configuration table.

Be sure to change Wi-Fi-Marriott Bonvoy.xml with the network profile (XML file) you like to add.

To check all the Mobile Broadband interfaces, run the below command. netsh mbn show interface

netsh wlan add profile filename="c:\New folder\Wi-Fi-Marriott Bonvoy.xml"
Adding a New WLAN Profile in the System

Adding a New WLAN Profile in the System

Perhaps you like to export a network profile. If so, run the following command, where SSID is the network interface, and destination is the network profile’s save path: netsh wlan export profile "SSID" key=clear folder=destination

3. Run the following command to connect to a particular mobile broadband network interface (delhi_Sagar_5GHz). Replace Wi-Fi Network with your Wi-Fi network name.

netsh wlan connect name="Wi-Fi Network"
Connecting to a Wi-Fi Network

Connecting to a Wi-Fi Network

4. Execute the below command to delete a network config profile (Marriott Bonvoy).

Deleting a network config profile from the profile data store is similar to running add command. The difference is that you’ll replace add with the delete sub-context in the command.

netsh wlan delete profile name="Marriott Bonvoy"
Deleting a WLAN profile in the system

Deleting a WLAN profile in the system

5. Now, run the following netsh dump command to capture and display interface configuration scripts.

Capturing Interface Configurations Details

Capturing Interface Configurations Details

If you wish to have a copy of the configuration details you can later review, run the following command. This command doesn’t print anything on the console but instead saves the output to a text file (netconfig.txt).

netsh dump > netconfig.txt

6. Execute the netsh set command below to set the configuration of specified interfaces, such as the following:

  • Setting the mobile broadband data auto-connect state for the given interface.
  • Turning the mobile broadband data on or off for the specified profile set or interface.
  • Setting the mobile broadband data highest connection category for the given interface.
Configuring Specified Interfaces

Configuring Specified Interfaces

Managing HTTP System Settings

Another important netsh command to look at is netsh http, which allows you to query and configure HTTP.sys settings and parameters.

These HTTP.sys settings can be, but are not limited to the following:

  • The cache of the HTTP service.
  • All the cached URL resources of the HTTP service.
  • All certificate bindings.
  • A snapshot of all the HTTP services.

Windows HTTP Services provides developers with an HTTP client API to send requests through the HTTP protocol to other HTTP servers.

Execute the below netsh command to show you a list of all the commands you can run to view the http service-related settings and configurations.

Below, you’ll see various options you can use with the netsh http command.

Viewing Available Commands for netsh http Command

Viewing Available Commands for netsh http Command

Now, run the below command to verify the HTTP settings and configuration, cacheparam perhaps.

netsh http show cacheparam
Viewing HTTP Cache Parameters

Viewing HTTP Cache Parameters

Automating Netsh Commands Execution with Batch Scripts

So far, you learned everything you need to know about Netsh utility, so consider yourself a pro. But at times, you need to run dozens of commands in one go and store the results. So why not automate executing Netsh commands with Batch scripts?

Create a file named myfile.bat on your desktop and copy/paste the code below to the myfile.bat file. The code below shows all network interfaces and configurations of all network interfaces.

# Show all the interfaces of the Windows System
interface show interface
# Show the configurations of all the interfaces 
interface ipv4 show config
# Show all the Wired lan network interfaces
lan show interfaces
# Updating the firewall rule to add ping protocol
advfirewall firewall add rule name="All ICMP V4" dir=in action=allow protocol=icmpv4
# Show all the events in the network
wfp show events
# Show all the network events
wfp show netevents

Next, run the below netsh command to execute the myfile.bat script from the specified folder path (-f C:\Users\Administrator\Desktop\).

netsh -f C:\Users\Administrator\Desktop\myfile.bat

As you can see below, the netsh commands inside the batch file (myfile.bat) were executed successfully.

Executing Netsh Commands with a Batch Script

Executing Netsh Commands with a Batch Script

Conclusion

Throughout this tutorial, you’ve learned different netsh commands to control your network configuration and diagnose potential issues. Netsh utility is a free tool with many features you can use whether you’re just checking out your network configuration or monitoring your network closely.

With this newfound knowledge, you can now monitor interfaces, run trace commands and scripts, and even convert all IP address settings.

Now that you’re a Netsh guru, how do you plan to use it? Why not automate command executions by compiling commands into a PowerShell script you can run at will?

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Почему не запускается the sims 3 на windows 10
  • Windows server инициализировать диск
  • Как сбросить открыть с помощью windows 10
  • Как изменить язык на компьютере windows на клавиатуре
  • Как запустить приложение в безопасном режиме windows 10