«Xrdp» и «VM»: разница между страницами

Материал из support.qbpro.ru
(Различия между страницами)
imported>Vix
 
imported>Supportadmin
 
Строка 1: Строка 1:
* [http://unixforum.org/index.php?showtopic=133976 сборка...]
http://nodejs.org/api/vm.html


==Переключение клавиатуры с удаленной машины==
'''2 - Unstable'''
Далее шрифты - этот бинарник ищет шрифты в /opt/X11rdp/lib/X11/fonts
Создал каталоги /opt/X11rdp/lib/X11, сделал симлинк fonts на папку со шрифтами уже стоящего X-сервера (у меня лежали в /usr/share/X11/fonts)
После этого X11rdp может запускаться, то есть уже можно виндовым клиентом терминалов заходить в sesman-X11rdp.
Однако setxkbmap не работает, видимо этот бинарник X11rdp ищет папку xkb где-то в другом месте. Поэтому, создал в /usr/local/lib/xrdp файл rus.map следующего содержания:


xkb_keymap {
В Node.js, JavaScript код может быть скомпилирован и сразу выполнен или скомпилирован, а запущен позже или скомпилирован, сохранен и еще позже запущен :). Для этого неоходимо включить в код require('vm');.
    xkb_keycodes  { include "xfree86+aliases(qwerty)"    };
    xkb_types    { include "complete"    };
    xkb_compat    { include "complete"    };
    xkb_symbols  { include "pc+ru(winkeys)+us:2+group(ctrl_shift_toggle)"    };
    xkb_geometry  { include "pc(pc104)"    };
};


Далее прописал в начале /usr/local/lib/xrdp/startwm.sh :
'''Внимание'''
для lxde - /usr/bin/startlxde


xkbcomp /usr/local/lib/xrdp/rus.map $DISPLAY
The vm module has many known issues and edge cases. If you run into issues or unexpected behavior, please consult the open issues on GitHub. Some of the biggest problems are described below.


Все. Теперь при входе язык русский, Ctrl+Shift переключает на английский.
'''Sandboxes'''
взято: [http://www.opennet.ru:8101/openforum/vsluhforumID15/1638.html тут]


* еще вариант [http://odtdocs.ru/informatika/14750/index.html?page=4 тут]
Аргумент sandbox в vm.runInNewContext и vm.createContext , наряду с аргументом initSandbox в vm.createContext, ведут себя не так, как можно было ожидать, и обычно их поведение варьируется между различными версиями Node.
if [ -r /etc/default/locale ]; then


. /etc/default/locale
The key issue to be aware of is that V8 provides no way to directly control the global object used within a context. As a result, while properties of your sandbox object will be available in the context, any properties from the prototypes of the sandbox may not be available. Furthermore, the this expression within the global scope of the context evaluates to the empty object ({}) instead of to your sandbox.


export LANG LANGUAGE
Your sandbox's properties are also not shared directly with the script. Instead, the properties of the sandbox are copied into the context at the beginning of execution, and then after execution, the properties are copied back out in an attempt to propagate any changes.


fi
'''Globals'''


setxkbmap -layout "us,ru(winkeys)" -model "pc105" -option "grp:ctrl_shift_toggle,grp_led:scroll"
Properties of the global object, like Array and String, have different values inside of a context. This means that common expressions like [] instanceof Array or Object.getPrototypeOf([]) === Array.prototype may not produce expected results when used inside of scripts evaluated via the vm module.
<hr>


==Удалённый рабочий стол в Ubuntu Linux==
Some of these problems have known workarounds listed in the issues for vm on GitHub. for example, Array.isArray works around the example problem with Array.


Сначала устанавливаем xrdp, он есть в репозиториях. Потом нужно установить последнюю версию x11rdp - это нормальный RDP сервер для Linux. Вся проблема лично для меня заключалась в нахождении его исходников. :)


Компилируем x11rdp:
=== vm.runInThisContext(code, [filename]) ===
# apt-get install subversion gcc libice-dev pkg-config zlib1g-dev cvs autoconf libtool libssl-dev libpam0g-dev libx11-dev libxfixes-dev xfonts-base 
$ svn co svn://server1.xrdp.org/srv/svn/repos/main/x11rdp_xorg71
$ mkdir /usr/local/X11rdp
$ cd x11rdp_xorg71
# sh buildx.sh /usr/local/X11rdp


Это займёт некоторое время. После успешной компиляции стоит сделать ссылки на xserver для xrdp:
vm.runInThisContext() компилирует код, запускает его и возвращает результат. Запущенный код не имеет доступа к локальной области видимости переменных (local scope). filename необязательный параметр, и используется только при трассировке (stack traces).
  # ln -s /usr/local/X11rdp/bin/X11rdp /usr/local/bin
# ln -s /usr/share/fonts/X11 /usr/local/X11rdp/lib/X11/fonts


И, наконец, указываем настройки для xrdp, чтобы он использовал x11rd. Правим /etc/xrdp/xrdp.ini:
Пример ипользования vm.runInThisContext и eval для запуска кода:
[globals]
bitmap_cache=yes
bitmap_compression=yes
port=3389
crypt_level=low
channel_code=1
[xrdp0]
name=sesman-X11rdp
lib=libxup.so
username=ask
password=ask
ip=127.0.0.1
port=-1


Вот и всё :) На самом деле всё очень просто! Это позволяет устанавливать одновременно несколько подключений, при нормальном rdp клиенте работают все сочетания клавиш и смены раскладок происходят без проблем. Если активных клиентов нет, работает только один процесс - xrdp. Я сейчас сижу на работе через удалённый рабочий стол ;)
<nowiki>var localVar = 123,
    usingscript, evaled,
    vm = require('vm');


* [http://hashcode.ru/questions/619/удалённый-рабочий-стол-в-ubuntu-linux статья тут]
usingscript = vm.runInThisContext('localVar = 1;',
  'myfile.vm');
console.log('localVar: ' + localVar + ', usingscript: ' +
  usingscript);
evaled = eval('localVar = 1;');
console.log('localVar: ' + localVar + ', evaled: ' +
  evaled);


* [http://rus-linux.net/nlib.php?name=/MyLDP/lvs/remote-graphical-desktops-on-linux.html еще руководство]
// localVar: 123, usingscript: 1
// localVar: 1, evaled: 1</nowiki>


==Debian 9 - настройка xrdp ==
===vm.runInNewContext(code, [sandbox], [filename])===
Терминальный RDP сервер Debian 9 + Xrdp
Год назад, я описал установку терминального сервера Debian+xRDP+X11-rdp.
В связи с переходом на другой гипервизор возникла необходимость его переустановки.
Так как за это время вышел 9-й релиз Debian, то естественно решено ставить его.
За этот год проект XRDP эволюционировал с версии 0.6.1 до версии 0.9.3 и установка сервера категорически упростилась.
После установки системы (при установке ставлю только системные утилиты, LXDE, SSH сервер и по желанию сервера печати), достаточно просто поставить XRDP из пакетов:


sudo apt update
vm.runInNewContext() компилирует код, а затем запускает его в sandbox и возвращает результат. Запущенный код не имеет доступа к локальной области видимости переменных (local scope). Объект sandbox используется как глобальный объект (global object) для кода. sandbox и filename необязательные параметры, и filename используется только при трассировке (stack traces).
sudo apt install -y xrdp


Вместе с пакетом xrdp поставится xorgxrdp, который собственно и является рекомендуемым командой xrdp RDP сервером, обеспечивающим удаленное подключение, а XRDP это прокси сервер, обеспечивающий одновременное подключение множества пользователей.
Example: compile and execute code that increments a global variable and sets a new one. These globals are contained in the sandbox.
Во время установки сгенерируется сертификат безопасности, который потом, при желании можно перегенерировать(я не стал).
После установки необходимо выполнить:


  dpkg-reconfigure xserver-xorg-legacy
  <nowiki>var util = require('util'),
    vm = require('vm'),
    sandbox = {
      animal: 'cat',
      count: 2
    };


* Выбрать - '''Кто угодно'''
vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');
console.log(util.inspect(sandbox));


Все, можно подключаться.
// { animal: 'cat', count: 3, name: 'kitty' }</nowiki>
В случае необходимости конфигурируем RDP параметры путем изменения настроек в /etc/xrdp/xrdp.ini
Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code requires a separate process.
и
/etc/xrdp/sesman.ini
в /etc/xrdp/xrdp.ini можно закомментировать  ненужные варианты подключений, например так:
в /etc/xrdp/sesman.ini настраиваем параметры сессии, использование буфера обмена и прочее(оба файла отлично комментированы и настройка не должна вызвать сложности)


mcedit /etc/xrdp/sesman.ini
In case of syntax error in code, vm.runInNewContext emits the syntax error to stderr and throws an exception.
= необходимое изменение =
[Security]
# Авторизация root. true - разрешено false - запрещено
'''AllowRootLogin=false'''


* Одна сессия для пользователя XRDP
==vm.runInContext(code, context, [filename])==
vm.runInContext compiles code, then runs it in context and returns the result. A (V8) context comprises a global object, together with a set of built-in objects and functions. Running code does not have access to local scope and the global object held within context will be used as the global object for code. filename is optional, it's used only in stack traces.


mcedit /etc/xrdp/sesman.ini
Example: compile and execute code in a existing context.
= вывод команды с необходимыми настройками =
[Globals]
ListenAddress=127.0.0.1
ListenPort=3350
EnableUserWindowManager=true
UserWindowManager=startwm.sh
DefaultWindowManager=startwm.sh
[Security]
'''AllowRootLogin=false'''
MaxLoginRetry=4
TerminalServerUsers=tsusers
TerminalServerAdmins=tsadmins
; When AlwaysGroupCheck=false access will be permitted
; if the group TerminalServerUsers is not defined.
AlwaysGroupCheck=false
[Sessions]
;; X11DisplayOffset - x11 display number offset
; Type: integer
; Default: 10
X11DisplayOffset=10 #
;; MaxSessions - maximum number of connections to an xrdp server
; Type: integer
; Default: 0
# Выставляем количество пользователей для одновременной работе на сервере
'''MaxSessions=3'''
;; KillDisconnected - kill disconnected sessions
; Type: boolean
; Default: false
; if 1, true, or yes, kill session after 60 seconds
# Не разрываем сеанс при отключении пользователя чтобы потом попасть в туже сессию
'''KillDisconnected=true'''
;; IdleTimeLimit - when to disconnect idle sessions
; Type: integer
; Default: 0
; if not zero, the seconds without mouse or keyboard input before disconnect
; not complete yet
IdleTimeLimit=0
;; DisconnectedTimeLimit - when to kill idle sessions
; Type: integer
; Default: 0
; if not zero, the seconds before a disconnected session is killed
; min 60 seconds
DisconnectedTimeLimit=0
;; Policy - session allocation policy
; Type: enum [ "Default" | "UBD" | "UBI" | "UBC" | "UBDI" | "UBDC" ]
; Default: Xrdp:<User,BitPerPixel> and Xvnc:<User,BitPerPixel,DisplaySize>
; "UBD" session per <User,BitPerPixel,DisplaySize>
; "UBI" session per <User,BitPerPixel,IPAddr>
; "UBC" session per <User,BitPerPixel,Connection>
; "UBDI" session per <User,BitPerPixel,DisplaySize,IPAddr>
; "UBDC" session per <User,BitPerPixel,DisplaySize,Connection>
Policy=Default
[Logging]
'''LogFile=/var/log/xrdp/xrdp-sesman.log'''
LogLevel=DEBUG
EnableSyslog=1
SyslogLevel=DEBUG
[Xorg]
param=Xorg
param=-config
param=xrdp/xorg.conf
param=-noreset
param=-nolisten
param=tcp
[Xvnc]
param=Xvnc
param=-bs
param=-nolisten
param=tcp
param=-localhost
param=-dpi
param=96
[Chansrv]
; drive redirection, defaults to xrdp_client if not set
'''FuseMountName=/tmp/thinclient_drives'''
[SessionVariables]
PULSE_SCRIPT=/etc/xrdp/pulse/default.pa
'''CHANSRV_LOG_PATH=/var/log/xrdp'''


'''Обязательно создать каталог: /var/log/xrdp'''
<nowiki>var util = require('util'),
mkdir -p /var/log/xrdp
    vm = require('vm'),
    initSandbox = {
      animal: 'cat',
      count: 2
    },
    context = vm.createContext(initSandbox);


* Раскладка клавиатуры
vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');
console.log(util.inspect(context));


$ sudo nano /etc/xrdp/xrdp_keyboard.ini
// { animal: 'cat', count: 3, name: 'CATT' }</nowiki>
Note that createContext will perform a shallow clone of the supplied sandbox object in order to initialize the global object of the freshly constructed context.


Изменить:
Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, vm.runInContext is quite useful, but safely running untrusted code requires a separate process.
(-) rdp_layout_us=us
(+) rdp_layout_us=us,ru


Добавить:
In case of syntax error in code, vm.runInContext emits the syntax error to stderr and throws an exception.


Пример на сайте проекта


в комментах
==vm.createContext([initSandbox])==
vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent call to vm.runInContext. A (V8) context comprises a global object together with a set of build-in objects and functions. The optional argument initSandbox will be shallow-copied to seed the initial contents of the global object used by the context.


[rdp_keyboard_ru]
==vm.createScript(code, [filename])==
keyboard_type=4
createScript compiles code but does not run it. Instead, it returns a vm.Script object representing this compiled code. This script can be run later many times using methods below. The returned script is not bound to any global object. It is bound before each run, just for that run. filename is optional, it's only used in stack traces.
keyboard_type=7
keyboard_subtype=1
model=pc105
options=grp:alt_shift_toggle
rdp_layouts=default_rdp_layouts
layouts_map=layouts_map_ru
[layouts_map_ru]
rdp_layout_us=us,ru
rdp_layout_ru=us,ru


In case of syntax error in code, createScript prints the syntax error to stderr and throws an exception.


перезапускаем XRDP
==Class: Script==
A class for running scripts. Returned by vm.createScript.


systemctl restart xrdp
==script.runInThisContext()==
Similar to vm.runInThisContext but a method of a precompiled Script object. script.runInThisContext runs the code of script and returns the result. Running code does not have access to local scope, but does have access to the global object (v8: in actual context).


Все, можно подключаться.
Example of using script.runInThisContext to compile code once and run it multiple times:
Настоятельно рекомендую удалить хранитель экрана, чтоб не грузить процессор.


  apt remove xscreensaver
  <nowiki>var vm = require('vm');


Если по какой то причине xorgrdp не устраивает  вот ссыдка  на документацию как собрать X11-rdp.
globalVar = 0;


Обратил внимание, что начинают появляться средства мониторинга и администрирования сессий и хотя они находятся в зачаточном состоянии, сама тенденция обнадеживает -
var script = vm.createScript('globalVar += 1', 'myfile.vm');
вот вывод man:
xrdp-sesadmin [options] -c=command


for (var i = 0; i < 1000 ; i += 1) {
  script.runInThisContext();
}


* файл /etc/xrdp/xrdp.ini
console.log(globalVar);


[Globals]
// 1000</nowiki>
; xrdp.ini file version number
==script.runInNewContext([sandbox])==
ini_version=1
Similar to vm.runInNewContext a method of a precompiled Script object. script.runInNewContext runs the code of script with sandbox as the global object and returns the result. Running code does not have access to local scope. sandbox is optional.
; fork a new process for each incoming connection
fork=true
; tcp port to listen
port=3389
; 'port' above should be connected to with vsock instead of tcp
use_vsock=false
; regulate if the listening socket use socket option tcp_nodelay
; no buffering will be performed in the TCP stack
tcp_nodelay=true
; regulate if the listening socket use socket option keepalive
; if the network connection disappear without close messages the connection will be closed
tcp_keepalive=true
#tcp_send_buffer_bytes=32768
#tcp_recv_buffer_bytes=32768
; security layer can be 'tls', 'rdp' or 'negotiate'
; for client compatible layer
security_layer=rdp
; minimum security level allowed for client
; can be 'none', 'low', 'medium', 'high', 'fips'
crypt_level=high
; X.509 certificate and private key
; openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 365
; certificate=
; key_file=
certificate=/etc/xrdp/certificate/cert.pem
key_file=/etc/xrdp/certificate/key.pem
; set SSL protocols
; can be comma separated list of 'SSLv3', 'TLSv1', 'TLSv1.1', 'TLSv1.2'
ssl_protocols=TLSv1, TLSv1.1, TLSv1.2
; set TLS cipher suites
#tls_ciphers=HIGH
; Section name to use for automatic login if the client sends username
; and password. If empty, the domain name sent by the client is used.
; If empty and no domain name is given, the first suitable section in
; this file will be used.
autorun=
allow_channels=true
allow_multimon=true
bitmap_cache=true
bitmap_compression=true
bulk_compression=true
#hidelogwindow=true
max_bpp=32
new_cursors=false
; fastpath - can be 'input', 'output', 'both', 'none'
use_fastpath=both
; when true, userid/password *must* be passed on cmd line
#require_credentials=true
; You can set the PAM error text in a gateway setup (MAX 256 chars)
#pamerrortxt=change your password according to policy at http://url
;
; colors used by windows in RGB format
;
blue=009cb5
grey=dedede
#black=000000
#dark_grey=808080
#blue=08246b
#dark_blue=08246b
#white=ffffff
#red=ff0000
#green=00ff00
#background=626c72
;
; configure login screen
;
; Login Screen Window Title
#ls_title=My Login Title
; top level window background color in RGB format
ls_top_window_bg_color=009cb5
; width and height of login screen
ls_width=350
ls_height=430
; login screen background color in RGB format
ls_bg_color=dedede
; optional background image filename (bmp format).
#ls_background_image=
; logo
; full path to bmp-file or file in shared folder
ls_logo_filename=
ls_logo_x_pos=55
ls_logo_y_pos=50
; for positioning labels such as username, password etc
ls_label_x_pos=30
ls_label_width=60
; for positioning text and combo boxes next to above labels
ls_input_x_pos=110
ls_input_width=210
; y pos for first label and combo box
ls_input_y_pos=220
; OK button
ls_btn_ok_x_pos=142
ls_btn_ok_y_pos=370
ls_btn_ok_width=85
ls_btn_ok_height=30
; Cancel button
ls_btn_cancel_x_pos=237
ls_btn_cancel_y_pos=370
ls_btn_cancel_width=85
ls_btn_cancel_height=30
[Logging]
LogFile=xrdp.log
LogLevel=DEBUG
EnableSyslog=true
SyslogLevel=DEBUG
; LogLevel and SysLogLevel could by any of: core, error, warning, info or debug
[Channels]
; Channel names not listed here will be blocked by XRDP.
; You can block any channel by setting its value to false.
; IMPORTANT! All channels are not supported in all use
; cases even if you set all values to true.
; You can override these settings on each session type
; These settings are only used if allow_channels=true
rdpdr=true
rdpsnd=true
drdynvc=true
cliprdr=true
rail=true
xrdpvr=true
tcutils=true
; for debugging xrdp, in section xrdp1, change port=-1 to this:
#port=/tmp/.xrdp/xrdp_display_10
; for debugging xrdp, add following line to section xrdp1
#chansrvport=/tmp/.xrdp/xrdp_chansrv_socket_7210
;
; Session types
;
; Some session types such as Xorg, X11rdp and Xvnc start a display server.
; Startup command-line parameters for the display server are configured
; in sesman.ini. See and configure also sesman.ini.
[Xorg]
name=Xorg
lib=libxup.so
username=ask
password=ask
ip=127.0.0.1
port=-1
code=20
[X11rdp]
name=X11rdp
lib=libxup.so
username=ask
password=ask
ip=127.0.0.1
port=-1
xserverbpp=24
code=10
[Xvnc]
name=Xvnc
lib=libvnc.so
username=ask
password=ask
ip=127.0.0.1
port=-1
#xserverbpp=24
#delay_ms=2000
[console]
name=console
lib=libvnc.so
ip=127.0.0.1
port=5900
username=na
password=ask
#delay_ms=2000
[vnc-any]
name=vnc-any
lib=libvnc.so
ip=ask
port=ask5900
username=na
password=ask
#pamusername=asksame
#pampassword=asksame
#pamsessionmng=127.0.0.1
#delay_ms=2000
[sesman-any]
name=sesman-any
lib=libvnc.so
ip=ask
port=-1
username=ask
password=ask
#delay_ms=2000
[neutrinordp-any]
name=neutrinordp-any
lib=libxrdpneutrinordp.so
ip=ask
port=ask3389
username=ask
password=ask
; You can override the common channel settings for each session type
#channel.rdpdr=true
#channel.rdpsnd=true
#channel.drdynvc=true
#channel.cliprdr=true
#channel.rail=true
#channel.xrdpvr=true


* Курсор в черном квадрате при подключении по RDP
Example: compile code that increments a global variable and sets one, then execute this code multiple times. These globals are contained in the sandbox.


Неожиданно после обновления системы Calculate Linux обнаружилось что стрелка курсора показывается черном квадрате. Проблема решается редактированием файла:
<nowiki>var util = require('util'),
    vm = require('vm'),
    sandbox = {
      animal: 'cat',
      count: 2
    };


mcedit /etc/xrdp/xrdp.ini
var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');
= часть вывода команды с необходимыми изменениями =
max_bpp=32
# Было true и с Сalculate Linux при подключении курсор в квадрате
'''new_cursors=false'''


* Сертификат при работе сервера XRDP
for (var i = 0; i < 10 ; i += 1) {
  script.runInNewContext(sandbox);
}


По умолчанию сертификат работает с сертификатами созданными при установке о чем свидетельствует информация в логе xrdp:
console.log(util.inspect(sandbox));


cat /var/log/xrdp.log
// { animal: 'cat', count: 12, name: 'kitty' }</nowiki>
= необходимая информация =
Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, script.runInNewContext is quite useful, but safely running untrusted code requires a separate process.
  Using default X.509 certificate: /etc/xrdp/cert.pem
  Using default X.509 key file: /etc/xrdp/key.pem


* Выпустим свой сертификат на 1 год по команде указанном в файле настройки xrdp. Создадим папку, перейдем туда и запустим команду генерации ключа:


mkdir /etc/xrpd/certificate
cd /etc/xrdp/certificate
openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 365


* Отредактируем файл настройки:


mcedit /etc/xrdp/xrdp.ini
= необходимые изменения =
; security layer can be 'tls', 'rdp' or 'negotiate'
; for client compatible layer
security_layer=negotiate
; minimum security level allowed for client
; can be 'none', 'low', 'medium', 'high', 'fips'
crypt_level=high
; X.509 certificate and private key
; openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 365
'''certificate=/etc/xrdp/certificate/cert.pem'''
'''key_file=/etc/xrdp/certificate/key.pem'''
; specify whether SSLv3 should be disabled
#disableSSLv3=true
; set TLS cipher suites
#tls_ciphers=HIGH


'''* Возможные проблемы:'''<br>
Появление в каталоге пользователя файла с запретом .thinclient_drives<br>
и лог файла от xrdp.


'''* Решение:''' внести в файл /etc/xrdp/xrdp.ini
  [Logging]
LogFile=/var/log/xrdp/xrdp-sesman.log
..
  [Chansrv]
; drive redirection, defaults to xrdp_client if not set
;FuseMountName=thinclient_drives
FuseMountName=/tmp/thinclient_drives
..
  [SessionVariables]
PULSE_SCRIPT=/etc/xrdp/pulse/default.pa
CHANSRV_LOG_PATH=/var/log/xrdp
и дополнительно создать каталог:
mkdir -p /var/log/xrdp


перезапускаем службу xrdp.
=== Методы ===
  /etc/init.d/xrdp restart
<nowiki>createContext([Object initSandbox]) -> Object</nowiki>
vm.createContext() '''''создает новый контекст''''' который используется в качестве второго аргумента при последующем вызове в vm.runInContext().
  <nowiki>createScript(String code[, String filename]) -> vm.Script</nowiki>
Этот скрипт может быть запущен намного позже использую другие методы VM. В случае синтаксической ошибки в коде,  createScript напечатает ошибку в stderr и вызовет exception(исключение).
<nowiki>runInContext(String code, Object context[, String filename]) -> String</nowiki>
vm.runInContext() компилирует код, а затем запускает его в контексте и возвращает результат.
<nowiki>runInNewContext(String code[, Object sandbox][, String filename])</nowiki>
vm.runInNewContext() компилирует код, а затем запускает его в sandbox и возвращает результат. Запущенный код не имеет доступа к локальной области видимости переменных (local scope). Объект sandbox используется как глобальный объект (global object) для кода. sandbox и filename необязательные параметры, и filename используется только при трассировке (stack traces).
<nowiki>runInThisContext(String code[, String filename]) -> String</nowiki>
vm.runInThisContext() компилирует код, как если бы он был загружен из файла, запускает его и возвращает результат. Запущенный код не имеет доступа к локальной области видимости переменных (local scope). filename необязательный параметр, и используется только при трассировке (stack traces).


== vm.Script ==


ИСТОЧНИКИ:
Этот объект создается как результат матода vm.createScript(). Он представляет собой некоторый скомпилированный код, чем может быть запущен позже.
<hr>
 
* [https://a-katyrev.blogspot.com/2018/01/rdp-debian-9-xrdp.html Терминальный RDP сервер Debian 9 + Xrdp]
===Methods===
* [http://renbuar.blogspot.com/2017/08/xrdp-debian-9-gnome.html Установка xrdp debian 9 gnome]
<nowiki>runInNewContext([Object sandbox]) -> String</nowiki>
* [https://sevo44.ru/xrdp-terminalnyj-server-linux/#Debian_9 Debian 9 - Xrdp]
Аналогичен vm.runInNewContext(), этот метод прекомпилирует Script object.
<nowiki>runInThisContext() -> String</nowiki>
Аналогичен vm.runInThisContext(), но  метод прекомпилирует Script object.

Версия от 12:43, 24 августа 2013

http://nodejs.org/api/vm.html

2 - Unstable

В Node.js, JavaScript код может быть скомпилирован и сразу выполнен или скомпилирован, а запущен позже или скомпилирован, сохранен и еще позже запущен :). Для этого неоходимо включить в код require('vm');.

Внимание

The vm module has many known issues and edge cases. If you run into issues or unexpected behavior, please consult the open issues on GitHub. Some of the biggest problems are described below.

Sandboxes

Аргумент sandbox в vm.runInNewContext и vm.createContext , наряду с аргументом initSandbox в vm.createContext, ведут себя не так, как можно было ожидать, и обычно их поведение варьируется между различными версиями Node.

The key issue to be aware of is that V8 provides no way to directly control the global object used within a context. As a result, while properties of your sandbox object will be available in the context, any properties from the prototypes of the sandbox may not be available. Furthermore, the this expression within the global scope of the context evaluates to the empty object ({}) instead of to your sandbox.

Your sandbox's properties are also not shared directly with the script. Instead, the properties of the sandbox are copied into the context at the beginning of execution, and then after execution, the properties are copied back out in an attempt to propagate any changes.

Globals

Properties of the global object, like Array and String, have different values inside of a context. This means that common expressions like [] instanceof Array or Object.getPrototypeOf([]) === Array.prototype may not produce expected results when used inside of scripts evaluated via the vm module.

Some of these problems have known workarounds listed in the issues for vm on GitHub. for example, Array.isArray works around the example problem with Array.


vm.runInThisContext(code, [filename])

vm.runInThisContext() компилирует код, запускает его и возвращает результат. Запущенный код не имеет доступа к локальной области видимости переменных (local scope). filename необязательный параметр, и используется только при трассировке (stack traces).

Пример ипользования vm.runInThisContext и eval для запуска кода:

var localVar = 123,
    usingscript, evaled,
    vm = require('vm');

usingscript = vm.runInThisContext('localVar = 1;',
  'myfile.vm');
console.log('localVar: ' + localVar + ', usingscript: ' +
  usingscript);
evaled = eval('localVar = 1;');
console.log('localVar: ' + localVar + ', evaled: ' +
  evaled);

// localVar: 123, usingscript: 1
// localVar: 1, evaled: 1

vm.runInNewContext(code, [sandbox], [filename])

vm.runInNewContext() компилирует код, а затем запускает его в sandbox и возвращает результат. Запущенный код не имеет доступа к локальной области видимости переменных (local scope). Объект sandbox используется как глобальный объект (global object) для кода. sandbox и filename необязательные параметры, и filename используется только при трассировке (stack traces).

Example: compile and execute code that increments a global variable and sets a new one. These globals are contained in the sandbox.

var util = require('util'),
    vm = require('vm'),
    sandbox = {
      animal: 'cat',
      count: 2
    };

vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');
console.log(util.inspect(sandbox));

// { animal: 'cat', count: 3, name: 'kitty' }

Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code requires a separate process.

In case of syntax error in code, vm.runInNewContext emits the syntax error to stderr and throws an exception.

vm.runInContext(code, context, [filename])

vm.runInContext compiles code, then runs it in context and returns the result. A (V8) context comprises a global object, together with a set of built-in objects and functions. Running code does not have access to local scope and the global object held within context will be used as the global object for code. filename is optional, it's used only in stack traces.

Example: compile and execute code in a existing context.

var util = require('util'),
    vm = require('vm'),
    initSandbox = {
      animal: 'cat',
      count: 2
    },
    context = vm.createContext(initSandbox);

vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');
console.log(util.inspect(context));

// { animal: 'cat', count: 3, name: 'CATT' }

Note that createContext will perform a shallow clone of the supplied sandbox object in order to initialize the global object of the freshly constructed context.

Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, vm.runInContext is quite useful, but safely running untrusted code requires a separate process.

In case of syntax error in code, vm.runInContext emits the syntax error to stderr and throws an exception.


vm.createContext([initSandbox])

vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent call to vm.runInContext. A (V8) context comprises a global object together with a set of build-in objects and functions. The optional argument initSandbox will be shallow-copied to seed the initial contents of the global object used by the context.

vm.createScript(code, [filename])

createScript compiles code but does not run it. Instead, it returns a vm.Script object representing this compiled code. This script can be run later many times using methods below. The returned script is not bound to any global object. It is bound before each run, just for that run. filename is optional, it's only used in stack traces.

In case of syntax error in code, createScript prints the syntax error to stderr and throws an exception.

Class: Script

A class for running scripts. Returned by vm.createScript.

script.runInThisContext()

Similar to vm.runInThisContext but a method of a precompiled Script object. script.runInThisContext runs the code of script and returns the result. Running code does not have access to local scope, but does have access to the global object (v8: in actual context).

Example of using script.runInThisContext to compile code once and run it multiple times:

var vm = require('vm');

globalVar = 0;

var script = vm.createScript('globalVar += 1', 'myfile.vm');

for (var i = 0; i < 1000 ; i += 1) {
  script.runInThisContext();
}

console.log(globalVar);

// 1000

script.runInNewContext([sandbox])

Similar to vm.runInNewContext a method of a precompiled Script object. script.runInNewContext runs the code of script with sandbox as the global object and returns the result. Running code does not have access to local scope. sandbox is optional.

Example: compile code that increments a global variable and sets one, then execute this code multiple times. These globals are contained in the sandbox.

var util = require('util'),
    vm = require('vm'),
    sandbox = {
      animal: 'cat',
      count: 2
    };

var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');

for (var i = 0; i < 10 ; i += 1) {
  script.runInNewContext(sandbox);
}

console.log(util.inspect(sandbox));

// { animal: 'cat', count: 12, name: 'kitty' }

Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, script.runInNewContext is quite useful, but safely running untrusted code requires a separate process.




Методы

createContext([Object initSandbox]) -> Object

vm.createContext() создает новый контекст который используется в качестве второго аргумента при последующем вызове в vm.runInContext().

createScript(String code[, String filename]) -> vm.Script 

Этот скрипт может быть запущен намного позже использую другие методы VM. В случае синтаксической ошибки в коде, createScript напечатает ошибку в stderr и вызовет exception(исключение).

runInContext(String code, Object context[, String filename]) -> String

vm.runInContext() компилирует код, а затем запускает его в контексте и возвращает результат.

runInNewContext(String code[, Object sandbox][, String filename])

vm.runInNewContext() компилирует код, а затем запускает его в sandbox и возвращает результат. Запущенный код не имеет доступа к локальной области видимости переменных (local scope). Объект sandbox используется как глобальный объект (global object) для кода. sandbox и filename необязательные параметры, и filename используется только при трассировке (stack traces).

runInThisContext(String code[, String filename]) -> String

vm.runInThisContext() компилирует код, как если бы он был загружен из файла, запускает его и возвращает результат. Запущенный код не имеет доступа к локальной области видимости переменных (local scope). filename необязательный параметр, и используется только при трассировке (stack traces).

vm.Script

Этот объект создается как результат матода vm.createScript(). Он представляет собой некоторый скомпилированный код, чем может быть запущен позже.

Methods

runInNewContext([Object sandbox]) -> String

Аналогичен vm.runInNewContext(), этот метод прекомпилирует Script object.

runInThisContext() -> String

Аналогичен vm.runInThisContext(), но метод прекомпилирует Script object.