Как подключиться к серверу через консоль windows

Especially with the option to install Server Core in Server 2008 and above, connecting to Windows servers over a CLI is increasingly useful ability, if not one that's very widespread amongst Windows

Especially with the option to install Server Core in Server 2008 and above, connecting to Windows servers over a CLI is increasingly useful ability, if not one that’s very widespread amongst Windows administrators.

Practically every Windows GUI management tool has an option to connect to a remote computer, but there is no such option present in the built-in Windows CLI (cmd.exe), which gives the initial impression that this might not be possible.

Is it possible to remotely management or administer a Windows Server using a CLI? And if so, what options are there to achieve this?

asked Sep 18, 2012 at 11:11

HopelessN00b's user avatar

HopelessN00bHopelessN00b

53.6k32 gold badges134 silver badges208 bronze badges

There are several fairly easy options available for remotely managing a remote Windows Server using a command line, including a few native options.

Native Options:

  1. WinRS/WinRM
    • Windows Remote Shell/Management tool is the easiest way to remotely manage a remote Windows server in a command line utility, and as with most Windows command line utilities, ss64 has a good page on its options and syntax.
    • Although not explicitly stated in the Microsoft documentation, this can be used to launch a remote instance of cmd.exe, which creates an interactive command line on the remote system, rather than as command line option to execute a single command on a remote server.
      • As with: winrs -r:myserver.mydomain.tld cmd
    • This is also the natively-supported option that will probably be most familiar to administrators of other systems (*nix, BSD, etc.) that are primarily CLI-based.
  2. PowerShell
    • Hopefully PowerShell needs no introduction, and can be used to manage remote computers from a CLI using WMI (Windows Management Instrumentation).
    • PowerShell remoting allows the execution of Powershell scripts and commands on remote computers.
    • There are a number of good resources on using WMI + PowerShell for remote management, such as The Scripting Guy’s blog, the MSDN WMI Reference and ss64.com, which has an index of PowerShell 2.0 commands.
  3. Remote Desktop
    • Probably not exactly the first thing to come to mind as a Window CLI option, but of course, using mstsc.exe to connect to a server over Remote Desktop Protocl (RDP) does enable the use of a command line on the remote server.
    • Connecting to a Server Core installation over RDP, is actually possible and will give the same interface as connecting to the console — an instance of cmd.exe.
      • This may be somewhat counter-intuitive, as Server Core lacks a desktop, or the other normal Windows shell options, but there’s a quick article over at petri.co.il about how to manage Server Core over RDP, should one be so inclined.

Popular, Non-Native Options:

Even though Windows now provides a few native options for accessing a remote sever over aCLI, this was not always the case, and as a result, a number of fairly popular 3rd party solutions were created. The three most notable are below.

  1. Install SSH on your Windows Server

    • If you just must have SSH, that’s an option too, and there’s a guide on social.technet for how to install OpenSSH on Server 2008.
    • Probably most useful for administrators of other systems (*nix, BSD, etc.) that make heavy use of SSH for this purpose, though there are advantages to even Windows-only administrators for having a single terminal emulator client (like PuTTY) store a number of target computers and customized (or standardized) settings for each.
  2. PSExec

    • The original option for executing remote commands on a Windows box through the Windows CLI, this is part of the excellent SysInternals suite. One of the very few «must have» packages for Windows admins, the SysInternals tools were so widely respected and used that SyInternals was bought out by Microsoft, and the tools are now somewhat officially supported by Microsoft.
    • Just as with WinRS/RM, PSExec can be used to issue single commands to a remote server, or to launch an interactive instance of cmd.exe on a remote computer.
      • As with: psexec \myserver.mydomain.tld cmd
    • As with the other options, there are steps one must take first to ensure PSExec is actually able to connect to the target machine.
  3. Add a utilities folder to the server and store its value in the %PATH% system variable

    • As has been noted in the comments there are many a good SysInternals program that can be executed on the command line and targeted at a remote system, and this is true of more than just SysInternals.
    • Basically, package up a bundle of your favorite Windows utilities into a folder you push to all your servers and add that folder to the %PATH% environmental variable of your systems. Both are easily done through GPO.
      • (I include the SysInternals Suite, PuTTY, WinDirStat and a bunch of custom scripts I find myself reusing) into a folder that gets pushed to all my servers
    • Obviously, this is useful for more than just managing Windows systems via CLI, but I find it so useful I think it’s worth including anyway.

Bdoserror's user avatar

answered Sep 18, 2012 at 11:11

HopelessN00b's user avatar

HopelessN00bHopelessN00b

53.6k32 gold badges134 silver badges208 bronze badges

8

Just for the sake of completeness: although it might not be the best solution for various reasons, every Windows system supports the Telnet service, which can be enabled from the features list.

Microsoft’s telnet implementation also supports NTLM authentication, thus, unlike standard telnet to a Unix system, no clear-text password is sent on the network when using it.

answered Mar 31, 2014 at 13:09

Massimo's user avatar

2

The Remote Desktop Connection (RDC) tool, also known as Microsoft Terminal Services Client (MSTSC), allows a user to connect to another computer remotely over the network using the Remote Desktop Protocol (RDP). Most users use this tool via its Graphical User Interface (GUI) which is convenient to use, but this article focuses on using the Remote Desktop via the command line.

Connecting to other computers using RDC through the command line allows you to control different settings and preferences of the connection. Windows allows a user to use certain switches to predefine the settings before the connection is made. For example, you can define the name or IP address of the remote computer, or adjust the RDC window size even before running the tool.

Learn how to enable RDC in Windows 11.

Table of contents

  • MSTSC commands and switches
    • Launch RDC from Run
    • Use RDC to connect via console
    • Launch RDC with IP address
    • Launch RDC with computer name
    • Launch RDC in full-screen mode
  • MSTSC commands and switches
  • Troubleshoot RDC via command line
    • Check if RDP is enabled from Command prompt
    • Check if RDP is enabled from PowerShell
  • Frequently Asked Questions
    • What is MSTSC?
    • How to open Remote Desktop from the command line?
    • How to add username and password to mstsc command line?
    • Is the RDP and RDC the same?

Let us help you become aware of the switch options and how you can use them to configure your RDC connections.

MSTSC commands and switches

The conventional way to open the RDC in Windows is by searching for “Remote Desktop Connection” or “RDC” in Run and open the tool.

rdc search

Search for RDC

This then opens the RDC tool where you can enter the name of IP address with port number (optional) of the remote computer that you want to connect to.

tool

RDC tool with IP address

Most of you would already be aware of this method.

This section covers the possible commands and switches that you can use with RDC via the command line. We shall start with the most basic ones and then continue.

Launch RDC from Run

The very basic command to run Remote Desktop Connection from the command line is via Run. Simply type in the following in Run and hit Enter.

mstsc

mstsc

mstsc in Run

Running this will open the RDC with a blank text field. However, with the addition of a few switches, you can change the settings and preferences of the RDC connection. Let us continue forward with a few examples.

Use RDC to connect via console

Although RDC fully supports GUI, you can also connect to remote machines through a console. This will help in case you wish to continue the session that you got disconnected from earlier. In contrast, a regular GUI-based RDC session creates a new session each time you connect to the same machine.

Use the following command to connect to a remote computer via console:

mstsc /console

console

mstsc /console

Launch RDC with IP address

You can also launch RDC along with the IP address of the machine to connect it with. If the port on the machine is changed from the default value, you can also add the port number. Use the following commands to do so:

mstsc /v:IPAddress
mstsc /v:IPAddress:PortNumber

Replace IPAddress with the complete IP address of the remote computer that you want to connect with, and PortNumber with the port number if changed from its default value.

ip and port

mstsc with IP address and port number

Launch RDC with computer name

You can also connect to the remote computer by its unique computer name. The switch used for this is the same one used with the IP address and port number in the steps above.

mstsc /v:ComputerName

Replace ComputerName with the unique name of the remote device that you can find in its settings or properties.

computer name

RDC with computer name

Launch RDC in full-screen mode

You can also launch the RDC connection in full-screen mode. Here is how:

mstsc /f

fullscreen

RDC in full-screen mode

These switches can be combined into a single command to execute an RDC connection to your preferences. Here is an example:

mstsc /f /v:192.168.10.122:8002

combined

RDC full-screen with IP address and port number

MSTSC commands and switches

There are more commands and switches you can use with mstsc command-line to adjust your settings for the connection beforehand. Here is the complete list:

<connectionfile> For a .rdp file required to make a connection (if applicable).
/v: IP Address or computer name of the remote computer.
/g: IP Address or device name of a Remote Gateway Server (if applicable).
/admin To establish a connection with administrative privileges.
/f View the Remote Desktop Window in full-screen mode.
/w: To specify the width of the Remote Desktop Window.
/h: To specify the height of the Remote Desktop Window.
/public Run the Remote Desktop Connection publicly (less secure).
/span To match the width and height of the Remote Desktop with the local desktop.
/edit <connectionfile> To edit a .rdp file.
/multimonTo make the monitor layout of the Remote Desktop Services session identical to the client-side configuration.
/restrictedAdmin Connect to the remote PC in Restricted Administration mode. The credentials are not sent to the remote PC in this mode, protecting you if you connect to a compromised PC.
/remoteGuard Connect your device to a remote device using the Remote Guard, which prevents sending credentials to a remote PC.
/prompt To prompt you to put in credentials to connect to the remote PC.
/shadow: The ID of the session that you want to connect to.
/control Give control of the session when shadowing.
/noConsentPrompt To allow shadowing without user consent.
/migrate Migrate legacy connection files created with Client Connection Manager to new .rdp connection files.
/? To get help in the command prompt.
MSTSC commands and Switches

These switches can have the following syntax in either Run or the Command Prompt:

mstsc [<connection file>] [/v:<server[:port]>] [/g:<gateway>] 
[/admin] [/f] [/w:<width> /h:<height>] [/public] | 
[/span] [/multimon] [/edit "connection file"] [/restrictedAdmin] 
[/remoteGuard] [/prompt] [/shadow:<sessionID> [/control][/noConsentPrompt]]

The parameters in the alligator brackets (< and >) are variables that you can adjust according to your preferences.

Troubleshoot RDC via command line

You can also troubleshoot Remote Desktop services through the command line. For example, if you are unable to connect to a device using the GUI RDC but have access via console, you can check whether there are any configurations to be made that will connect you via GUI successfully.

Check if RDP is enabled from Command prompt

Learn how to enable RDP remotely.

You can run the following command to check the status of your device if RDP is enabled or disabled:

netstat /p tcp /a | findstr 3389

listending

Check RDP status from Command Prompt

If the results come back as “Listening,” it means that RDP is enabled.

Check if RDP is enabled from PowerShell

Another method to check whether RDP is enabled is through Windows PowerShell. You can run the following commands in PowerShell and it will tell you whether the service is available or not.

if ((Get-ItemProperty "hklm:SystemCurrentControlSetControlTerminal Server").fDenyTSConnections -eq 0) { write-host "RDP is Enabled" } else { write-host "RDP is NOT enabled" }

rdp is enabled

Check RDP status from PowerShell

If the script returns “RDP is enabled,” it means that it is.

Frequently Asked Questions

What is MSTSC?

Microsoft Terminal Services Client (MSTSC) is a tool that allows a user to remotely connect to another device over the network as if they were physically present on the remote device.

How to open Remote Desktop from the command line?

You can open the Remote Desktop Connection window from Run or Command Prompt using mstsc. You may also add switches like /v and /f to control the connection’s arguments.

How to add username and password to mstsc command line?

You cannot add a username or password directly to the mstsc command. However, you can store the credentials in a generic key against the machine you want to connect to using these 2 commands:
cmdkey /generic:"<server>" /user:"<user>" /pass:"<password>"
mstsc /v:"<server>"

Is the RDP and RDC the same?

Remote Desktop Connection (RDC) is a tool used to establish a remote connection between devices. Remote Desktop Protocol (RDP) is the technology that RDC uses to create this remote connection.

Also see:

Subhan Zafar is an established IT professional with interests in Windows and Server infrastructure testing and research, and is currently working with Itechtics as a research consultant. He has studied Electrical Engineering and is also certified by Huawei (HCNA & HCNP Routing and Switching).

Mstsc — подключение к удаленному рабочему столу Windows

Команда Mstsc — подключение по RDP

Команда терминального сервера Mstsc используется для создания подключений к серверам терминалов или другим удаленным компьютерам с операционной системой Windows, редактирования существующего файла конфигурации подключения к удаленному рабочему столу (*.rdp) и переноса подключений Wndows (подключений, созданных с помощью диспетчера клиентских подключений) в новые файлы .rdp. Для принудительного выхода пользователей из системы используется команда LOGOFF.

Синтаксис и параметры команды Mstsc

mstsc.exe {файл_подключения|/v:сервер} [/console] [/f] [/w:ширина /h:высота]

mstsc.exe /edit»файл_подключения»

mstsc.exe /migrate

  • Файл_подключения — Задает имя файла .rdp для подключения.
  • /v:сервер — Задает имя удаленного компьютера, к которому необходимо подключиться.
  • /console — Подключается к сеансу консоли указанного компьютера под управлением Windows Server.
  • /f — Запускает подключение удаленного рабочего стола в полноэкранном режиме.
  • /w:ширина /h:высота — Указывает размеры экрана удаленного рабочего стола.
  • /edit — Открывает указанный файл .rdp для редактирования.
  • /migrate — Переносит устаревшие файлы подключений, созданные диспетчером клиентских подключений, в новые файлы .rdp.mstsc

Примечания по команде MSTSC

  • Для создания подключения к удаленной консоли необходимо быть администратором на сервере, к которому происходит подключение.
  • Для каждого пользователя файлы .rdp хранятся в папке «Мои документы» как скрытые.

Примеры команды MSTSC

Для подключения к удаленному рабочему столу сервера с IP-адресом 192.168.1.1 необходимо ввести команду: mstsc /v:192.168.1.1

     Если вы интересуетесь используете Windows Remote Desktop, то вы уже наверняка знаете, что эта служба делает, но, возможно, у вас нет полного представления о ее возможностях. 

      Windows Remote Desktop позволяет вам удаленно контролировать практически любой ПК или сервер с Windows. Вы можете удаленно управлять ПК с ПК, сервером с сервера, ПК с сервера или сервером с ПК. Серверный компонент RDP встроен в операционную систему Windows — в XP, Vista и Windows 7 и 8 (но вы должны включить remote desktop на целевом компьютере). Если вы удаленно работаете с компьютером, это соединение с ПК является единственным, и вы при этом контролируете консоль. 

      Если же вы работаете с сервером (скажем, с Windows 2003 или 2008), вы можете подключить многих пользователей к серверу с помощью службы Terminal Services.

Однако, вне зависимости от того, используете ли вы серверную ОС или нет, клиентская часть одна и та же — Remote Desktop Connection или клиент Remote Desktop, как я ее называю. Исполняемый файл для удаленного соединения называется mstsc.exe, он располагается в%systemroot%/system32/mstsc.exe.

Давайте же разберемся с тем, что вы можете сделать с помощью mstsc.exe’

Запуск Windows Remote Desktop Connection из командной строки

В подсказке для администраторов от Криса Сандера (Chris Sander) на WindowsNetworking.com (Использование Remote Desktop Client с помощью командной строки) разъясняются основные моменты работы с Windows Remote Desktop из командной строки. Как указывает Крис, базовый синтаксис команды mstsc.exe таков::

mstsc.exe {ConnectionFile | /v:ServerName[:Port]} [/console] [/f] [/w:Width/h:Height]

Но если вы запустите mstsc /? в Vista, 7 и 8, вы обнаружите еще несколько опций:

Рисунок 1: Экран помощи по использованию Remote Desktop Connection

В большинстве компьютеров, с которыми я сталкивался, через меню Start обнаружить remote desktop connection не так просто. Из-за этого я привык запускать Remote Desktop таким образом: Start — Run, потом нужно набрать mstsc и нажать Enter.

Обычные причины запуска mstsc.exe через командную строку

Я люблю Remote Desktop, потому что, используя его, я могу соединяться со своего ноутбука или домашнего компьютера с любым компьютером или сервером в своей инфраструктуре. Это сильно воодушевляет.

Мне часто приходится использовать опции командной строки. Иногда возникает необходимость сохранить RDP File, являющийся файлом сохраняемой конфигурации для конкретного часто осуществляемого RDP-соединения с конкретным сервером или ПК. Естественно, для одного сервера у вас может быть несколько RDP-файлов, если вам нужно несколько конфигураций.

Эти файлы .rdp представляют собой простые текстовые файлы; их можно создавать и редактировать блокнотом. Вот один для примера:

Рисунок 2: RDP-файл, открытый в блокноте

Рисунок 2: RDP-файл, открытый в блокноте

Хотя это можно делать с помощью блокнота, обычно редактирование файлов .rdp происходит через GUI клиента Remote Desktop, так как он дает возможность открывать и сохранять (Open, Save и Save as) файлы конфигурации:

Рисунок 3: Открытие и сохранение конфигурационных настроек RDP

Рисунок 3: Открытие и сохранение конфигурационных настроек RDP

Я также могу редактировать конкретный файл через GUI, инициируя этот процесс в командной строке с помощью опции /edit команды mstsc:

mstsc /edit test.rdp

Некоторые причины сохранения RDP-файлов для использования в дальнейшем:

  • Наличие сохраненных конфигураций для нескольких серверов и помещение этих настроек на рабочий стол или в папку в меню Start:

Рисунок 4: Создание нескольких RDP-соединений в меню Start

Рисунок 4: Создание нескольких RDP-соединений в меню Start

  • Наличие нескольких версий одной конфигурации; скажем, я соединяюсь с виртуальным рабочим столом с помощью VDI, и я создаю иконку для полноэкранного режима и иконку для разрешения 800×600
  • Наличие одного RDP-файла просто для соединения с сервером и файла для соединения с сервером и запуска приложения (что можно настроить в файле .rdp)

И как пример, использование RDP как опции в программах-пинговалках. И инфраструктурных картах. Найти необходимый узел на карте и сразу подключиться к нему. Но для этого в программе нужно задать опции командной строки (Рисунок 4.1).

Рисунок 4.1: Подключение к удаленному компьютеру из программы-пингера FriendlyPinger.

Создание ярлыка на рабочем столе для запуска Remote Desktop

Скажем, вы хотите создать ярлык на рабочем столе для соединения с конкретным сервером. При этом вы можете использовать базовый набор опций командной строки, либо воспользоваться этими опциями и файлом соединения .rdp.

Другим способом является ввод полной строки командного интерфейса в мастере создания ярлыка соединения на рабочем столе.

Предположим, вы хотите создать ярлык на рабочем столе для:

  • Соединения с сервером ‘exchange’
  • Соединения с консолью этого сервера
  • Создать окно разрешением 800×600

Для этого вам нужно запустить команду:

mstsc.exe /v:exchange /admin /w:800 /h:600

А для создания ярлыка на рабочем столе вам нужно ввести эту строку в create shortcut location, например:

Рисунок 5: Создание ярлыка на рабочем столе для соединения RDP

Рисунок 5: Создание ярлыка на рабочем столе для соединения RDP

Однако, если этих базовых опций недостаточно, вам понадобиться использовать файл соединения .rdp connection file.

Для этого вам потребуется запустить mstsc.exe, а затем настроить ваше соединения так, как вам нужно. Добавляйте звук, настраивайте пропускную способность, указывайте приложение для запуска, увеличивайте производительность, подсоединяйте локальные устройства и ресурсы типа принтеров и буфера обмена. Когда все будет готово, просто нажмите на кнопку Save as на вкладке General под настройками конфигурации. При сохранении дайте имя вроде имясервера. Убедитесь, что вам известно, в какую папку отправляется RDP-файл при сохранении. Я также рекомендую протестировать соединение, чтобы убедиться, что все работает правильно.

После сохранения вы можете закрыть окно Remote Desktop Connection и перейти к созданию ярлыка на рабочем столе. Когда вам нужно будет указать путь для ярлыка, введите файл соединения после mstsc.exe. Убедитесь, что вводите полный путь к RDP-файлу. Этот файл должен находиться либо по указанному вами пути, либо ярлык и файл .rdp должны находиться в одной и той же папке. То есть это должно выглядеть примерно так:

Mstsc.exe c:usersdaviddocumentsexchange.rdp

ЛИБО, если вы хотите запускать mstsc.exe через конфигурационный файл, вам вообще не нужно создавать ярлыки. Все, что вам нужно сделать – сохранить файл настроек RDP, а потом запустить его. Сам файл при запуске ассоциируется с mstsc.exe, и ваше соединение с сервером, указанным в конфигурационном файле, будет инициировано.

И последняя подсказка ‘ Если вы хотите изменить настройки по умолчанию, используемые mstsc.exe для запуска без определенных конфигураций, вы можете отредактировать файл Default.rdp в папке документов.

Меня всегда напрягал момент поиска утилиты удаленного рабочего стола в меню Пуск. Никогда не помнил, в каком именно разделе она находится и всегда тратил много времени на поиск.
Так я долго мучился,пока один добрый человек (спасибо тебе, Паша) не показал мне:
Win + R, mstsc

2016-11-30_12-58-20

mstsc.exe — такое имя файла имеет утилита удаленного рабочего стола. Просто запомнить, легко вводить.

Параметр Описание
<имя файла> Задает имя файла .rdp для подключения.
/v:<Server[:<Port>] Задает имя удаленного компьютера, к которому необходимо подключиться и, опционально, номер порта подключения
/console Коннект к сеансу физической консоли (сеанс 0).
/admin Подключает к сеансу для администратирования.
/f Запуск удаленного рабочего стола в полноэкранном режиме.
/w:<ширина> Указывает ширину экрана удаленного рабочего стола.
/h:<высота> Указывает высоту экрана удаленного рабочего стола.
/public Запускает удаленный рабочий стол в общедоступном режиме.
/span Сопоставление ширины и высоты удаленного рабочего стола с локальным виртуальным рабочим столом и развертывание на несколько мониторов при необходимости.
/multimon Задает расположение мониторов сеанса служб удаленного рабочего стола в соответствии с текущей конфигурацией на стороне клиента.
/edit <имя файла> Открывает указанный файл .rdp для редактирования.
/migrate Переносит устаревшие файлы подключений, созданные диспетчером клиентских подключений, в новые файлы .rdp
/control разрешает управление сеансом
/? Показывает помощь по параметрам командной строки.

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

2016-11-30_10-41-49

Следует заметить, что ключ /console применяется для подключения к сеансу физической консоли на сервере (также известный как сеанс 0). Этот режим использовался в Windows Server 2003. В Windows Server 2008 или Windows Server 2008 R2,а также более новых версий, данный режим является устаревшим, т.к. сеанс 0 стал неинтерактивной сессией, зарезервированной для службы.

Поэтому RDC 6.1  не поддерживает ключ /console. Тем не менее, для обеспечения обратной совместимости, можно использовать параметр /admin для подключения к сеансу физической консоли на сервере под управлением Windows Server 2003. Подробнее можно почитать в данной статье: Изменения для удаленного администрирования в Windows Server 2008

Кроме того, ключ /admin обладает еще и следующими особенностями:

  • При использовании этого ключа с MSTSC соединения не требуется лицензии клиентского доступа (CAL) Terminal Services.
  • Ключ /admin связан с повышением прав. Например, если на пользователя, имеющего полномочия применять ключ /admin, наложен запрет Deny Users Permissions To Log On To Terminal Server, он сможет подключиться через mstsc /admin.
  • Даже если сервер терминала не принимает новых сеансов, все же можно создать сеанс /admin.
  • Сеанс /admin не учитывается в счет предела, установленного на сервере терминала с целью ограничить число сеансов.

Как обычно, ссылки к дополнительной информации:

MSTSC /console is now MSTSC /admin
Microsoft TechNet — Опции командной строки mstsc
Подключение к удаленному столу (клиент служб терминалов версии 6.0)

Все статьи на тему RDP и устранения проблем в его работе на нашем сайте.

(Visited 54 057 times, 8 visits today)

Posted by Rewalon

Понравилась статья? Поделить с друзьями:
  • Как подключиться к wifi через консоль windows
  • Как подключиться к серверу через cmd windows
  • Как подключиться к wifi через командную строку windows 10
  • Как подключиться к серверу на windows server
  • Как подключиться к wifi через wps windows 10