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

Приветствую. Иногда возникают задачи когда нужно что-либо сделать на удаленном компьютере, при этом либо нет возможности подключиться по RDP, например, если вдруг сервер сильно загружен, и ему не хватит ресурсов для запуска терминальной сессии (да да, у меня такое встречалось, не сказать что часто, но бывало smiley). Либо из командной строки задачу сделать быстрее. Ну или еще как вариант, если нужно что то сделать скрытно, в том случае если пользователь в момент когда это нужно сделать работает за компьютером. Пользователям Linux с этим гораздо проще, у них есть ssh. Но и в Windows есть возможность подключаться, с позволения сказать, в командную строку.

В общем и целом на помощь к нам приходят утилиты SysInternals, а именно — pstools, а еще конкретнее — psexec из этого набора утилит. Скачать это добро можно здесь.

После того как скачали, нужно эти утилиты разархивировать куда-нибудь. Я обычно на диске C: создаю папку ps, что бы удобнее было добираться до утилит. Установки они не требуют. Для того что бы подключиться к удаленному компьютеру в командной строке набираем:

c:\ps\PsExec.exe \\192.168.1.114 -u domain\user -p password cmd

За место cmd можно например запустить какой-нибудь батник или другую команду.

Видео по теме:

11 8

Поделитесь статьей с друзьями в соц. сетях, возможно, она будет им полезна.


Если вам помогла статья, вы можете >>отблагодарить автора<<


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:\System\CurrentControlSet\Control\Terminal 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.

Меня всегда напрягал момент поиска утилиты удаленного рабочего стола в меню Пуск. Никогда не помнил, в каком именно разделе она находится и всегда тратил много времени на поиск.
Так я долго мучился,пока один добрый человек (спасибо тебе, Паша) не показал мне:
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 59 206 times, 4 visits today)

Posted by Rewalon

Access Remote Desktop Via Commandline

Command line syntax for Remote Desktop Connection

Syntax

mstsc [<connection file>] [/v:<server[:port]>] [/admin] [/f[ullscreen]] [/w:<width>] [/h:<height>] [/public] | [/span] [/edit «connection file»] [/migrate] [/?]

Command line parameters for Remote Desktop Connection

Parameter Description

/v:<server[:port]>

Specifies the remote computer you want to connect to.

/admin

Is used for administration of a terminal server. In this version of Remote Desktop Connection, if the Terminal Server role service is installed on the remote computer, running mstsc /admin will do the following (for the current connection only):

  • Disable Terminal Services client access licensing.

  • Disable time zone redirection.

  • Disable TS Session Broker redirection.

  • Disable TS EasyPrint.

/admin also does the following on connections to Windows Server 2008 with the Terminal Server role service installed:

  • Disables Plug and Play device redirection for this connection only.

  • Changes the remote session theme to Windows Classic View for this connection only.

To connect to a remote computer with the Terminal Server role service installed, follow these steps:

  1. Open the Command Prompt window by clicking the Start button Picture of the Start button, clicking All Programs, clicking Accessories, and then clicking Command Prompt.

  2. Type mstsc /v:server /admin.

/f

Starts Remote Desktop Connection in full-screen mode.

/w:<width>

Specifies the width of the Remote Desktop Connection window.

/h:<height>

Specifies the height of the Remote Desktop window.

/public

Runs Remote Desktop Connection in public mode.

/span

Matches the remote desktop width and height with the local virtual desktop, spanning across multiple monitors if necessary. To span across monitors, the monitors must all have the same height and be aligned side by side.

/edit «connection file»

Opens the specified .rdp connection file for editing.

/migrate

Migrates older connection files that were created with Client Connection Manager to new .rdp connection files.

/?

Lists these parameters.

Comments

  • 30 Aug 2011 11:58 AM

    Hi Arposh — Was checking MSTSC here and fouind your above help as is on my Vista-32, my Win7-64 also adds: [/multimon] and changes some text, eg ‘Migrates older’ is now ‘Migrates legacy’.. regds, pkn

  • 31 Aug 2011 1:22 PM

    pkn2011, You might want to mention that in the article. Thanks!

  • 31 Aug 2011 3:20 PM

    Hi, I’ve added a link to this page as a comment already as Arposh has added extra info here on Terminal server admin too. rgds, pkn

Remote-Desktop-Connection

Remote Desktop Protocol is a proprietary protocol developed by Microsoft which provides a user with a graphical interface to connect to another computer over a network connection. Most of us are administrators and we use this technology on a daily basis. Therefore, it isn’t new to us. Here is a link discussing all you need to know about the Kerberos delegation. Microsoft Terminal Services Client (MSTSC) is the command line interface to run the Microsoft Remote Desktop (RDP) client. It enables you to establish a remote connection to your Remote Desktop Server or Session Host (RDSH) as if you were directly connected. The mstsc command is used from within the Windows command line. In this article, you will learn about how to connect to the Remote Desktop console session from the command line.

You can type MSTSC directly into the search box on Windows 10 or from the Run dialogue box. You can also use the MSTSC command directly from the command line as well.  images below show what is obtainable and how to connect via the command line. There are a few different switches that you can use. I have described this topic extensively in this guide “how to protect Remote Desktop credentials with Windows Defender Remote Credential Guard or Restricted Admin Mode“. We will discuss all the various options available. 

image-44

image-43

Connect to Remote Desktop Console Session via the MSTSC Commands

The MSTSC command arguments used by an average user are /v and /f. You can use the command to set up the connection in seconds if the remote computer is in the same network or if you know the Internet Protocol (IP) address of the remote computer. The syntax of MSTSC is.

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

Available MSTSC Command Line Arguments

The following are the available command line arguments:

Switches Description
<connectionfile> The name of the .rdp file required for establishing the connection.
/v:<server[:port]> The remote computer or server where you want to connect.
/g:<gateway> The RD Gateway Server to be used for the connection. Required only if the endpoint remote PC is specified with /v.
/admin To establish the connection as an admin.
/f To view the Remote Desktop Window in full screen.
/w:<width> To specify the width of the Remote Desktop Window.
/h:<height> To specify the height of the Remote Desktop Window.
/public To run the Remote Desktop Connection publicly.
/span To match the width and height of the Remote Desktop with the local desktop.
/edit <connectionfile> To edit the specified .rdp file.
/multimon To make the monitor layout of the Remote Desktop Services session identical to the client-side configuration.
/restrictedAdmin To connect to the remote PC in the 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 To 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:<sessionID> The ID of the session to be shadowed.
/control To allow the control of the session when shadowing.
/noConsentPrompt To allow shadowing without user consent.
/migrate To migrate legacy connection files created with Client Connection Manager to new .rdp connection files.
/? To display help in the command prompt.

This command will connect you to the console session on a server rather than starting a new session. Please see the following guides: How to remove saved RDP credentials entries in Windows 10, how to remove entries histories from the Remote Desktop Connection, and how to prevent the saving of Remote Desktop Credentials in Windows. In place of an RDP client, you can also use AnyDesk!

mstsc / console

image-45

Command to open Remote Desktop in full-screen mode

Starts Remote Desktop Connection in full-screen mode. Add /f switch to the command. Input mstsc/f and then press the Enter key. After that, input the IP address, and click on Connect. Finally, type in the credentials of the remote PC and then you can connect successfully.

mstsc /f

mstsc /v:computername

To connect to the console session of the remote machine. The “address” field should be replaced with the address of the remote machine. The program launched is also known as Microsoft Terminal Server Connection. Once you launch the mstsc program with the correct address and switches as indicated above, you will be able to login with the desired account. This will be the account’s console session.

mstsc /console /V:address

Note: You can use RDP to remotely connect to the console session of the device with the /admin switch as shown below. A console session is either when you’re at the computer’s physical console or a remote connection that’s the same as if you’re at the computer’s physical console. I have described a useful use case in this guide “MBAM Frequent Report Errors: Understanding Microsoft BitLocker Administration and Monitoring compliance state and error status“

mstsc.exe /admin /v:<IP address of device>

I hope you found this blog post helpful. Now, you have learned all the available options on how to connect to the Remote Desktop console session from the Command Line. If you have any questions, please let me know in the comment session.

  • Windows удалить папку с подпапками
  • Windows удаленно выключить компьютер windows
  • Windows удалить маршрут по умолчанию
  • Windows сообщила что изменилось аппаратное оборудование устройства код ошибки 0xc004f211 windows 10
  • Windows удаление файлов мимо корзины