Netsh – настройка сети в Windows из командной строки cmd

Batch-файлы

На этом закончим наше знакомство с netsh и перейдем к batch-файлами Windows (текстовый файл с расширением «bat»), который позволяет не только автоматизировать ввод длинных команд (в том числе и netsh-комманд), но также поможет сделать этот процесс более интересным, интерактивным и не заставит нас использовать для каждого варианта настроек отдельный файл.

Gathering diagnostic data from windows firewall

Windows Firewall configuration and status information can be retrieved at the command line by using the Netsh.exe tool. This tool adds IPv4 firewall support to the following Netsh context:

netsh firewall

To use this context, type netsh firewall at a command prompt, and then use additional Netsh commands as needed. The following commands are useful for gathering firewall status and configuration information:

Netsh firewall show state Netsh firewall show config

Supported data gathering and configuration commands are listed in the following table.

List of available netsh contexts

AAAA – commands for AAAA Shows and sets the configuration of the Authentication, Authorization, Accounting, and Auditing (AAAA) database used by the Internet Authentication Service (IAS) and the Routing and Remote Access service.

Netsh


Итак, поигравшись с netsh на Windows 7 (для Windows XP синтаксис немного меняется) я обнаружил, что можно присвоить интерфейсу (в приведенном ниже примере — интерфейсу под названием «LAN») IP-адрес, маску и шлюз с помощью команды:

netsh interface ipv4 set address name="LAN" static 10.253.0.35 255.255.255.192 10.253.0.7

Команды, понятное дело, вводятся в командной строке Windows. Если параметры отказываются изменяться — запускаем cmd от имени администратора.

Если понадобится добавить еще один IP-адрес, то используем:

netsh interface ipv4 add address name="LAN" address=192.168.2.4 255.255.255.0

Две следующие команды очищают список DNS-серверов и выставляют IP-адрес 212.154.163.162 первым в списке DNS-серверов:

netsh interface ipv4 set dnsserver "LAN" static none
netsh interface ipv4 add dns "LAN" 212.154.163.162 1


Чтобы предоставить возможность назначения сетевых параметров DHCP-серверу используем:

netsh interface ipv4 set address name="LAN" source=dhcp
netsh interface ipv4 set dns name="LAN" source=dhcp

Ну и для отображения текущих параметров можно использовать:

netsh interface ipv4 show ipaddresses "LAN" normal
netsh interface ipv4 show dnsservers "LAN"

Netsh – использование оболочки сетевых сервисов

NETSH – использование оболочки сетевых сервисов

Оболочка сетевых сервисов Netsh — это утилита-сценарий командной строки, позволяющая управлять конфигурацией различных сетевых служб на локальном и удаленных компь­ютерах. Netsh предоставляет свою командную строку, которую можно использовать в интерактивном или неинтерактивном режиме.

:/>  Обновление часовых поясов для Windows XP/2003/vista/7/2008 x86/x64 (KB2570791) KB2570791 [rus] —

В интерактивном режиме вы входите в оболочку, набирая netsh и указывая имя контекста нужной сетевой службы. Име­на контекстов и их смысл рассмотрены ниже.

Имя контекста сообщает Netsh, какую вспомогательную DLL надо загрузить. Вспомогательная DLL (helper DLL) пре­доставляет команды, специфичные для контекста. Например, если вы набрали netsh для интерактивной работы с Netsh, а затем ввели грс, то войдете в контекст RPC. После этого вы могли бы набрать show interfaces для просмотра IP-интерфей­сов, настроенных на этом компьютере. Вот как выглядит эта процедура.

  1. Введите netsh. Командная строка сменится на Netsh>.
  2. Введите грс. Командная строка сменится на: Netsh грс>.
  3. Введите show interfaces. Будут выведены сведения об IP-интерфейсах, настроенных на компьютере, например:

Subnet Interface Status Description

127.0.0.0 127.0.0.1 Enabled MS TCP Loopback interface

192.168.1.0 192.168.1.56 Enabled Intel(R) PRO/100 VE

Network Connection

Каждый контекст имеет свой набор доступных команд, и некоторые из этих команд вызывают подконтексты, у которых тоже есть собственные команды. Учтите, что для работы с ка­ким-либо контекстом в домене должны быть сконфигурирова­ны соответствующие службы. В любом контексте можно про­смотреть список доступных команд, набрав help. То же самое относится к команде quit, введя которую вы покинете оболоч­ку сетевых сервисов и вернетесь в командную строку Windows. Быстро работать с Netsh в интерактивном режиме не удается. Но это даже хорошо для начинающих или для изучения дос­тупных команд.

Netsh command internal help

C:netshnetsh>helpThe following commands are available:
Commands in this context:.. - Goes up one context level.? - Displays a list of commands.abort - Discards changes made while in offline mode.add - Adds a configuration entry to a list of entries.alias - Adds an alias.bridge - Changes to the `netsh bridge' context.bye - Exits the program.commit - Commits changes made while in offline mode.delete - Deletes a configuration entry from a list of entries.diag - Changes to the `netsh diag' context.dump - Displays a configuration script.exec - Runs a script file.exit - Exits the program.firewall - Changes to the `netsh firewall' context.help - Displays a list of commands.interface - Changes to the `netsh interface' context.offline - Sets the current mode to offline.online - Sets the current mode to online.popd - Pops a context from the stack.pushd - Pushes current context on stack.quit - Exits the program.ras - Changes to the `netsh ras' context.routing - Changes to the `netsh routing' context.set - Updates configuration settings.show - Displays information.unalias - Deletes an alias.winsock - Changes to the `netsh winsock' context.

The following sub-contexts are available:

:/>  Как использовать команду tracert traceroute в windows

bridge diag firewall interface ras routing winsock

To view help for a command, type the command, followed by a space, and then type ?.

netsh> ?

Netsh contexts

Netsh utility interacts with others using dynamic-link library files. Each Netsh helper DLL provides an extensive set of features called a context, which is a group of commands specific to this DLL networking component. These contexts extend the functionality of netsh. For ex., Dhcpmon.dll provides netsh the context and set of commands necessary to configure and manage DHCP settings.

For more information about Netsh contexts, use this command in the netsh shell:

netsh>show helperDLL Filename Command
------------ -------
HNETMON.DLL bridge
DGNET.DLL diag
FWCFG.DLL firewall
IFMON.DLL interface
IFMON.DLL ip
IPV6MON.DLL ipv6
IPV6MON.DLL 6to4
IPV6MON.DLL isatap
IPV6MON.DLL portproxy
RASMONTR.DLL ras
RASMONTR.DLL aaaa
RASMONTR.DLL appletalk
RASMONTR.DLL ip
RASMONTR.DLL ipx
RASMONTR.DLL netbeui
IPMONTR.DLL routing
IPMONTR.DLL ip
IPPROMON.DLL autodhcp
IPPROMON.DLL dnsproxy
IPPROMON.DLL igmp
IPPROMON.DLL nat
IPPROMON.DLL ospf
IPPROMON.DLL relay
IPPROMON.DLL rip
IPPROMON.DLL routerdiscovery
IPXMONTR.DLL ipx
IPXPROMN.DLL netbios
IPXPROMN.DLL rip
IPXPROMN.DLL sap
IFMON.DLL winsock
netsh>

Netsh usage from command line, netsh syntax

netsh -a AliasFile -c Context -r RemoteComputer NetshCommand

netsh -a AliasFile -c Context -r RemoteComputer -f ScriptFile

-r : Configures a remote computer.

RemoteComputer : Specifies the remote computer to configure.

NetshCommand : Specifies the netsh command that you want to run.

-f : Exits Netsh.exe after running the script.

ScriptFile : Specifies the script that you want to run.

/? : Displays help at the command prompt.

Show multicast joins for an each network inteface

Type the following command:

netsh interface ip show joins

Show network diagnostic gui

Type the following command:

netsh diag gui

Switch the specified adapter from a static address to dhcp

Type the following command:

netsh interface ip set address “Local Area Connection” dhcp

NOTE: Typing this command changes the interface named “Local Area Connection” to DHCP. To display all of the adapters in the computer with their current IP addresses to determine the correct adapter name, type the following command:

Netsh interface ip show config

To change to a static address, type the following command:

netsh interface ip set address “Local Area Connection” static ipaddr subnetmask gateway metric

:/>  Почему дисковод не видит данные? Причины и их устранение

NOTE: Replace ipaddr with the static IP address, subnetmask with the subnet mask, gateway with the default gateway and, if necessary, metric with the appropriate metric. The following example changes the interface “Local Area Connection” to a static address of 192.168.0.10 with a subnet mask of 255.255.255.0, and the interface has a default gateway of 192.168.0.1 with a metric of 1:

netsh interface ip set address “Local Area Connection” static 192.168.0.10 255.255.255.0 192.168.0.1 1

What it netsh

Netsh tool is a command-line scripting utility that allows you to, either locally or remotely, display or modify the network configuration of a computer that is currently running. Netsh tool also provides an useful feature that allows you to run a group of commands in batch mode.

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

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

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

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

netsh interface ip show config

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

C:WindowsSystem32>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:WindowsSystem32>netsh -c interface dump > C:my-config.txt

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

C:WindowsSystem32>netsh -f C:my-config.txt

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

Итого

На этом можно закончить и торжественно сообщить, что Вы знаете все, что нужно для того, чтобы полностью разобраться в итоговом