Linux service start permission denied

Ошибка bash permission denied

Многие новички пытаются выполнить запись определенных значений в системные файлы с помощью операторов перенаправления ввода и вывода и получают ошибку bash permission denied. Эта ошибка выводится, даже если вы использовали sudo.

Казалось бы, sudo есть, значит права суперпользователя получены и все должно работать но тут все не так просто. В этой статье мы рассмотрим почему возникает ошибка bash permission denied и как ее обойти.

Ошибка bash permission denied

Допустим, вы выполняете команду:

sudo echo «nameserver 8.8.8.8» >> /etc/resolv.conf

А в результате вместо записи строчки в /etc/resolv.conf получаете ошибку:

bash: /etc/resolv.conf permission denied

В русской локализации это будет отказано в доступе bash linux. Так происходит потому что вы запускаете с правами суперпользователя утилиту echo и она честно выводит вашу строку в стандартный вывод bash с правами суперпользователя. Но bash запущен от обычного пользователя, и когда интерпретатор bash пытается записать полученную строчку в системный файл, естественно, что вы получите ошибку.

Но существует несколько способов обойти это ограничение, вы можете, например, использовать команду tee, которая записывает стандартный вывод в файл или запустить саму оболочку от имени суперпользователя. Рассмотрим сначала вариант с tee:

echo ‘текст’ | sudo tee -a /путь/к/файлу

echo ‘nameserver 8.8.8.8’ | sudo tee -a /etc/resolv.conf

Это очень простое решение, но, кроме того, вы можете запустить оболочку bash с правами суперпользователя, чтобы дать ей доступ на запись:

sudo sh -c ‘echo текст >> /путь/к/файлу’
sudo bash -c ‘echo текст >> /путь/к/файлу’

sudo bash -c ‘echo nameserver 8.8.8.8 >> /etc/resolv.conf

Еще одно решение, призванное, упростить эту команду, добавить такой код в

sudoe() <
[[ «$#» -ne 2 ]] && echo «Usage: sudoe

» && return 1
echo «$1» | sudo tee —append «$2» > /dev/null
>

Дальше для вывода строки в файл выполняйте:

sudoe ‘текст’ >> /путь/к/файлу

sudoe «nameserver 8.8.8.8» > /etc/resolv.conf

Теперь все будет работать, как и ожидалось, и ошибка bash отказано в доступе не появится. Еще можно поменять права на файл, а потом уже выводить в него строку. Но это очень неправильное решение. И даже не потому, что это небезопасно, а больше потому что там намного больше действий.

Выводы

В этой небольшой статье мы разобрали почему возникает ошибка bash permission denied при использовании команды echo для системных файлов, а также несколько путей ее решения. Как видите, все достаточно просто. Надеюсь, эта информация была полезной для вас.

Читайте также:  Ebooks reader windows 10

Источник

Ошибка «Permission denied» в Linux

Все операционные системы семейства Linux имеют четко разграниченные права доступа. В своей домашней директории пользователь может делать все, что ему угодно, до тех пор, пока укладывается в отведенные рамки. Попытка выйти за них приводит к появлению ошибки «Permission Denied».

Изменение прав в терминале

Рассмотрим вариант, в котором необходимо прочесть текстовый документ, созданный другим пользователем. Файлы TXT в Linux можно просматривать непосредственно в терминале с помощью команды «cat».

    Заходим в каталог с интересующим нас документом. Набираем команду «cat filename», подставляя вместо «filename» имя нужного файла. На скриншоте показана ошибка «Permission Denied», выглядящая в русской локализации как «Отказано в доступе».

Получаем ошибку «Permission Denied» при попытке просмотреть содержимое файла

Проверяем права доступа к документу используя команду «ls -l»

Используем команду «chmod» и административные права для получения доступа

Просматриваем содержимое текстового документа командой «cat»

Изменение прав в файловом менеджере

Разберемся, как выполнить рассмотренную выше операцию в графическом интерфейсе, используя файловый менеджер из дистрибутива.

    Как видно на скриншоте, значок файла изначально имеет дополнительные символы, указывающие на то, что доступ у нему ограничен. При попытке посмотреть содержимое получаем графический вариант ошибки «Permission Denied».

При попытке открыть текстовый документ получаем ошибку «Permission Denied»

Открываем меню «Файл» и перезапускаем файловый менеджер от имени root

Набираем пароль root в окне аутентификации

Открываем параметры файла с помощью контекстного меню

На вкладке «Права» разрешаем доступ для группы root и остальных пользователей

Открываем ранее недоступный файл в режиме чтения и изучаем содержимое

В заключение

Как видим, избавиться от ошибки Permission Denied достаточно просто. Решив изменить правда доступа к системным файлам, лишний раз убедитесь, что полностью уверены в своих действиях и понимаете последствия вносимых изменений.

Источник

Ubuntu 20.04 LTS permission denied error #2080

Comments

michalvasko commented Aug 4, 2020

On Ubuntu 20.04, there is an error with yet unknown cause tracked in CESNET/netopeer2#621. In sysrepo it manifests in permission denied errors on most operations even when using the root user. The only solution we can suggest right now is not to use this distribution.

The text was updated successfully, but these errors were encountered:

gunterw commented Oct 8, 2020

Any updates on this issue?
I would like to move to 20.04, but require sysrepo2, so currently in a holding pattern.

michalvasko commented Oct 9, 2020

There are links to all the bug reports we did in the linked netopeer2 issue. Sadly, there still was no real answer and there is nothing more we can do. If you can make someone from Ubuntu take an interest in the issue, it would help a great deal.

jktjkt commented Oct 28, 2020

This is not a Ubuntu-specific issue. It’s caused by recent enough kernel (4.19+) and systemd (>= 241). The /dev/shm directory has the sticky bit set, this kernel patch added support for the fs.protected_regular sysctl knob, and this knob in turn gets enabled via systemd . As a result, one cannot use O_CREAT on «somebody else’s files» on those world-writable sticky directories.

I’ll follow up on a random kernel mailing list to find out if this is the expected behavior here (my personal opinion is «WTF?»).

Читайте также:  Script search and replace windows

michalvasko commented Oct 29, 2020

Um, okay, thanks for learning more about this and keep us posted. Also, it seems I am using kernel 5.8.15 and systemd 246 , everything is working fine.

jktjkt commented Oct 29, 2020

How does the output of sysctl fs.protected_regular look for you? If it returns 1 , you «should» have problems. If it’s at 0 , then this security mechanism is not used, and it should indeed work fine.

michalvasko commented Oct 29, 2020

Okay, it is 0 so I am wondering whether it is the default or it is set some other way.

jktjkt commented Oct 29, 2020 •

Looks like Ubuntu might have reverted to the older behavior. But from that bugreport it seems that they might be willing to implement the new defaults via the kernel package anyway in future — I don’t know.

You can check your /etc/sysctl* files and see what packages provide them.

michalvasko commented Oct 29, 2020

The config files on OpenSUSE are provided by special aaa_base package so that is probably not helpful. However, I have not found fs.protected_regular option set in any of those config files meaning it should be set to the default value.

gkatsikas commented Nov 4, 2020

I also experience this issue with a fresh Ubuntu 20.04.01 installation:

[ERR]: Failed to open «/dev/shm/. » (Permission denied).
[ERR]: Failed to update data for the new context.

Источник

Getting «standard_init_linux.go:207: exec user process caused «permission denied»» inside docker container for mattermost_app #401

Comments

Philippe-Cote-Morneault commented Jul 9, 2019

Hi, I followed every instruction from the readme and everything seemed to work fine. I’ll show you the exact commands I made in case someone sees something odd.

Step 1) My docker-compose.yml

Step 2) docker-compose build

Step 3) Create volumes
[root@organisationServices mattermost]# mkdir -p /srv/docker/mattermost/

Step 4) Give permissions to volumes
[root@organisationServices mattermost]# sudo chown -R 2000:2000 /srv/docker/mattermost/

Step 5) docker-compose up

Everything seems fine up to here. Also, I am root user, so the permission steps was optional but I did it anyways.

Here’s what happens when I log the mattermost_app_1 container:

I can’t find a way to get more logging information about this container. Also, this is the status for both containers:

So the container keeps restarting with the same error logs. Does anyone have any idea how to fix this and what is the issue?

Also, I am new to Docker. I want to host my database in my own postgres database without creating one with Mattermost. My only issue is understanding what would be the host for said database when adding it in docker-compose . What is the host of a database inside a docker container so I can add it in the docker-compose ?

The text was updated successfully, but these errors were encountered:

Philippe-Cote-Morneault commented Jul 9, 2019

I decided to run docker-compose build with a verbose flag to see if that can help:

pichouk commented Jul 9, 2019

Very surprising, can you just paste the result of ls -la /srv/docker/mattermost to ensure permissions are OK ? I’m pretty sure they should be OK with the command you ran but it seems to be a permissions issue.

Philippe-Cote-Morneault commented Jul 9, 2019 •

@pichouk Thanks for replying! Here’s the result:

Читайте также:  Windows 10 два монитора переключение

pichouk commented Jul 12, 2019

I don’t know, it should be ok.
i’ll try to ping a Mattermost developer to find what trigger this specific log message, maybe we can figure out then.

Philippe-Cote-Morneault commented Jul 12, 2019

@pichouk If you managed to get a hold of a developer that would be great! I also don’t understand why this isn’t working. The problems seem to stem from the container itself, so I wonder if the image is the problem. I also noticed that even if I gave arguments such as team edition in the docker-compose, the image built is enterprise edition.

hmhealey commented Jul 15, 2019 •

That doesn’t look like an error that would come from Mattermost. standard_init_linux.go seems to be part of Docker itself.

pichouk commented Jul 15, 2019

Gosh you’re right @hmhealey this is a Docker error.

@JigsawCorp Is your Docker installation working for other container ? Are you able to run docker run hello-world ? What is the output of docker info ?
I found several issues about this on Github :

egandro commented Aug 13, 2019

Did you do the «chown»?

santiago-mooser commented Oct 3, 2019 •

@egandro I changed the permissions but I’m having the exact same issue when using CentOS, so it seems to be a permissions issue specifically to do with CentOS (possibly SELinux?)

@pichouk You might want to look at the difference in permissions between Ubuntu and CentOS with and without SELinux

I tried this fix with no avail

I’ve attached some extra info for troubleshooting

Docker and dockerCE versions:

sudo ls -la volumes/app/mattermost/ outputs:

Docker logs [container_id] for app container outputs:

My current docker-compose.yml file is as following: essentially unchanged except for passwords, SSL enabling, and changing the volumes’ rw in the app container to Z (I get the same error with rw )

Temporary and unsafe fix

Change the user in the app container to root. This is really not recommended as it is not safe to run a container as root, but it gets the app working if you need it to:

ctivanovich commented Nov 28, 2019

I came across this error for an entirely different service, apache airflow on docker (the puckel image), and what worked in my case was deleting previous docker volumes that were somehow overloading the namespace even though I had moved the build files to a new location and had been trying to mount entirely different volumes to the container.

AaronSharp5 commented Apr 16, 2020

I also encountered this issue in a totally different service*. In my case, the base image I used was Alpine Linux, and my Entrypoint file had the shebang line #!/bin/bash . By replacing it with #!/bin/sh , I got past the error message. It should have been an obvious fix, but the error message didn’t really help me find it.

*My issue had nothing to do with mattermost, but at time the of writing, this issue was the top Google hit when I searched the text of the error message. Hopefully this comment will help others facing the same issue, whether or not they’re using mattermost.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Оцените статью