- Ошибка «Permission denied» в Linux
- Изменение прав в терминале
- Изменение прав в файловом менеджере
- В заключение
- Linux / Unix Find Command Avoid Permission Denied Messages
- Find command basic syntax
- How to hide or fix find command permission denied messages
- How does it works?
- Exclude all “permission denied” messages from “find” command on Linux
- Conclusion
- Ошибка bash permission denied
- Ошибка bash permission denied
- Выводы
- Ubuntu says «bash: ./program Permission denied» [closed]
- 3 Answers 3
Ошибка «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 достаточно просто. Решив изменить правда доступа к системным файлам, лишний раз убедитесь, что полностью уверены в своих действиях и понимаете последствия вносимых изменений.
Источник
Linux / Unix Find Command Avoid Permission Denied Messages
W hen I type find . -type d -name «foo» command I get Permission denied error messages. How do I exclude all “permission denied: messages from the find command under Linux or Unix like operating systems?
The find command is used to locate files on a Linux or Unix like operating system. The find command will search directory to match the supplied search criteria. You can search for files by
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | find command+ Unix like os |
Est. reading time | 2m |
type, name, owner, group, date, permissions and more. By default the find will search all subdirectories for you. Let us see how to hide and fix permission denied message when using the find on Linux or Unix-like system.
Find command basic syntax
The syntax is as follows:
find where-to-look criteria action
find /dir/to/search -name filetosearch
find /dir/to/search -name «*.c»
find /home/nixcraft/project/ -name «*.py» -print
In this example, find will search the /tmp directory for any files named “data*.txt” and display their pathnames:
Fig. 01: Find will show an error message for each directory on which you don’t have read permission.
How to hide or fix find command permission denied messages
In this above example, I do not have read permission for vmware-root and orbit-Debian-gdm directories. To to avoid this problem try the following syntax:
Sample outputs without permission denied spam from find command:
How does it works?
The 2>/dev/null at the end of the find command tells your shell to redirect the error messages (FD #2) to /dev/null, so you don’t have to see them on screen. Use /dev/null to to send any unwanted output from program/command. All data written on a /dev/null special file is discarded by the system. To redirect standard error to /dev/null and store file list to output.txt, type:
Exclude all “permission denied” messages from “find” command on Linux
There is one problem with the following command. It would filter out all error messages created by find command, not just the permission denied ones:
To avoid that try the following find command along with grep command on Linux or Unix-like systems:
In short you should use following syntax to skip “permission denied” errors messages when running find in Linux or Unix-based systems:
To store output to a file run:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Conclusion
You learned how to hide and fix permission denied messages when using the find command on your Linux, Unix, or macOS-based systems. Of course, we can also run the command as sudo when possible but avoid all this mess. Unfortunately, you will not get sudo or root access at all times. Hence, we talked about various methods here. For your ready references, sudo syntax would be as follows:
sudo find /dir/to/search -name «pattern» -action
sudo find / -name «jail.conf» -print
Please see find/bash command man page online or read it by typing the following man command:
man find
man bash
man zsh
man ksh
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Both errors and warning are thrown into stderr is there any way we can identify that the command has a warning in it and not the error ??
Apart from checking the return code !!
Just use sudo (assuming you’re not running it in a script)
Источник
Ошибка 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 для системных файлов, а также несколько путей ее решения. Как видите, все достаточно просто. Надеюсь, эта информация была полезной для вас.
Источник
Ubuntu says «bash: ./program Permission denied» [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed last month .
I am running Ubuntu on computer 1 and computer 2. I compiled a C++ program on computer 1, and I can execute it from the terminal using ./program_name . It runs fine.
However, when I try to do this on computer 2, it says: bash: ./program_name: permission denied
What’s wrong and what can I do about it?
3 Answers 3
chmod u+x program_name . Then execute it.
If that does not work, copy the program from the USB device to a native volume on the system. Then chmod u+x program_name on the local copy and execute that.
Unix and Unix-like systems generally will not execute a program unless it is marked with permission to execute. The way you copied the file from one system to another (or mounted an external volume) may have turned off execute permission (as a safety feature). The command chmod u+x name adds permission for the user that owns the file to execute it.
That command only changes the permissions associated with the file; it does not change the security controls associated with the entire volume. If it is security controls on the volume that are interfering with execution (for example, a noexec option may be specified for a volume in the Unix fstab file, which says not to allow execute permission for files on the volume), then you can remount the volume with options to allow execution. However, copying the file to a local volume may be a quicker and easier solution.
Источник