you need to be root to run this script linux что делать

Thread: «This script must be run as root»

Thread Tools
Display

«This script must be run as root»

I am trying to install a program, but when I enter «./install» in the terminal, I get the message:

«This script must be run as root»

you need to be root to run this script linux что делать. Смотреть фото you need to be root to run this script linux что делать. Смотреть картинку you need to be root to run this script linux что делать. Картинка про you need to be root to run this script linux что делать. Фото you need to be root to run this script linux что делать

Re: «This script must be run as root»

root is the privileged adiminstrator’s account in Linux. It’s usually needed for example to install software outside your home folder.

Be careful what you do and run as root. Only run programs and scripts from trustworthy sources that way as the can harm your system.

Re: «This script must be run as root»

I am trying to install Avira Antivir Personal for Linux, if that helps. I unzipped the gz package to the /tmp folder in the main drive, where Linux is installed. I renamed it to «antivir» since the original name was long and complicated.

Re: «This script must be run as root»

Re: «This script must be run as root»

I quote from the Terminal with translations in bold, since it is the German version:

Re: «This script must be run as root»

It’s quite annoying that such a simple task like installing a downloaded program is so complicated under Linux. I’m not a computer illiterate, i have been working with Windows computers extensively since 1996 and some would call me a power-user with some reason. But Linux beats me.

Re: «This script must be run as root»

you need to be root to run this script linux что делать. Смотреть фото you need to be root to run this script linux что делать. Смотреть картинку you need to be root to run this script linux что делать. Картинка про you need to be root to run this script linux что делать. Фото you need to be root to run this script linux что делать

Re: «This script must be run as root»

Please post back if you have any further questions or comments.

Источник

Как проверить, работает ли с правами root в bash script

Я пишу script, который требует прав на уровне корневого уровня, и я хочу сделать так, чтобы, если script не запущен как root, он просто перекликается с “Пожалуйста, запустите от имени пользователя root”. и выходы.

Здесь некоторый псевдокод для того, что я ищу:

Как я могу (чище и безопасно) справиться с этим? Спасибо!

А, просто для того, чтобы уточнить: часть (сделайте что-то) будет включать в себя запуск команд, которые сами по себе требуют root. Так что запуск его, как обычный пользователь, просто придумал бы ошибку. Это просто предназначено для чистого запуска script, для которого требуются корневые команды, без использования sudo внутри script, я просто ищу какой-то синтаксический сахар.

Было дано несколько ответов, но, по-видимому, лучшим способом является использование:

В bash script у вас есть несколько способов проверить, является ли текущий пользователь root.

Способ, которым я подхожу к этой проблеме, заключается в том, чтобы вставлять sudo в мои команды, когда он не запускается с правами root. Вот пример:

Таким образом моя команда запускается root при использовании суперпользователя или sudo при запуске обычного пользователя.

Если ваш script всегда должен быть запущен root, просто установите права соответственно ( 0500 ).

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

Существует простая проверка для пользователя, являющегося пользователем root.

Синтаксис [[ stuff ]] – это стандартный способ запуска проверки в bash.

Это также предполагает, что вы хотите выйти с 1, если вы терпите неудачу. Функция error – это некоторое чутье, которое устанавливает выходной текст в красный (не нужен, но довольно классный, если вы меня спрашиваете).

0- Прочитайте официальную документацию GNU Linux, есть много способов сделать это правильно.

1- убедитесь, что вы помещаете подпись оболочки, чтобы избежать ошибок в интерпретации:

Очень простой способ просто поставить:

Преимущество использования этого вместо id заключается в том, что вы можете проверить, не работает ли какой-либо пользователь, не являющийся пользователем root; например.

Я полагаю, что здесь мало что можно объяснить, потому что ответы с большим количеством голосов объясняют многое из этого.

Тем не менее, если есть что-то, чтобы объяснить дальше, не стесняйтесь комментировать, я сделаю все возможное, чтобы заполнить пробелы.

Оптимизированное bash решение для производительности и надежности

Объяснение

Почему я публикую это решение после стольких лет, когда ОП спросил

Что ж, если я правильно вижу, кажется, что выше отсутствует фрагмент кода.

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

Портативное решение POSIX solution

Заключение

попробуйте следующий код:

Один простой способ сделать скрипт доступным только для пользователя root – запустить скрипт со строкой:

Насколько я знаю, правильный способ проверить это:

Смотрите раздел “Тестирование на корень” здесь:

Проверьте, являетесь ли вы пользователем root, и выйдите из системы, если вы не:

Или в этом примере попытайтесь создать каталог в корневом расположении, а затем попытайтесь после повышения прав.

Проверьте, являетесь ли вы пользователем root и, если возможно, не повышать его:

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

Источник

How do I run a command as the system administrator (root)

I need to run a command with administrative privileges. Someone said I should run a command as root. How do I do this?

4 Answers 4

The main two commandline possibilities are:

Running a shell command as root

sudo (preferred when not running a graphical display)

This is the preferred method on most systems, including Ubuntu, Linux Mint, (arguably) Debian, and others. If you don’t know a separate root password, use this method.

Sudo requires that you type your own password. (The purpose is to limit the damage if you leave your keyboard unattended and unlocked, and also to ensure that you really wish to run that command and it wasn’t e.g. a typo.) It is often configured to not ask again for a few minutes so you can run several sudo commands in succession.

For more information, see the sudo website, or type man sudo on your system. Sudo is very configurable; for example it can be configured to let a certain user only execute certain commands as root. Read the sudoers man page for more information; use sudo visudo to edit the sudoers file.

The su command exists on most unix-like systems. It lets you run a command as another user, provided you know that user’s password. When run with no user specified, su will default to the root account.

To run multiple commands as root, it is more convenient to start an interactive shell.

Logging in as root

If there is a root password set and you are in possession of it, you can simply type root at the login prompt and enter the root password. Be very careful, and avoid running complex applications as root as they might do something you didn’t intend. Logging in directly as root is mainly useful in emergency situations, such as disk failures or when you’ve locked yourself out of your account.

Single User Mode

Single user mode, or run-level 1, also gives you root privileges. This is intended primarily for emergency maintenance situations where booting into a multi-user run-level is not possible. You can boot into single user mode by passing single or emergency on the kernel command line. Note that booting into single-user mode is not the same as booting the system normally and logging in as root. Rather, the system will only start the services defined for run-level 1. Typically, this is the smallest number of services required to have a usable system.

You can also get to single user mode by using the telinit command: telinit 1 ; however, this command requires you to already have gotten root privileges via some other method in order to run.

Other programs

Calife

Calife lets you run commands as another user by typing your own password, if authorized. It is similar to the much more widespread sudo (see above). Calife is more light-weight than sudo but also less configurable.

Op lets you run commands as another user, including root. This not a full-blown tool to run arbitrary commands: you type op followed by a mnemonic configured by the system administrator to run a specific command.

Super

Super lets you run commands as another user, including root. The command must have been allowed by the system administrator.

Running a graphical command as root

PolicyKit (preferred when using GNOME)

See man pkexec for more information.

KdeSu, KdeSudo (preferred when using KDE)

kdesu and kdesudo are graphical front-ends to su and sudo respectively. They allow you to run X Window programs as root with no hassle. They are part of KDE. Type

and enter the root password, or type

and enter your password (if authorized to run sudo ). If you check the “keep password” option in KdeSu, you will only have to type the root password once per login session.

Other programs

Ktsuss (“keep the su simple, stupid”) is a graphical version of su.

Beesu is a graphical front-end to the su command that has replaced Gksu in Red Hat-based operating systems. It has been developed mainly for RHEL and Fedora.

Obsolete methods

gksu and gksudo are graphical front-ends to su and sudo respectively. They allow you to run X Window programs as root with no hassle. They are part of Gnome. Type

and enter the root password, or type

and enter your password (if authorized to run sudo ).

gksu and gksudo are obsolete. They have been replaced by PolicyKit in GNOME, and many distributions (such as Ubuntu) no longer install them by default. You should not depend on them being available or working properly.

Manually via one of the shell-based methods

Use one of the methods in the «running a shell command as root section». You will need to ensure that neither the DISPLAY environment variable nor the XAUTHORITY environment get reset during the transition to root. This may require additional configuration of those methods that is outside the scope of this question.

Overall, this is a bad idea, mostly because graphical applications will read and write configuration files as root, and when you try to use those applications again as your normal user, those applications won’t have permission to read their own configurations.

Editing a file as root

In either case, you will be prompted for the root password. For more information, see the manual page.

Since the question was not Linux specific, here’s how you achieve the same goal in Solaris 9+ (or Trusted Solaris 8):

Solaris, since version 9, has included a suite of tools affectionately referred to as RBAC, or Role Based Access Control.

The gist of RBAC is that through the granting of Authorizations and Rights, to Users and/or Role, or the granting of Roles to Users, you can create incredibly fine grained models for who can run what with which privileges.

Essentially, you identify authorization in /etc/security/auth_attr, then grant them to users or roles in /etc/user_attr.

You define profiles in /etc/security/prof_attr. You then associate commands with those profiles in /etc/security/exec_attr, followed by assigning those profiles to users in the /etc/user_attr file.

Once those things are done, you actually run pfexec to execute the command with privileged or authorizations that are granted to that user for that command.

The nice thing about RBAC is that there are no additional privileges granted to the command itself, or the user, only to the combination of user + command. So it’s safer than making a binary +s, or just using sudo to make a user be able to execute pretty much anything. (I know that you can lock down sudo, but in my experience most people don’t)

Ben Rockwood has a great blog post on RBAC that can be read at Using RBAC on (Open)Solaris.

Источник

How to run a script with root authority in Linux

I have to develop a Web site written in CGI.

I would like to know how to run a script with root authority from CGI.

Now I would like to run this hello file as root; can anybody help me with this?

you need to be root to run this script linux что делать. Смотреть фото you need to be root to run this script linux что делать. Смотреть картинку you need to be root to run this script linux что делать. Картинка про you need to be root to run this script linux что делать. Фото you need to be root to run this script linux что делать

3 Answers 3

Then no matter who executes the program, it will execute as root. This works for native executables, but not for interpreted scripts. If «hello» has to be a script, then this won’t work for you.

Now, I have to say that in general, setuid root programs aren’t a great idea. Often you can create a special user to own the script, and give that user some limited privileges needed, and then make the script setuid to that user.

A much safer method of doing things as root from a web page is to disconnect the program execution from the web page. Instead, use Unix local sockets, named pipes, or a directory of queued jobs.

The directory is probably the easiest to handle. Set up a directory that your web page can write files into. When your page needs something done, write a file describing the job. Then you have a program running as root waiting for new jobs. It can run continuously if it needs fast response or it can run every minute or every few minutes using a crontab entry.

The normal method would be to have the executable file owned by the user you want to run it as, then set the SUID bit.

The method of using sudo usually requires user input for the password (there are ways around this but they’re hideously complex).

I suppose I don’t need to mention that setting the SUID bit is a very dangerous thing to do, yes? If there’s any other way to do what you want, you should use it.

One thing you may want to consider is to pose the question not in terms of the solution you need but in terms of the problem you want solved. Running as root is a solution and not necessarily a good one. Post what you’re trying to achieve rather than how, and we can help you out in a far less dangerous way.

Источник

How to run a specific program as root without a password prompt?

I need to run something as sudo without a password, so I used visudo and added this to my sudoers file:

Then I tried it out:

Why does it ask for a password? How can I run/use commands as root with a non-root user, without asking for a password?

you need to be root to run this script linux что делать. Смотреть фото you need to be root to run this script linux что делать. Смотреть картинку you need to be root to run this script linux что делать. Картинка про you need to be root to run this script linux что делать. Фото you need to be root to run this script linux что делать

15 Answers 15

you need to be root to run this script linux что делать. Смотреть фото you need to be root to run this script linux что делать. Смотреть картинку you need to be root to run this script linux что делать. Картинка про you need to be root to run this script linux что делать. Фото you need to be root to run this script linux что делать

WARNING: This answer has been deemed insecure. See comments below

Complete Solution: The following steps will help you achieve the desired output:

Create a new script file (replace create_dir.sh with your desired script name):

The script will be created in the user’s home directory

Add some commands that only a root or sudo user can execute like creating a folder at the root directory level:

Note: Don’t add sudo to these commands. Save and exit (using :wq! )

Assign execute permissions to it using:

Make changes so that this script doesn’t require a password.

Open the sudoers file:

Add the following line at the end:

Replace ahmad with whatever your username is. Also make sure this is the last line. Save and exit.

Now when running the command add sudo before it like:

This will run the commands inside the script file without asking for a password.

I think your syntax is wrong. At least I use the following which works for me:

If you want to avoid having to use sudo nor have to change the sudoers config file, you can use:

This will make the command run as root without the need of sudo.

you need to be root to run this script linux что делать. Смотреть фото you need to be root to run this script linux что делать. Смотреть картинку you need to be root to run this script linux что делать. Картинка про you need to be root to run this script linux что делать. Фото you need to be root to run this script linux что делать

If you have an distro like Manjaro, you must deal first with a file that overrides the definition of /etc/sudoers, you may delete it or work directly with that file to add your new configurations.

The ONLY way to see it is under root privilegies, you cannot list this directory without it, this file is Manjaro specific, you may found this configuration with other name, but in same directory.

In your file of choice, you can add the following line(s) to get your desired configuration(s):

Ignore authentication for a group

or Ignore authentication for a user

or Ignore authentication a executable for a specific user

QUICK NOTE: You are opening a door to use SUDO without authentication, that means you can run everything modifing everything from your system, use it with responsability.

Verify that sudo is not aliased. Run like this

For example a shell alias like this one:

may cause this behaviour.

You could also consider using gtk-sudo for a visual password prompt.

You should probably consider the idea that you shouldn’t be running things as root and that changing the system farther down the road so that you don’t need root permissions at all would be a better way to go.

you need to be root to run this script linux что делать. Смотреть фото you need to be root to run this script linux что делать. Смотреть картинку you need to be root to run this script linux что делать. Картинка про you need to be root to run this script linux что делать. Фото you need to be root to run this script linux что делать

This solved the issue for me (also tried some of the other answers, that might have helped):

Also something I doubted about (clarifying for future readers): You need to run your script as sudo. Type sudo when calling the script. Don’t use sudo for the command inside your script that actually needs root (changing keyboard backlight in my case). Perhaps that also works, but you don’t need to, and it seems like a better solution not to.

Alternately you can use python pudo package.

Below is the code snippet for using in python automation for running commands under root privilege:

Below is the cmd example for running commands under root privilege:

In the script sudoers which is inside /etc/ uncomment the line given below:

Create one file with any name inside /etc/sudoers.d/ directory and add the content as given in the maximum answers. Like for all users as root

This is the safest way to run the script with root permission.

Another possibility might be to install, configure, then use the super command to run your script as

Concretely, your program should be paranoically coded (so check all arguments and the environment and outside conditions before «acting», assuming a potentially hostile user), then you could use seteuid(2) and friends (see also setreuid(2)) carefully (see also capabilities(7) & credentials(7) & execve(2). )

You’ll use chmod u+s (read chmod(1)) when installing such a binary.

But be very careful.

Read many things about setuid, including Advanced Linux Programming, before coding such a thing.

Notice that a script, or any shebang-ed thing, cannot be setuid. But you could code (in C) a small setuid-binary wrapping it.

Be aware that on Linux, application code interact with the Linux kernel using syscalls(2). Most of them could fail, see errno(3). A lot of Linux applications (e.g. GNU bash, GNU make, GNU gdb, GNOME) are open source : you are allowed to download then study and contribute to their source code.

you need to be root to run this script linux что делать. Смотреть фото you need to be root to run this script linux что делать. Смотреть картинку you need to be root to run this script linux что делать. Картинка про you need to be root to run this script linux что делать. Фото you need to be root to run this script linux что делать

Ideally if you are customizing what commands can be run via sudo you should be making these changes in a separate file under /etc/sudoers.d/ instead of editing the sudoers file directly. You should also always use visudo to edit the file(s). You should NEVER grant NOPASSWD on ALL commands.

Insert your line granting permission: myuser ALL= NOPASSWD: /path/to/your/program

Then save and exit and visudo will warn you if you have any syntax errors.

If you find yourself creating lots of these sudoers.d files then perhaps you will want to create them named per user so they are easier to visualize. Keep in mind that the ordering of the FILE NAMES and of the RULES within the file is very important, the LAST one loaded wins, whether it is MORE or LESS permissive than the previous entries.

You can control the file name ordering by using a prefix of 00-99 or aa/bb/cc, though also keep in mind that if you have ANY files that don’t have numeric prefix, they will load after the numbered files, overriding the settings. This is because depending on your language settings the «lexical sorting» the shell uses sorts numbers first and then may interleave upper and lowercase when sorting in «ascending» order.

Try running printf ‘%s\n’ <<0..99>,,> | sort and printf ‘%s\n’ <<0..99>,,> | LANG=C sort to see whether your current language prints AaBbCc etc or ABC then abc to determine what the best «last» letter prefix to use would be.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *