Convenient remote control of the linux console from under Windows

Published on November 19, 2014

Convenient remote control of the linux console from under Windows

So friends, some subset of us (people) somehow feel the need to remotely control a computer (usually a server) on linux (the method can work on both BSD and Mac OS X, but I haven’t tried it) using ssh. Another subset uses Windows as the OS on the main production machine. The intersection of these subsets is addressed in my paper.

Utilities, for which the whole universe is conceived:
1. Maintaining a connection when the connection is disconnected. This item is the most important for me and played a decisive role in setting up such a system. The fact is that I live in a dormitory with a very, very unstable Internet, and disconnections from me (on bad days) can happen every minute. And putty requires a sequence of actions to reconnect every time
2. Saving the session, including the current directory, command history and output. Often, the only task when connecting to the server is: go to the same directory and write git pull. In order not to recall the path to this directory each time, you need to save session
3. The terminal supports tabs. Most importantly, this terminal can also be used for cmd, and for PS, and for git bash console. Therefore, you do not have to keep several different terminals open.
4. Pros of tmux: multi-windowing in one session and split

image

The recipe for success will include several points:
  1. Terminal - ConEmu code.google.com/p/conemu-maximus5
  2. Session Manager - tmux tmux.sourceforge.net
  3. Connector between client and server - mosh mosh.mit.edu
  4. Running * nix applications under windows - cygwin www.cygwin.com


Also, for all the manipulations we will also need a similar set of software:

  1. Putty or another ssh client;
  2. Remote server (I use ubuntu on aws, although this is not significant).


What do we get in the end?


As a result, we get a terminal with the ability to access a remote console. If the connection is disconnected (the Internet is disconnected, the ip-address is changed, the routing is changed, the connection is unstable, the laptop falls asleep etc), you won’t have to reconnect, and when you reconnect, the work context will not be lost.

Now in detail.

Configuration


We will configure our system in stages, starting with a remote server. We connect to it via ssh and set ...

Tmux


Tmux is a session manager, as they say, screen on steroids. To my distribution tmux was already bundled, and if not, then put it:

sudo apt-get install tmux

Or we collect from source:

git clone git://git.code.sf.net/p/tmux/tmux-code tmux
cd tmux
sh autogen.sh
./configure && make


Short cheat sheet by tmux
Скопировано из http://habrahabr.ru/post/126996/

Очень хороший способ запустить tmux:
tmux attach || tmux new — делая так, вы сперва пытаетесь подключиться к уже существующему серверу tmux, если он существует; если такого ещё нет — создаёте новый.

После этого вы попадаете в полноценную консоль.
Ctrl+b d — отключиться. (Точно так же вы отключитесь, если прервётся соединение. Как подключиться обратно и продолжить работу — см. выше.)

В одной сессии может быть сколько угодно окошек:
Ctrl+b c — создать окошко;
Ctrl+b 0...9 — перейти в такое-то окошко;
Ctrl+b p — перейти в предыдущее окошко;
Ctrl+b n — перейти в следующее окошко;
Ctrl+b l — перейти в предыдущее активное окошко (из которого вы переключились в текущее);
Ctrl+b & — закрыть окошко (а можно просто набрать exit в терминале).

В одном окошке может быть много панелей:
Ctrl+b % — разделить текущую панель на две, по вертикали;
Ctrl+b " — разделить текущую панель на две, по горизонтали (это кавычка, которая около Enter, а не Shift+2);
Ctrl+b →←↑↓ — переходить между панелями;
Ctrl+b x — закрыть панель (а можно просто набрать exit в терминале).

Недостаток — непривычным становится скроллинг:
Ctrl+b PgUp — вход в «режим копирования», после чего:
PgUp, PgDown — скроллинг;
q — выход из «режима копирования».


In the config, which is located in ~ / .tmux.conf, add the following:

new-session
set-window-option -g mode-mouse on
set -g history-limit 25000


The first line means that when you try to connect, if there is no active session, a new one is created. The second line includes mouse support, and the third sets the size of the story.

Mosh


Mosh in our bundle is a system that ensures uninterrupted connection. When the connection is broken, the program waits until the connectivity is restored and continues to work from the point of stop. It also helps with slow / unstable connections.

We install from the sources to get a version that supports all the necessary features:

git clone https://github.com/keithw/mosh.git
cd mosh/
sudo apt-get build-dep mosh
./autogen.sh && ./configure && make
sudo make install


Special configuration is not required.

Cygwin


Now go to the client side.

Cygwin is an alternative implementation of linux api that allows you to use linux utilities from under windows. It is installed from the official site (https://cygwin.com/install.html). I have x86_64 version. Download, install.
When choosing packages (in addition to the main ones), mosh and ssh should be noted:

image

No configuration is required.

Conemu


The last point is ConEmu . A wonderful terminal for windows. Supports a bunch of features, such as:

  1. tabs and split-screns;
  2. work with console applications using the console API;
  3. flexible configuration and management;
  4. work with flowers;
  5. ... and much more, details about this terminal can be found in the developer's article .

ConEmu is installed from the official site. Download, install (or unpack), run. At the first start, leave the checkmarks in place. Open the settings for Win + Alt + P. We are interested in the item Tasks.

Here's what the task of running cygwin looks like:

image

Create such an item for yourself, and you may need to replace the path with your installation path:

C:\cool\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico -

Save, close the settings, select our cygwin in the drop-down menu next to the plus sign in the upper right corner.
Now we need to achieve ssh connection to our server.

My command looks like this:

ssh -i key2014.pem -p 22

key2014.pem is my ssh private instance access key in aws. Perhaps it should be copied from the windows disk (which is mounted in / cygdrive) to the root folder.

The next step is to connect via Mosh:

mosh <username>@<hostname> --ssh=\"ssh -i key2014.pem -p 22\" -p 55505 -- tmux a

55505 - UDP port that I previously opened for incoming connections in the security rules in the aws admin panel. Now all connections will be conducted only through it (in addition to the initial establishment of communication - it goes through port 22).
tmux a - a command that is executed when connecting to the server (attach to a running tmux session).
We check. Works? Sumptuously! The final task is to create a new Task in ConEmu.

image

Specifically:

C:\cool\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico /bin/bash -l -c "mosh <username>@<hostname> --ssh=\"ssh -i key2014.pem -p 22\" -p 55505 -- tmux a"

I think everything is clear. Pay attention to the slashes before quotation marks. They distinguish the degree of enclosure of quotation marks.

Well, perhaps that's all. Now, when we want to connect to the server, launch ConEmu, poke the arrow next to the plus sign and select our Task.

Addition


Another simplification that I use is that I have added all the Task I need to call directly from Totcmd:

image

Normal cmd:

image

Connection to aws:

image

PS I
suggest that everyone who read this article offer suggestions on what else can be included in this scheme. Thanks for attention.

PPS
This article is a compilation of other articles taken from different places and their own developments. The only article I remember is http://xakep.ru/komfort-shell/