Error you need to be root to run this script

Debian User Forums Must run as root, but I am already root Must run as root, but I am already root #1 Post by bertenvdb » 2015-01-21 16:29 I’m trying to install OpenNMS. I need to execute: uname -a: Linux kira 3.2.0-4-amd64 #1 SMP Debian 3.2.65-1+deb7u1 x86_64 GNU/Linux Re: Must run as root, but […]

Содержание

  1. Debian User Forums
  2. Must run as root, but I am already root
  3. Must run as root, but I am already root
  4. Re: Must run as root, but I am already root
  5. Re: Must run as root, but I am already root
  6. Re: Must run as root, but I am already root
  7. Re: Must run as root, but I am already root
  8. Re: Must run as root, but I am already root
  9. Re: Must run as root, but I am already root
  10. Re: Must run as root, but I am already root
  11. Re: Must run as root, but I am already root
  12. Re: Must run as root, but I am already root
  13. Re: Must run as root, but I am already root
  14. Thread: «This script must be run as root»
  15. «This script must be run as root»
  16. Re: «This script must be run as root»
  17. Re: «This script must be run as root»
  18. Re: «This script must be run as root»
  19. Re: «This script must be run as root»
  20. Re: «This script must be run as root»
  21. Re: «This script must be run as root»
  22. Re: «This script must be run as root»
  23. Amazon EC2 set-up failure #10
  24. Comments
  25. please help me #21
  26. Comments
  27. Footer
  28. Allow bash script to be run as root, but not sudo
  29. 8 Answers 8

Debian User Forums

Must run as root, but I am already root

Must run as root, but I am already root

#1 Post by bertenvdb » 2015-01-21 16:29

I’m trying to install OpenNMS. I need to execute:

uname -a: Linux kira 3.2.0-4-amd64 #1 SMP Debian 3.2.65-1+deb7u1 x86_64 GNU/Linux

Re: Must run as root, but I am already root

#2 Post by aicardi » 2015-01-21 17:03

Re: Must run as root, but I am already root

#3 Post by bertenvdb » 2015-01-21 17:09

Re: Must run as root, but I am already root

#4 Post by aicardi » 2015-01-21 17:33

Re: Must run as root, but I am already root

#5 Post by bertenvdb » 2015-01-21 17:48

Same result

I wonder what you searched for, I guess you found this on the OpenNMS mailinglist. I have been searching for 2 hours and didn’t come accross that yet.

Re: Must run as root, but I am already root

#6 Post by roseway » 2015-01-21 18:44

Re: Must run as root, but I am already root

#7 Post by dilberts_left_nut » 2015-01-21 18:50

Re: Must run as root, but I am already root

#8 Post by schnuller » 2015-01-21 21:35

Perhaps try
su —
too. Which usually should be done, i was told, but as i get away without doing it .

Looking at the error message i doubt that is the problem. I would do what was proposed above (ask the devs and/or look at the code, how it checks for user id).

Re: Must run as root, but I am already root

#9 Post by bertenvdb » 2015-01-22 01:25

I commented out the if. fi that checks for the user and the complete script executed without any errrors.
Running opennms itself gave the same error, same workaround also works. Everything seems to run as it should.

Will post a topic on OpenNMS as soon as I wake up in the morning.

Thanks for the support !

For reference or curious people:

Re: Must run as root, but I am already root

#10 Post by fsmithred » 2015-01-22 13:23

right before the test to see if the variable is being created correctly. It should print «myuser=xrootx»

FWIW, here’s another way to do the same test:

Re: Must run as root, but I am already root

#11 Post by impensj » 2016-07-05 17:24

The script expects the `id` command to return a line containing uid= but gets a line containing UID= instead.

Changing uid to UID in the script makes the script itself run without error. The script /usr/share/opennms/bin/opennms has a similar issue.

Источник

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»

How can I run it as root, and what does that mean ?

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 used the «sudo ./install» command and it asked me for my password, which I entered. Then I got the message «command not found», though I navigated exactly to the directory where it is inside.

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.

Yet I cannot get it to install.

Re: «This script must be run as root»

Do I have to enter «sudo ./install» exactly or something like «sudo cd /tmp/antivir/install» ?

Re: «This script must be run as root»

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

So first it asks me for permission, and when I enter «sudo» before the «./install» it suddenly does not find the command anymore ?!

But when I open the folder with the file manager, the install command/file is clearly there !

Re: «This script must be run as root»

Could it be that the program, though written for Linux, is not compatible with Ubuntu ?

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.

Last edited by Ali_Barba; June 15th, 2012 at 11:38 PM .

Re: «This script must be run as root»

Maybe somebody could download the program, too, and see whether it works ? The source is definitely trustworthy, one of the major antivirus companies. But maybe they made some mistake while writing the installer and it is corrupted ?

Re: «This script must be run as root»

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

Источник

Amazon EC2 set-up failure #10

First, before you have the script running, it’s necessary to install a software called docker on Amazon EC2 Ubuntu system, where docker is not pre-installed.
Second, it doesn’t work. After running the script, the server doesn’t show any api. It stopped at «starting Watchtower. OK», which is obviously not OK.

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

Thanks for the feedback, and sorry for your trouble.

When you run docker ps , does it show a shadowbox container? That’s the core of the service.

You can get the JSON needed to set up the Server Manager with

(Don’t share the output of that with anyone)

If you’d like to try again, the server installation on EC2 was tested using the image ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20180126 — ami-66506c1c (from Community AMIs)

What we did to get it working was:

Under «Configure Security Group», added a «Custom TCP Rule» and a «Custom UDP Rule». Set the Port Range for both to 1024-65535 , and Source to 0.0.0.0/0

  1. SSH in as user «unbuntu»
  2. curl -sS https://get.docker.com/ | sh
  3. sudo usermod -aG docker $USER

Reboot machine, then SSH again and run:
wget -qO- https://raw.githubusercontent.com/Jigsaw-Code/outline-server/master/src/server_manager/install_scripts/install_server.sh | bash
Ignore the error:

Because «ufw status» requires «sudo», we accidentally think that ufw is enabled when it is not by default

Could you try that and let us know if it still doesn’t work?

Источник

please help me #21

[!]::[Check Dependencies]:
[ ✔ ]::[Distro]: Kali
[ ✔ ]::[Release]: kali-rolling
[ ✔ ]::[Check User]: root
[ ✔ ]::[Terminal]: local
[ ✔ ]::[Internet Connection]: CONNECTED!
[ ✔ ]::[Medusa: Installation found!
[ ✔ ]::[Crunch]: Installation found!
[ ✔ ]::[Cewl]: Installation found!
[x]::[warning]:this script require fcrackzip installed to work

[!]::Please install fcrackzip to work properly

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

type apt-get install fcrackzip and install it

what a question . xD

Type: sudo apt-get install fcrackzip

type apt-get install fcrackzip and install it

Hey i have tried using the sudo command

root@kali:/home/vrj# apt-get install fcrackzip
Reading package lists. Done
Building dependency tree
Reading state information. Done
E: Unable to locate package fcrackzip

can u please help me resolve this issue

@imvrajshah Try
sudo apt-get update -y && sudo apt-get install fcrackzip -y

Maybe your repositories are a bit outdated.

[!]::[Check Dependencies]:
[ ✔ ]::[Distro]: Kali
[ ✔ ]::[Release]: kali-rolling
[ ✔ ]::[Check User]: root
[ ✔ ]::[Terminal]: local
[ ✔ ]::[Internet Connection]: CONNECTED!
[ ✔ ]::[Medusa: Installation found!
[ ✔ ]::[Crunch]: Installation found!
[ ✔ ]::[Cewl]: Installation found!
[x]::[warning]:this script require fcrackzip installed to work

[!]::Please install fcrackzip to work properly

If you are using ubuntu terminal on windows, Try using

i need help for the fcrackzip install

did you solve it out
.

[!]:: [ Check Dependencies]
[ ✔️ ]:: [check user]
[ ✔ ]::[Distro]: Kali
[ ✔ ]::[Release]: kali-rolling
[x]:: [not root]: you need to be [root] to run this script.

what Should i do

can anyone help me proxy is not working it says ip is on instagram jail

© 2023 GitHub, Inc.

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.

Источник

Allow bash script to be run as root, but not sudo

I’m new here and new to bash/linux.

My teacher gave me an assignment to allow a script to be run only when you’re «really» root and not when you’re using sudo. After two hours of searching and trying I’m beginning to think he’s trolling me. Allowing only root is easy, but how do I exclude users that run it with sudo?

This is what I have:

8 Answers 8

The only way I could think of is to check one of the SUDO_* environment variables set by sudo:

Notice that of course this solution is not future proof as you cannot stop anyone from setting a variable before running the script:

Another option would be to check if the grandparent process name is «sudo»:

The information about which user logged in is available in /proc/self/loginuid . EDIT due to comments: That file does not seem to exist on all systems. I tested and it is available on Centos 6, Fedora 32, Fedora 33 and Ubuntu 20.04, all in standard x86_64 setups. If we login as our user and than use sudo or su to become root, this will not change /proc/self/loginuid and it will be some non-zero value. If we directly log in as root, then cat /proc/self/loginuid will return 0 . Note that this file can NOT be modified, even root cannot do this. EDIT due to Stéphane Chazelas’ comment: Root can overwrite this file using echo 0 > /proc/self/loginuid . However, this can be prevented by setting auditctl —loginuid-immutable .

The script to check for real root (if auditctl —loginuid-immutable is set) could look like

Источник

  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Official Flavours Support
  • General Help
  • [ubuntu] «This script must be run as root»

  1. «This script must be run as root»

    Hello.

    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»

    How can I run it as root, and what does that mean ?


  2. Re: «This script must be run as root»

    Use
    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.


  3. Re: «This script must be run as root»

    Thank you.

    I used the «sudo ./install» command and it asked me for my password, which I entered. Then I got the message «command not found», though I navigated exactly to the directory where it is inside.

    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.

    Yet I cannot get it to install.


  4. Re: «This script must be run as root»

    Do I have to enter «sudo ./install» exactly or something like «sudo cd /tmp/antivir/install» ?


  5. Re: «This script must be run as root»

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

    axel@axel-ESPRIMO-P:/tmp/antivir$ ./install
    bash: ./install: Keine Berechtigung (No permission)
    axel@axel-ESPRIMO-P:/tmp/antivir$ sudo ./install
    sudo: ./install: Befehl nicht gefunden (Command not found)

    So first it asks me for permission, and when I enter «sudo» before the «./install» it suddenly does not find the command anymore ?!

    But when I open the folder with the file manager, the install command/file is clearly there !


  6. Re: «This script must be run as root»

    Could it be that the program, though written for Linux, is not compatible with Ubuntu ?

    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.

    Last edited by Ali_Barba; June 15th, 2012 at 11:38 PM.


  7. Re: «This script must be run as root»

    Maybe somebody could download the program, too, and see whether it works ? The source is definitely trustworthy, one of the major antivirus companies. But maybe they made some mistake while writing the installer and it is corrupted ?


  8. Re: «This script must be run as root»

    Have a look here: https://help.ubuntu.com/community/RootSudo

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


  9. Re: «This script must be run as root»

    Quote Originally Posted by lisati
    View Post

    Yeah, I got the sudo thing now, but it still will not install.

    See the quote from the Terminal above.


  10. Re: «This script must be run as root»

    Could you show the output of an ‘ls’ in the install directory?


Bookmarks

Bookmarks


Posting Permissions

bertenvdb

Posts: 6
Joined: 2015-01-21 15:25
Location: Belgium

Must run as root, but I am already root

#1

Post

by bertenvdb » 2015-01-21 16:29

Hi,

I’m trying to install OpenNMS. I need to execute:

Code: Select all

sudo $OPENNMS_HOME/bin/install -dis

But wether I do the above using sudo or logged as root, I get:

Code: Select all

Error: you must run this script as root, not 'UID=0(root'

I just did a fresh install, and I remember not getting sudo adduser to work. I then used visudo and did this:

Code: Select all

# User privilege specification
root      ALL=(ALL:ALL) ALL
berten    ALL=(ALL:ALL) ALL

uname -a: Linux kira 3.2.0-4-amd64 #1 SMP Debian 3.2.65-1+deb7u1 x86_64 GNU/Linux



bertenvdb

Posts: 6
Joined: 2015-01-21 15:25
Location: Belgium

Re: Must run as root, but I am already root

#3

Post

by bertenvdb » 2015-01-21 17:09

Code: Select all

berten@kira:/usr/share/opennms$ sudo $OPENNMS_HOME/bin/install -dis
Error: you must run this script as root, not 'UID=0(root'
berten@kira:/usr/share/opennms$ su root
Wachtwoord: 
root@kira:/usr/share/opennms# $OPENNMS_HOME/bin/install -dis
Error: you must run this script as root, not 'UID=0(root'






schnuller

Posts: 386
Joined: 2014-11-25 05:05

Re: Must run as root, but I am already root

#8

Post

by schnuller » 2015-01-21 21:35

Perhaps try
su —
too. Which usually should be done, i was told, but as i get away without doing it …

Looking at the error message i doubt that is the problem. I would do what was proposed above (ask the devs and/or look at the code, how it checks for user id).


bertenvdb

Posts: 6
Joined: 2015-01-21 15:25
Location: Belgium

Re: Must run as root, but I am already root

#9

Post

by bertenvdb » 2015-01-22 01:25

schnuller wrote:
Perhaps try su —

I tried this, but no dice.

roseway wrote:Have you tried examining the script? Search for the error message and see what triggers it. It’s probably just a bug in the script, and you could edit it to bypass the root check.

I commented out the if…fi that checks for the user and the complete script executed without any errrors.
Running opennms itself gave the same error, same workaround also works. Everything seems to run as it should.

Will post a topic on OpenNMS as soon as I wake up in the morning.

Thanks for the support ! :wink:

For reference or curious people:

Code: Select all

#!/bin/sh -

OPENNMS_HOME="/usr/share/opennms"
OPENNMS_BINDIR="/usr/share/opennms/bin"

RUNAS="root"

ULIMIT=`which ulimit 2>/dev/null`
if [ -n $ULIMIT ]; then
        for SIZE in 1024 2048 4096 8192 unlimited; do
                ulimit -n "$SIZE" >/dev/null 2>&1
                if [ $? -gt 0 ]; then
                        break
                fi
        done
fi

myuser="`id | sed -e 's/uid=[0-9][0-9]*(//' -e 's/).*//'`"
#if [ x"$myuser" = x"$RUNAS" ]; then
#       true # all is well
#else
#       echo "Error: you must run this script as $RUNAS, not '$myuser'" >&2
#       exit 4 # According to LSB: 4 - user had insufficient privileges
#fi

if [ -f "$OPENNMS_HOME/etc/opennms.conf" ]; then
        . "$OPENNMS_HOME/etc/opennms.conf"
fi

exec "$OPENNMS_BINDIR"/runjava -r -- 
        $ADDITIONAL_MANAGER_OPTIONS 
        -Dopennms.home="$OPENNMS_HOME" 
        -Dlog4j.configurationFile="$OPENNMS_HOME"/etc/log4j2-tools.xml 
        -cp "$OPENNMS_HOME/lib/opennms_bootstrap.jar" 
        org.opennms.bootstrap.InstallerBootstrap 
        "$@"


fsmithred

Posts: 1873
Joined: 2008-01-02 14:52

Re: Must run as root, but I am already root

#10

Post

by fsmithred » 2015-01-22 13:23

That’s weird. It looks like it should work. It does work on command line, and it does work if I put just that test in a script by itself. Is there something odd about the output of the id command? You could add

right before the test to see if the variable is being created correctly. It should print «myuser=xrootx»

FWIW, here’s another way to do the same test:

Code: Select all

# Check that user is root.
[[ $(id -u) -eq 0 ]] || { echo -e "nt You need to be root!n" ; exit 1 ; }


impensj

Posts: 1
Joined: 2016-07-05 16:58

Re: Must run as root, but I am already root

#11

Post

by impensj » 2016-07-05 17:24

The script expects the `id` command to return a line containing uid= but gets a line containing UID= instead.

Changing uid to UID in the script makes the script itself run without error. The script /usr/share/opennms/bin/opennms has a similar issue.


Thread: «This script must be run as root»

Thread Tools
Display

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 что делать

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 что делать

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 что делать

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 что делать

15 Answers 15

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 что делать

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 что делать

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 что делать

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 ‘%sn’ <<0..99>,,> | sort and printf ‘%sn’ <<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.

Источник

Понравилась статья? Поделить с друзьями:
  • Error you must define at least one round robin archive
  • Error you must be logged in as an administrator when installing this program
  • Error you have missing monobehaviours on your gameobjects
  • Error you cannot perform this operation unless you are root
  • Error you can find them in the drivers folder of flashtool