- Check if a user is root
- 6 Answers 6
- How to check if running as root in a bash script
- 18 Answers 18
- What is the best way for checking if the user of a script has root-like privileges?
- 10 Answers 10
- How do you check if you are root in Linux?
- How do I know if I have root access?
- How do I know if user is root or sudo?
- How do I run as root in Linux?
- Does factory reset remove root?
- Can my phone be rooted without me knowing?
- How do I know if a user has sudo access?
- Is Sudo password same as root?
- How do I login as Sudo?
- How do I run sudo?
- How do I find my root password in Linux?
- How do I run as administrator root?
- Is rooting illegal?
- Can I Unroot my phone after rooting?
- Can a rooted phone be updated?
- Как проверить, работает ли с правами root в bash script
- Оптимизированное bash решение для производительности и надежности
- Объяснение
- Почему я публикую это решение после стольких лет, когда ОП спросил
- Портативное решение POSIX solution
- Заключение
Check if a user is root
How can i verify if a user is root in a PHP script ? What is the command ? I tried something like that :
but the su command can not receive password.
Note that the machine is isolated from internet so I can run PHP as root if needed.
EDIT: I don’t want to know if the current user who run the script is root or not. I have a list of users in my PHP script and I want to know for each login if he has root privileges.
6 Answers 6
First, ask yourself what exactly defines a login «having root privileges». AFAICT there are 2 basic solutions.
The old-school way, where sysadmins create multiple accounts with uid 0, which I — and I’m certainly not alone in this — consider to be a nightmare. In this scenario you could check all users in your list using posix_getpwnam and see if their uid matches 0.
The following code snippet does just that, $privileged will contain the users with root privileges :
The other (and imho only sane) way to do this is to add all users with root/administrative privileges to a specific group (wheel or admin are already used in different Linux distributions, find out which one works for you). This scenario is even simpler, since you can use posix_getgrnam to fetch all members in a specific group.
The following code snippet will match an array of logins you provide, and see who’s a member with specific privileges, again $privileged will contain the result (ie. the users in your list that are a member of the group you specified) :
Источник
How to check if running as root in a bash script
I’m writing a script that requires root level permissions, and I want to make it so that if the script is not run as root, it simply echoes «Please run as root.» and exits.
Here’s some pseudocode for what I’m looking for:
How could I best (cleanly and securely) accomplish this? Thanks!
Ah, just to clarify: the (do stuff) part would involve running commands that in-and-of themselves require root. So running it as a normal user would just come up with an error. This is just meant to cleanly run a script that requires root commands, without using sudo inside the script, I’m just looking for some syntactic sugar.
18 Answers 18
The $EUID environment variable holds the current user’s UID. Root’s UID is 0. Use something like this in your script:
Note: If you get 2: [: Illegal number: check if you have #!/bin/sh at the top and change it to #!/bin/bash .
A few answers have been given, but it appears that the best method is to use is:
- id -u
- If run as root, will return an id of 0.
This appears to be more reliable than the other methods, and it seems that it return an id of 0 even if the script is run through sudo .
In a bash script, you have several ways to check if the running user is root.
As a warning, do not check if a user is root by using the root username. Nothing guarantees that the user with ID 0 is called root . It’s a very strong convention that is broadly followed but anybody could rename the superuser another name.
I think the best way when using bash is to use $EUID , from the man page:
This is a better way than $UID which could be changed and not reflect the real user running the script.
A way I approach that kind of problem is by injecting sudo in my commands when not run as root. Here is an example:
This ways my command is run by root when using the superuser or by sudo when run by a regular user.
If your script is always to be run by root, simply set the rights accordingly ( 0500 ).
Источник
What is the best way for checking if the user of a script has root-like privileges?
I have a Python script that will be doing a lot of things that would require root-level privileges, such as moving files in /etc, installing with apt-get, and so on. I currently have:
Is this the best way to do the check? Are there other best practices?
10 Answers 10
os.geteuid gets the effective user id, which is exactly what you want, so I can’t think of any better way to perform such a check. The one bit that’s uncertain is that «root-like’ in the title: your code checks for exactly root , no «like» about it, and indeed I wouldn’t know what «root-like but not root» would mean — so, if you mean something different than «exactly root», perhaps you can clarify, thanks!
Under the «Easier to Ask Forgiveness than Permission» principle:
If you are concerned about the non-portability of os.geteuid() you probably shouldn’t be mucking with /etc anyway.
You can prompt the user for sudo access:
The sudo -v switch update the user’s cached credentials (see man sudo ).
If you really want your code to be robust across a wide variety of Linux configurations I’d suggest that you consider the corner cases where someone may be using SELinux, or filesystem ACLs, or the «capabilities» features that have been in the Linux kernel since v. 2.2 or so. Your process might be running under some wrapper that has used SELinux, or some Linux capabilities library, such as libcap2 libcap-ng, or fscaps or elfcap via something more exotic like Niels Provos’ wonderful and sadly under-appreciated systrace system.
All of these are ways that you code might be running as non-root and yet your process might have been delegated the necessary access to perform its work without EUID==0.
So I’d suggest that you consider writing your code more Pythonically, by wrapping operations that may fail due to permissions or other issues with exception handling code. If you’re shelling out to perform various operations (e.g. using the subprocess module) you might offer to prefix all such calls with sudo (as a command line, environment, or .rc file option, for example). If it’s being run interactively you can offer to re-execute any commands that raise permissions related exceptions using sudo (optionally only if you find sudo on the os.environ[‘PATH’]).
Overall it’s true that most Linux and UNIX systems still have most of their administration done by a ‘root’ privileged user. However, it’s old school and we, as programmers, should try to support newer models. Trying your operations and letting the exception handling do its job allows your code to work under any system that transparently permits the operations you need, and being aware of and ready to use sudo is a nice touch (as it is, by far, the most widespread tool for controlled delegation of system privileges).
Источник
How do you check if you are root in Linux?
If you are able to use sudo to run any command (for example passwd to change the root password), you definitely have root access. A UID of 0 (zero) means “root”, always.
How do I know if I have root access?
Install a root checker app from Google Play. Open it and follow the instructions, and it will tell you if your phone is rooted or not. Go old school and use a terminal. Any terminal app from the Play Store will work, and all you need to do is open it and enter the word “su” (without the quotes) and hit return.
How do I know if user is root or sudo?
Executive summary: “root” is the actual name of the administrator account. “sudo” is a command which allows ordinary users to perform administrative tasks. “Sudo” is not a user.
How do I run as root in Linux?
To get root access, you can use one of a variety of methods:
- Run sudo and type in your login password, if prompted, to run only that instance of the command as root. …
- Run sudo -i . …
- Use the su (substitute user) command to get a root shell. …
- Run sudo -s .
Does factory reset remove root?
No, root won’t be removed by factory reset. If you want to remove it, then you should flash stock ROM; or delete the su binary from the system/bin and system/xbin and then delete the Superuser app from the system/app .
Can my phone be rooted without me knowing?
No. Someone or an app has to do this. If you are installing apps outside the usual Google store, some will root your phone. … Think back over your apps from the Google Play store.
How do I know if a user has sudo access?
To know whether a particular user is having sudo access or not, we can use -l and -U options together. For example, If the user has sudo access, it will print the level of sudo access for that particular user. If the user don’t have sudo access, it will print that user is not allowed to run sudo on localhost.
Is Sudo password same as root?
The primary difference between the two is the password they require: while ‘sudo’ requires current user’s password, ‘su’ requires you to enter the root user password. … Given that ‘sudo’ requires users to enter their own password, you don’t need to share the root password will all the users in the first place.
How do I login as Sudo?
How to become superuser on Ubuntu Linux
- Open a terminal Window. Press Ctrl + Alt + T to open the terminal on Ubuntu.
- To become root user type: sudo -i. sudo -s.
- When promoted provide your password.
- After successful login, the $ prompt would change to # to indicate that you logged in as root user on Ubuntu.
How do I run sudo?
To see the commands that are available for you to run with sudo, use sudo -l . To run a command as the root user, use sudo command .
…
Using sudo.
Commands | Meaning |
---|---|
sudo -l | List available commands. |
sudo command | Run command as root. |
sudo -u root command | Run command as root. |
sudo -u user command | Run command as user. |
How do I find my root password in Linux?
- Step 1: Open a Terminal Window. Right-click the desktop, then left-click Open in terminal. Alternately, you can click Menu > Applications > Accessories > Terminal.
- Step 2: Change Your Root Password. In the terminal window, type the following: sudo passwd root.
How do I run as administrator root?
You should run cmd.exe as administrator. Follow the following steps: Click Start, click All Programs, and then click Accessories. Right-click Command prompt, and then click Run as administrator.
Is rooting illegal?
Some manufacturers allow official rooting of Android devices on the one hand. These are Nexus and Google that can be officially rooted with the permission of a manufacturer. Thus it’s not illegal. But on the other hand, a vast majority of Android manufacturers don’t approve rooting at all.
Can I Unroot my phone after rooting?
Any Phone that has only been rooted: If all you’ve done is root your phone, and stuck with your phone’s default version of Android, unrooting should (hopefully) be easy. You can unroot your phone using an option in the SuperSU app, which will remove root and replace Android’s stock recovery.
Can a rooted phone be updated?
The answer is simple… you can’t update a rooted phone using the standard method. Instead, you have to use either the Samsung Kies or Mobile Odin Pro to flash the new Android version, but you lose root access. Once that’s done, you’ll have to reroot your device.
Источник
Как проверить, работает ли с правами root в bash script
Я пишу script, который требует прав на уровне корневого уровня, и я хочу сделать так, чтобы, если script не запущен как root, он просто перекликается с “Пожалуйста, запустите от имени пользователя root”. и выходы.
Здесь некоторый псевдокод для того, что я ищу:
Как я могу (чище и безопасно) справиться с этим? Спасибо!
А, просто для того, чтобы уточнить: часть (сделайте что-то) будет включать в себя запуск команд, которые сами по себе требуют root. Так что запуск его, как обычный пользователь, просто придумал бы ошибку. Это просто предназначено для чистого запуска script, для которого требуются корневые команды, без использования sudo внутри script, я просто ищу какой-то синтаксический сахар.
Было дано несколько ответов, но, по-видимому, лучшим способом является использование:
- id -u
- Если запустить с правами root, вернет идентификатор 0.
Это кажется более надежным, чем другие методы, и кажется, что он возвращает id из 0, даже если script выполняется через sudo .
Переменная среды $ EUID содержит текущий UID пользователя. Root UID равен 0. Используйте что-то вроде этого в вашем скрипте:
Примечание: Если вы получаете 2: [: Illegal number: проверьте, есть ли у вас #!/bin/sh вверху и измените его на #!/bin/bash .
В bash script у вас есть несколько способов проверить, является ли текущий пользователь root.
Как предупреждение , не проверяйте, является ли пользователь root, используя имя пользователя root . Ничто не гарантирует, что пользователь с ID 0 называется root . Это очень сильное соглашение, которое широко применяется, но любой может переименовать суперпользователя в другое имя.
Я думаю, что лучший способ использования bash – использовать $EUID , с man-страницы:
Это лучший способ, чем $UID , который может быть изменен и не отражает реального пользователя, запускающего script.
Способ, которым я подхожу к этой проблеме, заключается в том, чтобы вставлять sudo в мои команды, когда он не запускается с правами root. Вот пример:
Таким образом моя команда запускается root при использовании суперпользователя или sudo при запуске обычного пользователя.
Если ваш script всегда должен быть запущен root, просто установите права соответственно ( 0500 ).
Как упоминает @wrikken в своих комментариях, id -u – это гораздо лучшая проверка для root.
Кроме того, при правильном использовании sudo вы можете проверить script и посмотреть, работает ли он с правами root. Если нет, попросите его вспомнить через sudo , а затем запустите с правами root.
В зависимости от того, что делает script, другой может быть настройка записи sudo для любых специализированных команд, которые могут понадобиться script.
Существует простая проверка для пользователя, являющегося пользователем root.
Синтаксис [[ stuff ]] – это стандартный способ запуска проверки в bash.
Это также предполагает, что вы хотите выйти с 1, если вы терпите неудачу. Функция error – это некоторое чутье, которое устанавливает выходной текст в красный (не нужен, но довольно классный, если вы меня спрашиваете).
0- Прочитайте официальную документацию GNU Linux, есть много способов сделать это правильно.
1- убедитесь, что вы помещаете подпись оболочки, чтобы избежать ошибок в интерпретации:
2- это мой script
Очень простой способ просто поставить:
Преимущество использования этого вместо id заключается в том, что вы можете проверить, не работает ли какой-либо пользователь, не являющийся пользователем root; например.
Если script действительно требует доступа к корню, тогда его права на файлы должны отражать это. Наличие корневого script исполняемого пользователями, не являющимся пользователем root, будет красным. Я рекомендую вам не контролировать доступ с помощью проверки if .
В этом ответе, чтобы было ясно, я предполагаю, что читатель может читать сценарии оболочки bash и POSIX, такие как dash .
Я полагаю, что здесь мало что можно объяснить, потому что ответы с большим количеством голосов объясняют многое из этого.
Тем не менее, если есть что-то, чтобы объяснить дальше, не стесняйтесь комментировать, я сделаю все возможное, чтобы заполнить пробелы.
Оптимизированное bash решение для производительности и надежности
Объяснение
Так как чтение переменной bash стандарта во много раз быстрее, эффективный идентификатор пользователя, чем выполнение команды id -u для POSIX -ly, находит пользователя ID, это решение объединяет оба в красиво упакованную функцию. Если и только если $EUID по какой-либо причине недоступен, команда id -u будет выполнена, гарантируя, что мы получим правильное возвращаемое значение независимо от обстоятельств.
Почему я публикую это решение после стольких лет, когда ОП спросил
Что ж, если я правильно вижу, кажется, что выше отсутствует фрагмент кода.
Видите ли, есть много переменных, которые необходимо учитывать, и одна из них сочетает в себе производительность и надежность.
Портативное решение POSIX solution
Заключение
Как бы вам это ни нравилось, среда Unix/Linux очень разнообразна. Это означает, что есть люди, которым так нравится bash , что они даже не думают о переносимости (POSIX оболочки). Другие, как я, предпочитают POSIX оболочки. В настоящее время это вопрос личного выбора и потребностей.
попробуйте следующий код:
Один простой способ сделать скрипт доступным только для пользователя root – запустить скрипт со строкой:
Насколько я знаю, правильный способ проверить это:
Смотрите раздел “Тестирование на корень” здесь:
id -u намного лучше, чем whoami , поскольку некоторые системы, такие как android, могут не предоставлять слово root.
Проверьте, являетесь ли вы пользователем root, и выйдите из системы, если вы не:
Или в этом примере попытайтесь создать каталог в корневом расположении, а затем попытайтесь после повышения прав.
Проверьте, являетесь ли вы пользователем root и, если возможно, не повышать его:
Примечание редактора: если вам не нужны двойные скобки, используйте одинарные для переносимости кода.
Источник