Environment variable home linux or homepath windows are not set

I want to control my pm2 app via apache server. I have tried it via a bash script and php. Here is my index.php: <meta c <?php if (isset($_POST['Righ...

I want to control my pm2 app via apache server. I have tried it via a bash script and php. Here is my index.php:

<html>
<head>
<meta c
</head>


<?php
if (isset($_POST['RightOPEN']))
{
exec("/home/pi/startmm.sh");
}
if (isset($_POST['LeftOPEN']))
{
exec("/home/pi/channel4.sh");
}
?>
<form method="post">
<button name="LeftOPEN">Channel 4</button>&nbsp;
<button name="RightOPEN">Mirror</button><br>



</form>
</html>

and my channel4.sh is:

#!/bin/bash
pm2 stop mm

and startmm.sh:

#!/bin/bash
pm2 start mm

Can anyone help? It doesnt seem to work and I get the following errors on my apache log:

[PM2][Initialization] Environment variable HOME (Linux) or HOMEPATH (Windows) are not set!
[PM2][Initialization] Defaulting to /etc/.pm2
Error: EACCES: permission denied, mkdir '/etc/.pm2'
    at Object.mkdirSync (fs.js:757:3)
    at sync (/usr/lib/node_modules/pm2/node_modules/mkdirp/index.js:71:13)
    at Function.sync (/usr/lib/node_modules/pm2/node_modules/mkdirp/index.js:77:24)
    at module.exports.Client.initFileStructure (/usr/lib/node_modules/pm2/lib/Client.js:132:25)
    at new module.exports (/usr/lib/node_modules/pm2/lib/Client.js:37:8)
    at new API (/usr/lib/node_modules/pm2/lib/API.js:107:19)
    at Object.<anonymous> (/usr/lib/node_modules/pm2/lib/binaries/CLI.js:22:11)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
Error: EACCES: permission denied, mkdir '/etc/.pm2'

asked Feb 27, 2020 at 23:41

Ahmed.B's user avatar

You can see this is a permission error from permission denied, mkdir '/etc/.pm2'. As you are invoking a shell script from the web browser you most likely need to give the www-data user permission to execute the script as a root user.

If you edit the sudoers file, most likely: sudo vi /etc/sudoers, and add a line similar to this at the end www-data ALL=(root) NOPASSWD: /full/path/to/thescript.sh, this will allow the shell script to be invoked as a root user from the web browser, meaning it shouldn’t fail to create any directories.

You can add a line for each individual script (recommended) or allow all www-data to execute all scripts as root (dangerous) but here — www-data ALL=(root) NOPASSWD:ALL

Dont forget to restart your server sudo service apache2 restart

Hope this helps.

answered Feb 28, 2020 at 2:06

omeanwell's user avatar

omeanwellomeanwell

1,6981 gold badge10 silver badges15 bronze badges

7

This is an error because pm2 doesn’t find home variable. There are two steps to solve it.

Step 1. Running apache from your user.

Let’s suppose your user name is $USER through which you have started your pm2 process.
Run command sudo nano /etc/apache2/envvars and edit below lines with your user.

export APACHE_RUN_USER=$USER
export APACHE_RUN_GROUP=$USER

After this run below command to restart apache

sudo systemctl restart apache2

Step 2. Exporting home variable.
Lets suppose your user is $USER , then its home dir path would be /home/$USER .

When running any shell command in PHP first export the HOME variable as shown below

shell_exec("export HOME=/home/$USER && your command here 2>&1")

You are done, now your pm2 command will execute without any permission issue.

answered Jul 26, 2022 at 14:59

Surya Pratap's user avatar

Hi.

I’m trying to deploy Nest.js app with help of GitHub actions and PM2. In workflow logs, I can see that the app was started (as root).

[PM2][Initialization] Environment variable HOME (Linux) or HOMEPATH (Windows) are not set!

[PM2][Initialization] Defaulting to /etc/.pm2

[PM2] Spawning PM2 daemon with pm2_home=/etc/.pm2

[PM2] PM2 Successfully daemonized

[PM2] Starting /root/actions-runner/_work/_tool/node/16.5.0/x64/bin/npm in fork_mode (1 instance)

[PM2] Done.

┌─────┬─────────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐

│ id │ name │ namespace │ version │ mode │ pid │ uptime │ ↺ │ status │ cpu │ mem │ user │ watching │

├─────┼─────────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤

│ 0 │ api │ default │ N/A │ fork │ 7701 │ 0s │ 0 │ online │ 0% │ 27.1mb │ root │ disabled │

└─────┴─────────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

But when I ssh to the VPS and run pm2 ls command, I can’t see anything.

Any help would be appreciated.

1. Вопрос: / bin / sh: node: команда не найдена

[[email protected] ~]# salt 'uat01007' cmd.run "node -v"
uat01007:
    /bin/sh: node: command not found
ERROR: Minions returned with non-zero exit code

[[email protected] ~]# node -v
v8.12.0
[[email protected] ~]# whereis node
node: /usr/local/node-v8.12.0-linux-x64/bin/node

Решение:

[[email protected] ~]# ln -s /usr/local/node-v8.12.0-linux-x64/bin/node /usr/bin/node
[[email protected] ~]# ln -s /usr/local/node-v8.12.0-linux-x64/bin/npm /usr/bin/npm
[[email protected] ~]# ln -s /usr/local/node-v8.12.0-linux-x64/bin/pm2 /usr/bin/pm2

[[email protected] ~]# salt 'uat01007' cmd.run "node -v"
uat01007:
    v8.12.0

2. Проблема: Saltstack может удаленно выполнять статус pm2, но запущенный процесс не виден.

[[email protected] ~]# salt 'uat01007' cmd.run "pm2 status"
uat01007:
    [PM2][Initialization] Environment variable HOME (Linux) or HOMEPATH (Windows) are not set!
    [PM2][Initialization] Defaulting to /etc/.pm2
    ┌──────────┬────┬─────────┬──────┬─────┬────────┬─────────┬────────┬─────┬─────┬──────┬──────────┐
    │ App name │ id │ version │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │
    └──────────┴────┴─────────┴──────┴─────┴────────┴─────────┴────────┴─────┴─────┴──────┴──────────┘
     Use `pm2 show <id|name>` to get more details about an app

[[email protected] qadist]# pm2 status
┌──────────┬────┬─────────┬──────┬───────┬────────┬─────────┬────────┬─────┬───────────┬──────┬──────────┐
│ App name │ id │ version │ mode │ pid   │ status │ restart │ uptime │ cpu │ mem       │ user │ watching │
├──────────┼────┼─────────┼──────┼───────┼────────┼─────────┼────────┼─────┼───────────┼──────┼──────────┤
│ app      │ 0  │ 2.0.0   │ fork │ 15233 │ online │ 0       │ 93m    │ 0%  │ 70.4 MB   │ root │ disabled │
└──────────┴────┴─────────┴──────┴───────┴────────┴─────────┴────────┴─────┴───────────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app

[[email protected] qadist]# ps -ef|grep pm2
root     15223     1  0 14:39 ?        00:00:02 PM2 v3.2.2: God Daemon (/root/.pm2)
root     17659     1  0 15:24 ?        00:00:00 PM2 v3.2.2: God Daemon (/etc/.pm2)
root     19961     1  0 16:06 ?        00:00:00 PM2 v3.2.2: God Daemon (/etc/.pm2)
root     20390 20010  0 16:13 pts/0    00:00:00 grep --color=auto pm2

Процесс устранения неполадок:

[[email protected] qadist]# PM2_HOME=/etc/.pm2 pm2 status
┌──────────┬────┬─────────┬──────┬─────┬────────┬─────────┬────────┬─────┬─────┬──────┬──────────┐
│ App name │ id │ version │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │
└──────────┴────┴─────────┴──────┴─────┴────────┴─────────┴────────┴─────┴─────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app

[[email protected] qadist]# PM2_HOME=/root/.pm2 pm2 status
┌──────────┬────┬─────────┬──────┬───────┬────────┬─────────┬────────┬──────┬───────────┬──────┬──────────┐
│ App name │ id │ version │ mode │ pid   │ status │ restart │ uptime │ cpu  │ mem       │ user │ watching │
├──────────┼────┼─────────┼──────┼───────┼────────┼─────────┼────────┼──────┼───────────┼──────┼──────────┤
│ app      │ 0  │ 2.0.0   │ fork │ 20794 │ online │ 0       │ 11m    │ 0.1% │ 44.9 MB   │ root │ disabled │
└──────────┴────┴─────────┴──────┴───────┴────────┴─────────┴────────┴──────┴───────────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app

Процессы, которые можно увидеть в разных PM2_HOME, различны.Процессы, запускаемые непосредственно из командной строки linux, находятся в /root/.pm2, а процессы, запускаемые saltstack, находятся в /etc/.pm2

Решение: разрешите процессам работать в /etc/.pm2

// Добавляем переменную окружения PM2_HOME, указывая на /etc/.pm2/
[[email protected] qadist]# cat /etc/profile.d/nodejs.sh 
export NODEJS_HOME=/usr/local/node-v8.12.0-linux-x64
export PATH=$PATH:$NODEJS_HOME/bin
export PM2_HOME=/etc/.pm2/
[[email protected] qadist]# source /etc/profile

 // Перезапускаем приложение
[[email protected] qadist]# PM2_HOME=/root/.pm2/ pm2 del all && pkill PM2 && pm2 start app.js
[PM2] Applying action deleteProcessId on app [all](ids: 0)
[PM2] [app](0) ✓
┌──────────┬────┬─────────┬──────┬─────┬────────┬─────────┬────────┬─────┬─────┬──────┬──────────┐
│ App name │ id │ version │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │
└──────────┴────┴─────────┴──────┴─────┴────────┴─────────┴────────┴─────┴─────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app
[PM2] Spawning PM2 daemon with pm2_home=/etc/.pm2/
[PM2] PM2 Successfully daemonized
[PM2] Starting /data/apps/zbcf-h5-pc/qadist/app.js in fork_mode (1 instance)
[PM2] Done.
┌──────────┬────┬─────────┬──────┬───────┬────────┬─────────┬────────┬─────┬───────────┬──────┬──────────┐
│ App name │ id │ version │ mode │ pid   │ status │ restart │ uptime │ cpu │ mem       │ user │ watching │
├──────────┼────┼─────────┼──────┼───────┼────────┼─────────┼────────┼─────┼───────────┼──────┼──────────┤
│ app      │ 0  │ 2.0.0   │ fork │ 11460 │ online │ 0       │ 0s     │ 0%  │ 11.4 MB   │ root │ disabled │
└──────────┴────┴─────────┴──────┴───────┴────────┴─────────┴────────┴─────┴───────────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app

[[email protected] qadist]# pm2 status
┌──────────┬────┬─────────┬──────┬───────┬────────┬─────────┬────────┬───────┬───────────┬──────┬──────────┐
│ App name │ id │ version │ mode │ pid   │ status │ restart │ uptime │ cpu   │ mem       │ user │ watching │
├──────────┼────┼─────────┼──────┼───────┼────────┼─────────┼────────┼───────┼───────────┼──────┼──────────┤
│ app      │ 0  │ 2.0.0   │ fork │ 11460 │ online │ 0       │ 5s     │ 12.9% │ 60.9 MB   │ root │ disabled │
└──────────┴────┴─────────┴──────┴───────┴────────┴─────────┴────────┴───────┴───────────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app

[[email protected] qadist]# ps -ef|grep pm2
root     11450     1  3 17:41 ?        00:00:00 PM2 v3.2.2: God Daemon (/etc/.pm2/)
root     11479 11242  0 17:41 pts/0    00:00:00 grep --color=auto pm2

 // Удаленное выполнение может видеть запущенный процесс
[[email protected] zbcf-salt]# salt 'uat01007' cmd.run 'pm2 status'
uat01007:
    [PM2][Initialization] Environment variable HOME (Linux) or HOMEPATH (Windows) are not set!
    [PM2][Initialization] Defaulting to /etc/.pm2
    ┌──────────┬────┬─────────┬──────┬───────┬────────┬─────────┬────────┬─────┬───────────┬──────┬──────────┐
    │ App name │ id │ version │ mode │ pid   │ status │ restart │ uptime │ cpu │ mem       │ user │ watching │
    ├──────────┼────┼─────────┼──────┼───────┼────────┼─────────┼────────┼─────┼───────────┼──────┼──────────┤
    │ app      │ 0  │ 2.0.0   │ fork │ 22792 │ online │ 0       │ 14m    │ 0%  │ 45.1 MB   │ root │ disabled │
    └──────────┴────┴─────────┴──────┴───────┴────────┴─────────┴────────┴─────┴───────────┴──────┴──────────┘
     Use `pm2 show <id|name>` to get more details about an app

I’ve been using various linux distributions for quite some time now and become accustomed to using the «~» key to indicate «home» when typing in paths.

Today, working in Windows 7, I found myself doing the same thing in the «File Name» field of a «File Open» dialog. I realized that I could substitute %HOMEPATH%, but this seems too long for repeated use. It’s certainly fine for scripting though (IMO).

Is there an equivalent to «~» in Windows? If not, is there a way to implement «~» as the %HOMEPATH% variable? I tried creating a System variable with «~» and the OS hasn’t given me any trouble with this (as far as I can tell), but it doesn’t seem to work.

Any suggestions would be much appreciated!

asked Oct 25, 2009 at 16:28

seedofc's user avatar

1

no. (to all of your questions)

the way of the hackerish-crazy: use autohotkey to check any typed key for «~», check that the user really means «~» and then replace that with the full path of %USERPROFILE% / %HOMEPATH%. but in general: no.

answered Oct 25, 2009 at 16:42

akira's user avatar

akiraakira

60k17 gold badges135 silver badges165 bronze badges

The only thing you can do is set the variable of ~ to your home directory:

set ~=%HOMEDRIVE%%HOMEPATH%

Which if you echo out the value of the variable:

echo %~%

You will see your home directory…

But if you do this inside of the command prompt you wont be able to use it inside of Windows. If you goto control panel -> System -> Advanced System Settings (or just Advanced if on XP) click on Environment Variables and click New under System Variables and set the variable name to ~ and the Variable Value to %HOMEDRIVE%%HOMEPATH% and click ok. You should be able to «run» %~% and it will take you to your home directory. Unfourntally, you cannot access the variable without the percent signs.

answered Oct 25, 2009 at 17:29

Natalie Adams's user avatar

Natalie AdamsNatalie Adams

2,1371 gold badge16 silver badges23 bronze badges

5

Perhaps this works for you too:

  1. Open Explorer and browse to the directory/folder containing your user dir.
  2. Right click and select Send to desktop as shortcut.
  3. Go to your desktop and rename that shortcut to ~.
  4. Open Explorer again on a random directory and input ~ in the address bar.
  5. It should take you to your home directory.

Not really suited for command line usage though. An alias would work here though

answered Oct 25, 2009 at 17:40

mr-euro's user avatar

mr-euromr-euro

4712 gold badges6 silver badges16 bronze badges

2

Download MSYS which is part of MinGW, and then set your HOME variable to whatever you want. In your MSYS shell, which is a bash shell, you will have ~ as your HOME directory. BTW: installing MSYS and MinGW is a snap with their installer and package manager.

Alternately, if you are so inclined, you can install Cygwin or KDE for Windows; either will give you a POSIX-like environment.

answered Nov 15, 2012 at 6:35

Mark Mikofski's user avatar

Я хочу управлять своим приложением pm2 через сервер apache. Я пробовал это через скрипт bash и php. Вот мой index.php:

<html>
<head>
<meta c
</head>


<?php
if (isset($_POST['RightOPEN']))
{
exec("/home/pi/startmm.sh");
}
if (isset($_POST['LeftOPEN']))
{
exec("/home/pi/channel4.sh");
}
?>
<form method="post">
<button name="LeftOPEN">Channel 4</button>&nbsp;
<button name="RightOPEN">Mirror</button><br>



</form>
</html>

И мой канал4.sh:

#!/bin/bash
pm2 stop mm

И startmm.sh:

#!/bin/bash
pm2 start mm

Кто-нибудь может помочь? Кажется, это не работает, и я получаю следующие ошибки в своем журнале apache:

[PM2][Initialization] Environment variable HOME (Linux) or HOMEPATH (Windows) are not set!
[PM2][Initialization] Defaulting to /etc/.pm2
Error: EACCES: permission denied, mkdir '/etc/.pm2'
    at Object.mkdirSync (fs.js:757:3)
    at sync (/usr/lib/node_modules/pm2/node_modules/mkdirp/index.js:71:13)
    at Function.sync (/usr/lib/node_modules/pm2/node_modules/mkdirp/index.js:77:24)
    at module.exports.Client.initFileStructure (/usr/lib/node_modules/pm2/lib/Client.js:132:25)
    at new module.exports (/usr/lib/node_modules/pm2/lib/Client.js:37:8)
    at new API (/usr/lib/node_modules/pm2/lib/API.js:107:19)
    at Object.<anonymous> (/usr/lib/node_modules/pm2/lib/binaries/CLI.js:22:11)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
Error: EACCES: permission denied, mkdir '/etc/.pm2'

2 ответа

Вы можете видеть, что это ошибка разрешения от permission denied, mkdir '/etc/.pm2'. Поскольку вы вызываете сценарий оболочки из веб-браузера, вам, скорее всего, потребуется предоставить пользователю www-data разрешение на выполнение сценария в качестве пользователя root.

Если вы отредактируете файл sudoers, скорее всего: sudo vi /etc/sudoers, и добавите строку, подобную этой, в конце www-data ALL=(root) NOPASSWD: /full/path/to/thescript.sh, это позволит вызывать сценарий оболочки от имени пользователя root из веб-браузера, это означает, что он не должен создавать никаких каталогов.

Вы можете добавить строку для каждого отдельного сценария (рекомендуется) или разрешить всем www-data выполнять все сценарии от имени пользователя root (опасно), но здесь — www-data ALL=(root) NOPASSWD:ALL

Не забудьте перезапустить сервер sudo service apache2 restart

Надеюсь это поможет.


0

omeanwell
28 Фев 2020 в 05:06

Это ошибка, потому что pm2 не находит домашнюю переменную. Есть два шага, чтобы решить эту проблему.

Шаг 1. Запуск apache от вашего пользователя.

Предположим, ваше имя пользователя $USER, через которое вы запустили процесс pm2. Запустите команду sudo nano /etc/apache2/envvars и отредактируйте строки ниже с вашим пользователем.

export APACHE_RUN_USER=$USER
export APACHE_RUN_GROUP=$USER

После этого запустите команду ниже, чтобы перезапустить apache

sudo systemctl restart apache2

Шаг 2. Экспорт домашней переменной. Предположим, что ваш пользователь $USER , тогда его путь к домашнему каталогу будет /home/$USER .

При запуске любой команды оболочки в PHP сначала экспортируйте переменную HOME, как показано ниже.

shell_exec("export HOME=/home/$USER && your command here 2>&1")

Готово, теперь ваша команда pm2 будет выполняться без каких-либо проблем с разрешением.


0

Keshav Bhamaan
26 Июл 2022 в 17:59

  • Remove From My Forums
  • Question

  • Hello Folks,

    maybe someone here can help. In a Windows 2008 R2 (+Xenapp 6) Environment, when I set user environment variables via «Advanced Settings» — «Environment Variables» those settings are not set throughout the user session. For example: If I open a command prompt
    after setting the environment variables (f.e. %HOMEDRIVE% -> H: and %HOMEPATH% -> ) and execute the set command, the previously configured environment variables are not active. It still shows the old variables %HOMEDRIVE% -> C: and %HOMEPATH% ->
    C:Usersname…

    Even if I enter the environment varibale into Windows Explorer (f.e. %homepath%), it jumps right to the location of the old variable.

    I even set the user environment variable via VBscript, which works quite nice (checked in «Advanced Settings» — «Environment Variables»), however if I try another set command, it still shows the old variables! Windows Explorer jumps to the old locations
    as well…

    Any ideas?

Answers

    • Marked as answer by

      Monday, May 16, 2011 7:48 AM

Понравилась статья? Поделить с друзьями:
  • Entry point not found windows 2000
  • Entg71bm не работает тачпад windows 10
  • Entering setup зависает при включении компьютера windows
  • Entering dnx mode waiting for fastboot command windows планшет
  • Enter windows safe mode windows 10