Centos permission denied как исправить

Обновлено: 04.07.2024

Today when I try to SSH into my server, I get a permission denied message (same for sftp ). It used to work well before, I didn't change any server settings, except I was trying to modify a few folders chown permission.

Root user can ssh / sftp without problem.

(For root user, there is no .ssh/authorized_keys file, only a .ssh/known_hosts file. For normal user home folder does not have a .ssh folder).

65.8k 30 30 gold badges 176 176 silver badges 217 217 bronze badges

2 Answers 2

you said you have root access. ssh to the box as root and see what exactly is causing it. check the master log file /var/log/messages .

keep this command tail -f /var/log/messages running in a terminal and ssh to the server as a normal user. Look at the entries in log file.

It sounds like you might have changed the permissions of your

/.ssh directory and/or your

/.ssh/authorized_keys file. Or possibly made your home dir group or world writable.

/.ssh should be 700 (drwx------) and

/.ssh/authorized_keys should be 600 (-rw-------).

Your private key file(s) in

/.ssh ( id_rsa , id_dsa , etc) should also be 600. The perms on the public key files ( id_rsa.pub , id_dsa.pub , etc) are less strict - they can be world-readable.

All these files and directories should be owned by your user.

If your home directory is world-writable and StrictModes is set in sshd_config (default is "yes"), then sshd will not trust anything underneath your home directory (including

/.ssh and everything in it) because a world-writable hoome dir means any user on the system could have created or modified the files.

I'm not sure how sshd on Centos handles group-writable home dirs, but the same may apply if your home dir is group-writable - any user in the group may have created/altered the

/.ssh files. (IIRC Debian's sshd is configured to allow group-writable home dirs because Debian's adduser traditionally creates a group for each user which only the user is a member of)

Многие новички пытаются выполнить запись определенных значений в системные файлы с помощью операторов перенаправления ввода и вывода и получают ошибку 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 'текст' >> /путь/к/файлу

sudoe "nameserver 8.8.8.8" > /etc/resolv.conf


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

Выводы

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

I thought that I knew how to set up permissions in Linux. I apparently don't.

I have a user called "web3". This user was automatically created by ISPConfig (A server management application like CPannel).

I also have an application that I installed on the server called "Drush". I installed "Drush" while logged in as root. This application is located at:

This file and it's containing folder have the following permissions:

Since the file allows read and execute permissions to everyone, how come every time I login as the "web3" user and try to run the aforementioned application I get the following error message:

I have faced this problem before but I resorted to giving sudo full root permissions to the user I was having problems with. On a local development environment, this is not a big deal. I am managing my own Dedicated Server now and this sledgehammer solution will not do.

What am I doing wrong?

I'd appreciate any help!


123 1 1 gold badge 1 1 silver badge 5 5 bronze badges

2 Answers 2

/root/ is root's home directory. The permissions on /root/ are hopefully 700, preventing anyone but root from traversing the entire directory tree below it.

You're being prevented from running the binary as a non-root user by permissions further up the directory tree.

Installing anything into /root/ is unusual, you would normally install executable code to be used by multiple users into /opt/ or another directory.

So those are the two main things that are 'wrong'. You need to find a better location to install the code, and to ensure the full path is accessible to the users you want to use it.

Lastly, as others have pointing out, while you often need to be root to complete an install, the resulting files should only be owned by root if absolutely necessary. In many cases, specific users are created (such as the www-data user, or an oracle user) which limits exposure if the code is compromised. I don't know your application, but it might be worth either installing it as the web3 user or installing it as root, but changing the permissions later to a non-privileged user created specifically for the task.

You should resist the urge to open up the permissions on /root/ to fix the issue, and sudo is a sticking plaster over the problem. The problem is that you should not install executable code into root's home directory.


19.8k 4 4 gold badges 55 55 silver badges 60 60 bronze badges What was puzzling to me was that I needed to have permissive permissions down the directory tree. I thought that, as long as the current folder had enough permissions, I should have access to the files/folders that I was trying to access. Is this a permission rule for the entire Linux environment or is it just some special characteristic of the root home folder?

Just checking the permissions of the containing folder will not be enough: you'll need to check the permissions of all the higher-level folders, up to the root directory. For example, like this:

You may find that the /root directory has permissions 700 (or drwx------ ), and that is blocking the web3 user from proceeding any further on that path. It is not a good idea to let other users access the home directory of the root user, although you technically could give it permissions 711 ( drwx--x--x ) if you consider it absolutely necessary.

But it is possible that this won't help you either.

You're using CentOS 7, which has SELinux enabled by default.

RHEL/CentOS has a default SELinux configuration that usually has a pretty negligible effect on regular user accounts, but it can place some strict limits on system services - like a web server, for example.

Under SELinux, it is possible to restrict a process and all of its descendants from certain actions - independently from traditional Unix-style user/group/permissions system. Those restrictions can be configured to automatically "latch on" when certain binaries are executed, for certain system users, and on a multitude of other conditions.

One of the default SELinux restrictions for a webserver is that access to anything outside specifically enabled directories like /var/www is blocked, unless specifically enabled using a SELinux boolean, a kind of switchable option in SELinux ruleset. I think this might be another thing stopping the web3 user from accessing the Drush application.

If you want a web server (or any of its descendants, like a PHP interpreter) to access any content that is not under /var/www and is created by other users, you'll need to run this command:

On RHEL/CentOS, each system service has an additional man page, named like <service name>_selinux , that contains information on SELinux restrictions and booleans for that specific service. Those man pages come in a RPM package named selinux-policy-doc : here's more information about that package. If you're using a system with SELinux enabled, you really should read those man pages for all the services you're planning to run: they make dealing with SELinux just so much easier.

Of course, you may find on the internet a lot of suggestions on how to disable SELinux, but if you are planning to run a secure server, that might not be the best option.

Favorite

Добавить в избранное

Главное меню » Операционная система Linux » Ошибка SSH в Linux. Исправление разрешения denied (publickey)

(1 оценок, среднее: 5,00 из 5)

Ошибка SSH в Linux. Исправление разрешения denied (publickey)

Е сли вы пытаетесь подключиться к удаленному серверу через SSH, вы можете столкнуться с ошибкой, отказано в доступе. Эта ошибка может произойти по ряду причин. И исправление этой проблемы зависит от причины ошибки.

В нашем случае у нас были общедоступные и закрытые ключи, хранящиеся на рабочем столе Ubuntu 16.04. После выпуска Ubuntu 18.04 мы решили перейти на эту новую версию. Мы предпочитаем новую установку поверх обновлений дистрибутива.

Итак, мы сделали резервную копию основных папок моего домашнего каталога, включая папку .ssh, на которой были открытые и закрытые ключи на внешнем диске. После установки Ubuntu 18.04 мы восстановили все, включая ключи SSH.

Теперь, когда мы попытались подключиться к удаленному серверу с помощью ssh, то подумали, что это сработает сразу, потому что были такие же публичные и закрытые ключи.

Но это не сработало. SSH выдал эту ошибку:

Ошибка исправления отказа от прав (publicickey)

Поэтому проблема заключается в разрешении файлов. Видите ли, когда мы копировали файлы, USB флешка была в формате файла FAT Microsoft. Этот файл не поддерживает разрешения файлов UNIX/Linux.

И, следовательно, разрешения на скопированные ключи ssh были изменены на 777.

Для SSH права доступа к файлу слишком открыты. Просто не разрешено иметь 777 для открытых или закрытых ключей. И вот почему SSH отказался от подключения.

Закрытый ключ должен иметь права на чтение и запись только для пользователя и другие разрешения для группы и других.

Вы должны изменить разрешение, используя команду CHMOD:

Аналогично, открытый ключ не должен иметь права на запись и выполнение для группы и других.

Теперь, когда вы установили правильные разрешения, вы можете снова подключиться к ssh. Он попросит пароль администратора чтобы разблокировать ключи. Введите пароль администратора.

Дайте нам знать в разделе комментариев, исправление работает для вас или нет. Также предложите свое мнение о копировании ключей ssh на другие компьютеры.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Читайте также: