Как подключиться к удаленному серверу через консоль 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.8k33 gold badges137 silver badges210 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.8k33 gold badges137 silver badges210 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

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

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.8k33 gold badges137 silver badges210 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.8k33 gold badges137 silver badges210 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

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

Для настройки и управления удаленными серверами на базе Linux обычно используется протокол SSH. С помощью SSH на удаленный компьютер можно передавать данные и команды, которые будут выполняться так как бы они выполнялись на локальной машине.

В этой инструкции мы рассмотрим процесс подключения к SSH из Windows 10. Первый способ будет актуален для Windows 10 версии 1809 и выше, а второй можно использовать как на Windows 10, так и на Windows 7.

Подключение по SSH с помощью OpenSSH

Раньше для подключения к Linux серверу по SSH из Windows компьютера требовалась установка программы PuTTy или какого-то другого SSH-клиента. Но, в операционной системе Windows 10 (начиная с версии 1809) доступен клиент OpenSSH, с помощью которого можно подключаться к Linux серверам по SSH. Это позволяет работать с терминалом Linux прямо из командной строки Windows 10, при этом не требуется установка никаких сторонних программ.

Перед тем как использовать данный способ подключения необходимо проверить версию Windows 10. Для этого нажмите комбинацию клавиш Win-R и выполните команду «winver». Если на вашем компьютере установлена Windows 10 с версией 1809 или выше, то все нормально, в противном случае сначала нужно выполнить обновление.

версия Windows 10

Также нужно открыть меню «Параметры» и зайти в раздел «Приложения – Дополнительные возможности».

раздел Приложения – Дополнительные возможности

Здесь нужно пролистать список установленных дополнительных компонентов и найти в нем «Клиент OpenSSH». Если такой компонент присутствует, значит все нормально и можно переходить к следующему шагу. Если нет, то его нужно сначала установить с помощью меню «Добавить компонент».

Обратите внимание, не нужно путать «Клиент OpenSSH» и «Сервер OpenSSH». Для подключения по SSH вам нужен именно клиент.

Клиент OpenSSH - Добавить компонент

Также клиент OpenSSH можно установить с помощью PowerShell. Для этого запустите консоль PowerShell с правами администратора и выполните следующую команду:

Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

Более подробно об установке и удалении клиента OpenSSH можно почитать в официальной документации Майкрософт.

установка клиента OpenSSH

Если версия Windows 10 подходящая и клиент OpenSSH установлен, то можно начинать подключение по SSH. Для этого запустите обычную командную строку Windows и введите команду «ssh». В ответ вы должны получить информацию о работе с данной командой.

ssh в командной строке Windows 10

В общем случае синтаксис команды «ssh» выглядит следующем образом:

ssh user@server

Где «user» — это имя пользователя на удаленном сервере, а «server» — это имя компьютера или его ip адрес.

Например, если наш сервер доступен по ip адресу «192.168.1.214», а имя пользователя это «aleks», то команда для подключения будет выглядеть так:

ssh [email protected]

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

подключение по ssh в Windows 10

По умолчанию для SSH используется порт 22. Для того чтобы это изменить нужно использовать параметр «-p». Например, для подключения по порту 2222 нужно выполнить вот такую команду.

ssh [email protected] -p 2222

Если подключение предполагает использование ключей, то они должны находиться в папке «C:\Users\user\.ssh». А при подключении путь к приватному ключу нужно указать с помощью параметра «-i». Например, чтобы использовать ключ «C:\Users\stepu\.ssh\id_rsa» нужно выполнить:

ssh [email protected] -i C:\Users\stepu\.ssh\id_rsa

Более подробную информацию о команде «ssh» и ее параметрам можно получить на сайте man.openbsd.org/ssh или на opennet.ru (перевод).

Подключение по SSH через PuTTY

В тех случаях, когда версия Windows 10 не поддерживает OpenSSH (или используется Windows 7) к SSH можно подключаться с помощью программы PyTTY. Скачать установщик данной программы можно на официальном сайте www.putty.org.

После установки программы PyTTY ее можно будет запустить с помощью поиска в меню «Пуск»

запуск программы PyTTY

Сразу после запуска программы PuTTY появляется окно с настройками подключения. Основными параметры здесь находятся на вкладке «Session», здесь нужно ввести:

  • Имя компьютера или IP адрес;
  • Порт для подключения (по умолчанию, 22);
  • Способ подключения (SSH);

После ввода этих данных можно запускать подключение с помощью кнопки «Open».

подключение по ssh через программу PyTTY

Если для подключения к SSH используются ключи, то путь к приватному ключу нужно указать в разделе «Connection – SSH – Auth».

Обратите внимание, ключ должен быть сгенерирован программой PuTTYgen, которая устанавливается вместе с PuTTY. Если вы сгенерировали ключи с помощью OpenSSH, то их можно загрузить в PuTTYgen и сохранить в формате подходящем для PuTTy.

ввод приватного ключа в программу PyTTY

Если информация для подключения правильная, то вы увидите консоль с запросом на ввод имени пользователя пароля. Также при первом запуске появится запрос на добавление компьютера в список известных.

запрос логина и пароля в PyTTY

После ввода этих данных вы будете подключены к удаленному серверу по SSH.

Посмотрите также:

  • Как удалить папку в Linux через терминал (консоль)
  • Как открыть файл в терминале Linux
  • Как создать файл в Linux через терминал
  • Как скопировать файл в Linux через терминал
  • Как удалить файл в Linux через терминал

Автор
Александр Степушин

Создатель сайта comp-security.net, автор более 2000 статей о ремонте компьютеров, работе с программами, настройке операционных систем.

Остались вопросы?

Задайте вопрос в комментариях под статьей или на странице
«Задать вопрос»
и вы обязательно получите ответ.

Самым основным способом, как можно соединиться и управлять удаленным веб-сервером является командная строка (консоль). О том, что это такое я писал здесь.

Конечно, есть некоторые графические интерфейсы, которые позволяют управлять веб-сервером, такие как (ISPManager или C-panel), но количество действий и настроек системы, которые вы можете произвести с помощью этих интерфейсов очень ограниченно.

По настоящему и полноценно управлять удаленным веб-сервером можно только через командную строку. Именно поэтому очень важно освоить работу с этим инструментом как можно скорее. 

Задача этой статьи показать вам те способы, как вы можете соединиться с командной строкой на удаленном веб-сервере.

Для того, чтобы работать с командной строкой на удаленном компьютере, существует специальный протокол передачи данных, который называется SSH (Secure Shell — «безопасная оболочка»).

Соединившись по этому протоколу с удаленным компьютером вы сможете управлять им через командную строку.

Это соединение можно выполнить с помощью 2 основных способов.

Способ 1. Использовать специальную программу, которая называется SSH-клиент.

Для разных операционных систем написаны специальные программы, которые называются SSH-клиенты. С их помощью можно соединиться с удаленным сервером (с его командной строкой) по протоколу SSH.

Вот некоторые из таких программ:

Для Windows:

Putty, WinSCP и др.

Для Mac OS:

vSSH, ZOC и др.

Найти эти программы можно без труда с помощью поиска в Интернете.

Способ 2. Воспользоваться командной строкой на вашем компьютере.

Этот способ хорош тем, что не требует от вас какого-либо дополнительного программного обеспечения. Соединиться с удаленным сервером можно напрямую от одной командной строки к другой.

Я могу расписать как я это делаю на Mac OS, в остальных системах, наверняка есть способ сделать что-то подобное.

Итак, запускаем терминал и пишем там команду:

ssh имя_пользователя@имя_хоста

Например,

ssh root@95.132.34.151

Вас попросят ввести пароль для пользователя на сервере и если все правильно, вы соединитесь с удаленной командной строкой и сможете управлять сервером.

Очень удобно, быстро и не требует дополнительного ПО.

Выбирайте тот способ, который для вас более удобен и управляйте удаленным веб-сервером.

Больше уроков по работе с командной строкой здесь.

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.

  • Как поднять dlna сервер на windows 10
  • Как поднять php сервер на windows
  • Как поднять dhcp сервер на windows server 2019
  • Как поднять openvpn сервер на windows
  • Как подключиться к удаленному реестру windows 10