- linux-notes.org
- Настройка X11 forwarding используя ssh в Unix/Linux
- Установка ПО для настройки X11 forwarding используя ssh в Unix/Linux
- Установка xauth в Debian/Ubuntu
- Установка xauth в CentOS/RedHat
- Установка xauth в Fedora
- Установка xauth для других Unix/Linux ОС
- Настройка X11 forwarding используя ssh в Unix/Linux
- Использование X11 forwarding через ssh в Unix/Linux
- Навигация
- Настройка сервера
- Настройка клиента
- Запуск
- Настройка клиента Windows
- Установка Xming
- Настройка PuTTy
- Обсуждение
- Персональный блог Толика Панкова
- Стихи, рассказы, философия, IT, политика, панкизм, раздолбайство и болтовня.
- Выведенный из искусственной комы ополченец Бабай объявил, что не ждет ребенка от покойного осьминога Пауля
- Настройка X11-forwarding через ssh, с помощью PuTTY и Xming
- Is it possible to enable X11 forwarding on windows to windows?
- 2 Answers 2
- How to set up working X11 forwarding on WSL2
- 20 Answers 20
- Prerequisite
- How to forward X-server connection
- How to forward any TCP connection back to host
- How to forward any TCP connection from host into WSL2
- Performance
- How to Setup X11 forwarding in WSL2
linux-notes.org
Настройка X11 forwarding используя ssh в Unix/Linux
X11 forwarding — это механизм, позволяющий отображать на локальном клиентском компьютере графические интерфейсы X11 программ, запущенных на удаленном Unix/Linux сервере. SSH имеет возможность безопасного туннелирования X11 соединений, так что сеансы X11 forwarding-а шифруются и инкапсулируются. Если вы хотите настроить X11 forwarding через SSH, то данная тема именно для вас.
Установка ПО для настройки X11 forwarding используя ssh в Unix/Linux
Для X11 forwarding-а на удаленном сервере не требуется полная система X11. Однако, серверу необходимо установить xauth. xauth — это утилита, которая поддерживает конфигурации Xauthority, используемые сервером и клиентом для аутентификации сеансов X11. Чтобы установить xauth, выполните следующие действия на удаленном сервере.
Установка xauth в Debian/Ubuntu
И так, выполняем команду:
Переходим к настройке.
Установка xauth в CentOS/RedHat
И так, выполняем команду:
Установка xauth в Fedora
И так, выполняем команду:
Установка xauth для других Unix/Linux ОС
Можно создать docker контейнер и запустить его.
Переходим к настройке.
Настройка X11 forwarding используя ssh в Unix/Linux
И прописываем (приводим к виду):
Так же, можно прописать:
Перезапуск SSH сервера:
- Если используете Debian 6, Ubuntu или Linux Mint:
- Если используете Debian 7, CentOS/RHEL 7, Fedora
- Если используете CentOS/RHEL 6
Вышеупомянутая настройка, позволяет X11 форвардинг на хост сервера. Если вы хотели бы включить X11 forwarding для отдельного пользователя, вы можете использовать пользовательский файл конфигурации ssh (т. е. $HOME/.ssh/config). Таким образом, вы можете использовать переадресацию X11 только тогда, когда вы используете ssh для учетной записи пользователя. Открываем:
Мой файл выглядит следующим образом:
Если используете Vagrant, то внутри его, можно пробросить следующие опции:
Ну и далее запускаем все это дело.
Использование X11 forwarding через ssh в Unix/Linux
На локальном хосте должна быть установлена система с X11, чтобы отображать удаленные программы. Для того чтобы выполнить форвардинг, выполните:
После входа в систему вы можете запускать любую X11 программу на удаленном сервере, как обычно, и ее отображение будет отображаться на локальной клиентской машине.
Можно еще опции, передавать через коммандную строку:
Безопастность при использовании X11 forwarding через ssh
Обычно, не рекомендуется всегда работать с «ForwardX11 yes». Поэтому, если вы хотите использовать свои SSH-соединения с пвыщенной безопасностью, лучше всего сделать следующее:
- Не прописывать «ForwardX11 yes» в ваш «$HOME/.ssh/confi»g файл.
- Используйте «ForwardingX11» только когда вам это необходимо, используя «ssh -X your_user@your_server».
- Если вы можете, полностью отключите «X11Forwarding» на вашем сервере.
Вот и все, статья «Настройка X11 forwarding используя ssh в Unix/Linux» завершена.
Навигация
X11 SSH Forwarding
Настройка сервера
Настройка клиента
Запуск
Заходим на удаленный хост и потом запускаем приложение kopete
Сразу запустить приложение kopete
X11 connection rejected because of wrong authentication
Убедитесь что права на удаленном хосте принадлежат пользователю
Настройка клиента Windows
Установка Xming
Xming — порт сервера X Window System для операционной системы Microsoft Windows.
Скачать Xming с SourceForge и установить.
Настройка PuTTy
Указать адрес дисплея
Просто запускаем программу в терминале
Обсуждение
спасибо, всё работает на ура! только очень тормознуто (или это только у меня так?).
Да есть такое, что тормозит жутко, даже если через локалку
Алексей, радует, что причина тормозов в данном случае — не мои кривые ручки. а что посоветуете вместо данного решения? пробую сейчас xrdp (в линуксах не шибко разбираюсь), и через rdp из winxp у меня только консольное окно появилось, рабочего стола как такового нет. думаю вот, что делать дальше. 🙂
Кроме VNC ничего другого не использовал, так что советовать мне особо нечем
у меня уже всё получилось. доставил xrdp в систему, из winxp запустил терминальную сессию на ip-адрес компа с linux, увидел окошко терминала, набрал google-chrome (ради чего всё и затевал) и получил нужное. что радует, после закрытия терминального окна и повторного входа вижу всё ту же картинку, что и до закрытия. сам не ожидал, что всё так просто получится. Алексей, спасибо за статью и успехов в делах! 🙂
тоже настроил, всё работает кроме PHPStorm. запускаю, он запускается, но картинку на клиента не передаёт, а локально отображается почему-то. А все остальные программы работают как надо, удалённо.
Персональный блог Толика Панкова
Стихи, рассказы, философия, IT, политика, панкизм, раздолбайство и болтовня.
Выведенный из искусственной комы ополченец Бабай объявил, что не ждет ребенка от покойного осьминога Пауля
Настройка X11-forwarding через ssh, с помощью PuTTY и Xming
Вообще в Linux, а особенно на сервере под Linux вполне можно обходиться голой консолью, ибо все инструменты обычно в консольном варианте есть. Но иногда хочется запустить и графическое приложение, например программу разметки диска, а иногда без графики вообще не обойтись, если обрабатываешь видео или работаешь с виртуальными машинами. На наше счастье возможность удаленно работать с графическими программами есть. Называется это дело X11-Forwarding и существует оно аж в двух вариациях:
— XDMCP, нечто вроде RDP в винде — когда мы подключаемся к оконному менеджеру Linux, вводим свой логин/пароль и работаем с удаленным рабочим столом.
— И просто возможность запуска отдельных приложений (GIMP, GParted и т.д.)
К первому я еще может, когда-нибудь вернусь, а пока будем настраивать второе.
Настройка X11-forwarding в ssh на стороне Linux
Будем считать, что ssh у нас уже настроен. Правим конфиг демона ssh /etc/ssh/sshd_config
Раскомментируем или дописываем следующие строки:
X11Forwarding yes
X11DisplayOffset 10
X11UseLocalhost yes
Перезапускаем демон или рестартируем сервер.
Если надо, открываем порты на файерволе:
Для переопределения дисплея:
iptables -A INPUT -s x.x.x.x/xx -p tcp —dport 6000 -j ACCEPT
iptables -A OUTPUT -s x.x.x.x/xx -p tcp —sport 6000 -j ACCEPT
Вместо x.x.x.x/xx подставить нужную подсеть
Щелкаем по значку в лотке, открываем Конфигурация и в появившемся окне выбираем в дереве слева Соединение -> SSH -> X11
Выставляем все значения как на картинке и запоминаем число после localhost: (оно понадобится виндовому X-серверу).
Настройка виндового X-сервера
Их, наверное с десяток всякоразных наберется, но я особо не экспериментировал, все побежали и я побежал, взял самый популярный Xming
1. Качаем с официального сайта или напрямую с SourceForge
2. Устанавливаем
3. Настраиваем, запускаем Пуск -> Все программы -> Xming ->XLaunch
Выбираем Multiple windows и устанавливаем Display number таким же, как было настроено в PuTTY:
Нажимаем Далее и выбираем Start no client, тогда Xming «поселится» в трее и будет ждать, пока мы с консоли PuTTY запустим какое-нибудь графическое приложение.
В следующем окне я оставил все также, поскольку Font Server не настраивал.
Хотя глюк со шрифтами у меня был, но как оказалось, его исправление особого шаманства не требует.
Если нажать Готово в следующем окне, Xming сядет в лоток и будет ждать, пока мы запустим что-нибудь графическое из консоли. Например
gparted &
символ & — чтоб программа запустилась в фоновом режиме и не занимала консоль.
Чтобы каждый раз не лезть в XLaunch, можно в свойства ярлыка Xming дописать нужные параметры «C:\Program Files\Xming\Xming.exe» :0 -clipboard -multiwindow
Глюк с размером шрифтов и борьба с ним.
По умолчанию Xming почему-то выставляет ОЧЕНЬ маленький размер шрифта меню и диалоговых окон
Борьба проста. Дописываем в окне Additional Parameters XLaunch’а в строку Additional parameters for Xming параметр -dpi 96 или его же в свойства ярлыка. Число в параметре выбираем под свои глаза и монитор
Вот что получилось:
Источники не помню, но УМВР. И у друга тоже.
Is it possible to enable X11 forwarding on windows to windows?
I managed to connect to a win10 through putty, using newest openssh.
I am not sure it is so-called Microsoft support the ssh. And whether the openssh is almost fully functional.
While, at least i can connect to it through putty(kitty actually). I tried to set X11. Of course I know how to config x11, like localhost:0 and enable X11Forwarding.
Then I tried to execute sublime_text.exe through ssh. The process is up but no UI, is it possible to make X11 up? Or something like X11 that support win-system?
2 Answers 2
To get X11 forwarding working over ssh, you’ll need 3 things in place. 1.Your client must be set up to forward X11. 2.Your server must be set up to allow X11 forwarding. 3.Your server must be able to set up X11 authentication.
If you have both #1 and #2 in place but are missing #3, then you’ll end up with an empty DISPLAY environment variable.
X11 forwarding needs to be enabled on both the client side and the server side.
On the client side, the -X (capital X) option to ssh enables X11 forwarding, and you can make this the default (for all connections or for a specific conection) with ForwardX11 yes in
On the server side, X11Forwarding yes must specified in /etc/ssh/sshd_config. Note that the default is no forwarding (some distributions turn it on in their default /etc/ssh/sshd_config), and that the user cannot override this setting.
The xauth program must be installed on the server side. If there are any X11 programs there, it’s very likely that xauth will be there. In the unlikely case xauth was installed in a nonstandard location, it can be called through
/.ssh/rc (on the server!).
Note that you do not need to set any environment variables on the server. DISPLAY and XAUTHORITY will automatically be set to their proper values. If you run ssh and DISPLAY is not set, it means ssh is not forwarding the X11 connection.
To confirm that ssh is forwarding X11, check for a line containing Requesting X11 forwarding in the ssh -v -X output. Note that the server won’t reply either way.
How to set up working X11 forwarding on WSL2
When moving from WSL1 to WSL2 many things change; apparently this applies to X11 forwarding as well.
What steps do I need to make in order to use X11 forwarding with WSL2 on Windows 10 as I did with WSL1?
20 Answers 20
Add the following to your
Enable Public Access on your X11 server for Windows.*
Add a separate inbound rule for TCP port 6000 to the windows firewall in order to allow WSL access to the X server, as described by the wsl-windows-toolbar-launcher people.
As pointed out by WSL_subreddit_mod on reddit and as you can read in Microsoft’s documentation on WSL2, the WSL2 architecture uses virtualized network components. This means that WSL2 has a different IP address than the host machine. This explains why the X11 forwarding settings of WSL1 cannot simply be transferred to WSL2.
On the Ubuntu Wiki page about WSL you can already find a configuration adapted for WSL2 under Running Graphical Applications. A similar configuration is also suggested by the above mentioned Reddit User, who also contributes another part of the solution: Enable Public Access on the X11 server under Windows.
This means add the following to your
And Enable Public Access on your X11 server for Windows.*
The most important part to enable X11 forwarding for WSL2 on Windows 10 is still missing: the Windows firewall blocks connections via the network interface configured for WSL by default.
A separate inbound rule for TCP port 6000 is required to allow WSL access to the X server. After the rule has been created, as described by the wsl-windows-toolbar-launcher people, the IP address range can be restricted to the WSL subnet in the settings of the newly created rule, under Scope: 172.16.0.0/12.
*: If you use VcXSrv you can enable public access for your X server by disabling Access Control on the Extra Settings:
Or by calling vcxsrv.exe directly with the ac flag: vcxsrv.exe -ac as pointed out by ameeno on the github issue.
For some people who allowed only for private networks like me,
although they Should have been Both Ticked
It should have stop signs on Windows Defender firewall
Double click it and allow the connection for both private and public,
So all the 4 items should be ticked green.
Then the above answer from @NicolasBrauer was working for me.
Like disabling the access control when you XLaunch and
Using /etc/resolv.conf nameserver won’t work for me since I disabled resolv.conf generation in /etc/wsl.conf (I have a custom resolv.conf ).
Ultimately you want the WSL2 host IP address, which should also be your default route. Here’s my
/.bashrc entry for my Debian WSL2 distro:
Copied my answer from this github issue.
The idea is to use the ability to communicate over stdio.
Prerequisite
- Just so we can use socat in Windows host, you need a distribution running WSL1. I am sure you can do this in powershell but I didn’t have time to research this. Maybe someone can write a stdio->tcp redirector in powershell, then we wouldn’t need to have 2 WSL distros.
How to forward X-server connection
- Have your favorite X server running on Windows. By default they would listen to port 6000.
- In the WSL2 distro, run the following command in the background ( ubuntu is the name of the WSL1 distro with socat installed):
Basically this sets up a tunnel from the normal X unix domain socket into the host’s port 6000.
How to forward any TCP connection back to host
Let’s assume there is a tcp service running at port 5555 on Windows. In the WSL2 distro, run the following command in the background ( ubuntu is the name of the WSL1 distro with socat installed):
How to forward any TCP connection from host into WSL2
This is simply doing the same thing, but in the opposite direction. You can run the following in your WSL1 distro:
Performance
On my PC, it can handle up to 150MB/s of data so it’s not the fastest but fast enough for most applications.
For those who may work with simulation engines such as ROS/Gazebo, Unity and so on, another configuration is needed.
Be sure to enable both Public Access and Private Access for your X11 server in windows. Also disable any access control your X11 server supports.
If you use VcXSrv uncheck Native opengl. Final config for VcXSrv will be like:
Alternative good X11 servers with less difficulties are X410 and MobaXterm. For some details about this configuration refer here and here.
How to Setup X11 forwarding in WSL2
This answer assumes that you already have a working XServer and PulseAudio configuration running on your Windows host because you already were using WSL1. (You also may have to add the -ac parameter to the command line to get your XServer of choice to work with WSL2.)
The way that I do this, and to ensure that I get X11 forwarding no matter whether I am using a static IP address or DHCP on the Windows host, or even whether my hostname or network location changes, I add the following to my
After doing the above, no matter what my Hostname or IP address of the Host is, it will be placed in the environment each time a BASH session is started in WSL2. Test it by running firefox from the command line and watch a YouTube video. You should be able to hear the sound as well as see the app itself to watch the video. Test by launching other GUI apps from the command line in addition.
What it does: It uses the host command to pull the IPv4 Addresses associated with the Hostname from the output, greps the address that matches the line that contains your Windows Host IPv4 address, strips the rest of the information except for the IP Address, and then awks that and prints it into the variable, with the output trimmed. This then is used to provide the necessary IP address as a string for use in the environment variables that allow for forwarding of X11 and sound output.
Hopefully it works for you if the other methods don’t work for you (as they didn’t for me).
Most CLI apps can be run either from the BASH Prompt or from Windows Terminal. If you want to make a shortcut, most CLI apps can be set up like either of the following examples (no need for X11 forwarding in such cases except apps like Links2):
If you want to create desktop shortcuts for Linux GUI apps, unless you can get the environment variables from your
/.bashrc file to be used before launching the programs, you will have to create shortcuts using the following template, and put the program name in place of
You do not have to place the full command line for many programs. For PERL-based programs or Python-based programs, you sometimes will have to add the path for PERL and PYTHON, as well as your program’s full path, to run such GUI programs in Linux using WSL2. For one of my perl programs, I have to do it this way:
You may have to experiment a bit to get some apps working properly. For example, you might need to dbus-launch an app, and will need to add that command to the shortcut just before the program name.
And you might have to use a shorter variable name in some circumstances. Some apps just won’t work well, if at all, but this situation is improving over time. Also, don’t try to run the above from a Windows Command Prompt or from PowerShell. It will throw errors about ‘grep’ not being recognized as an internal or external command, etc.
Following is a screenshot of a few Linux GUI apps running on my Windows 10 system, with working X11 forwarding on WSL2.