Запуск скрипта от имени администратора linux

Execute a shell script in current shell with sudo permission

To execute a shell script in current shell, we need to use a period . or a source command. But why does it not work with a sudo permission? I have a script with execute permission called setup.sh . When I use a period, I get this:

$ sudo . ./setup.sh sudo: .: command not found 

The source command also produces a similar error. Am I missing out something? What should I do to run the script with sudo permission in the same/current shell?

Despite the excellent answers, I think the problem is almost just a typo. Delete the first period that is by itself.

@beroe you are in error. The problem is not a typo. If setup.sh does not have execute privileges, then you must explicitly interpret it with bash. This can be done as bash setup.sh or source setup.sh or . setup.sh . However, because the latter 2 are bash built-ins, only the 1st form can be used with sudo which requires an executable. You can use sudo which bash and sudo which source and sudo which . to see what sudo will find.

@BrunoBronosky it looked (looks) to me like they are trying to run the first lone dot as a command. Since this specifies the current working directory, which is not a command, it throws that error. If they put ./setup.sh it would be a different story.

@beroe A lone dot is a shell command — specifically, it’s a shell builtin that’s equivalent to the source command (also a builtin).

10 Answers 10

I’m not sure if this breaks any rules but

What you are trying to do is impossible; your current shell is running under your regular user ID (i.e. without root the access sudo would give you), and there is no way to grant it root access. What sudo does is create a new *sub*process that runs as root. The subprocess could be just a regular program (e.g. sudo cp . runs the cp program in a root process) or it could be a root subshell, but it cannot be the current shell.

(It’s actually even more impossible than that, because the sudo command itself is executed as a subprocess of the current shell — meaning that in a sense it’s already too late for it to do anything in the «current shell», because that’s not where it executes.)

Читайте также:  Install kali linux nethunter

I’m not sure why this is the accepted answer when @JaseC’s answer below seems to work for me. sudo bash myscript.sh does exactly what I was looking for, and what the OP seemed to be asking for.

@dalesikkema: sudo bash myscript.sh will run the script in a subshell, rather than the current shell. If that works in your situation, great — but this particular question is about running the script as root in the current shell.

The entire premise of ambiguous because of the inaccurate word choice. «For executing a shell script in current shell, we need to use a period» No, that period doesn’t execute, it sources, inserts, reads, or interprets. Execution implies a disparate PID. So, we are unclear if/why they might care about the PID of their current shell.

I think you are confused about the difference between sourcing and executing a script.

Executing a script means creating a new process, and running the program. The program can be a shell script, or any other type of program. As it is a sub process, any environmental variables changed in the program will not affect the shell.

Sourcing a script can only be used with a bash script (if you are running bash). It effectively types the commands in as if you did them. This is useful as it lets a script change environmental variables in the shell.

Running a script is simple, you just type in the path to the script. . is the current directory. So ./script.sh will execute the file script.sh in the current directory. If the command is a single file (eg script.sh ), it will check all the folders in the PATH variable to find the script. Note that the current directory isn’t in PATH, so you can’t execute a file script.sh in the current directory by running script.sh , you need to run ./script.sh (unless the current directory is in the PATH, eg you can run ls while in the /bin dir).

Sourcing a script doesn’t use the PATH, and just searches for the path. Note that source isn’t a program — otherwise it wouldn’t be able to change environmental variables in the current shell. It is actually a bash built in command. Search /bin and /usr/bin — you won’t find a source program there. So to source a file script.sh in the current directory, you just use source script.sh .

How does sudo interact with this? Well sudo takes a program, and executes it as root. Eg sudo ./script.sh executes script.sh in a sub process but running as root.

What does sudo source ./script.sh do however? Remember source isn’t a program (rather a shell builtin)? Sudo expects a program name though, so it searches for a program named source . It doesn’t find one, and so fails. It isn’t possible to source a file running as root, without creating a new subprocess, as you cannot change the runner of a program (in this case, bash) after it has started.

I’m not sure what you actually wanted, but hopefully this will clear it up for you.

Here is a concrete example. Make the file script.sh in your current directory with the contents:

#!/bin/bash export NEW_VAR="hello" whoami echo "Some text" 

Make it executable with chmod +x script.sh .

Читайте также:  Opera adobe flash linux

Now observe what happens with bash:

> ./script.sh david Some text > echo $NEW_VAR > sudo ./script.sh root Some text > echo $NEW_VAR > source script.sh david Some text > echo $NEW_VAR hello > sudo source script.sh sudo: source: command not found 

Источник

unixforum.org

Можно, конечно, и так — использовать sudo в самом скрипте, а можно и просто весь скрипт запустить командой вида «sudo script.sh».

Re: запуск скрипта от имени root

Сообщение safronowmax » 13.12.2012 22:33

Проблема в том, что данный скрипт будет отдавать данные в zabbix, и такой вариант не подойдет, попробовал в /etc/sudoerc прописать пользователя с правами root: vbox ALL=(ALL) ALL, но что-то все равно не работает

Bizdelnick Модератор Сообщения: 20387 Статус: nulla salus bello ОС: Debian GNU/Linux

Re: запуск скрипта от имени root

Сообщение Bizdelnick » 13.12.2012 23:43

vbox localhost = NOPASSWD: /usr/local/bin/myscript
в консоли
вку́пе (с чем-либо)
в общем
вообще
в течение (часа)
новичок
нюанс
по умолчанию
приемлемо
проблема
пробовать
трафик

Re: запуск скрипта от имени root

Сообщение Vascom » 14.12.2012 09:06

allez Сообщения: 2223 Статус: Не очень злой админ 🙂 ОС: SuSE, CentOS, FreeBSD, Windows

Re: запуск скрипта от имени root

Сообщение allez » 14.12.2012 12:23

eddy Сообщения: 3321 Статус: Красный глаз тролля ОС: ArchLinux Контактная информация:

Re: запуск скрипта от имени root

Сообщение eddy » 14.12.2012 13:54

Re: запуск скрипта от имени root

Сообщение trendix » 14.12.2012 20:52

Простите несведущего!
А нельзя изменить пользователя у этого скрипта?
А нельзя ли его запускать при старте ОС?

drBatty Сообщения: 8735 Статус: GPG ID: 4DFBD1D6 дом горит, козёл не видит. ОС: Slackware-current Контактная информация:

Re: запуск скрипта от имени root

Сообщение drBatty » 17.12.2012 11:42

Re: запуск скрипта от имени root

Сообщение liaonau » 17.12.2012 18:27

И вызван когнитивный диссонанс ☺. Нет универсального ответа: в Gentoo, например, ответ /etc/local.d/*.start

drBatty Сообщения: 8735 Статус: GPG ID: 4DFBD1D6 дом горит, козёл не видит. ОС: Slackware-current Контактная информация:

Re: запуск скрипта от имени root

Сообщение drBatty » 18.12.2012 11:23

у гентушника? о_О
может вам рассказать, где у вас компилятор, и как называется?
По теме: используйте /etc/conf.d/local.start, если у вас гента, и вы этого не знаете.

/etc/rc.local это универсальный ответ для большинства дистрибутивов, но он не Ъ. Например в слаке такого тоже делать не нужно, там /etc/rc.d/rc.local (только все слакварщики, в отличие от гентушников, в курсе)

Re: запуск скрипта от имени root

Сообщение Kopilov » 18.12.2012 18:52

Откуда такая информация?
В моей рабочей генте (ветка stable, обновлял месяц назад) такого файла нет, и я не сталкивался с предложением его создать.
А каталог

This directory should contain programs or scripts which are to be run when the local service is started or stopped. If a file in this directory is executable and it has a .start extension, it will be run when the local service is started. If a file is executable and it has a .stop extension, it will be run when the local service is stopped. All files are processed in lexical order.

drBatty Сообщения: 8735 Статус: GPG ID: 4DFBD1D6 дом горит, козёл не видит. ОС: Slackware-current Контактная информация:

Читайте также:  Setup linux and windows

Re: запуск скрипта от имени root

Сообщение drBatty » 19.12.2012 16:31

Poor Fred Сообщения: 1575 Статус: Pygoscelis papua ОС: Gentoo Linux, FreeBSD

Re: запуск скрипта от имени root

Сообщение Poor Fred » 19.12.2012 16:39

Проблема в том, что данный скрипт будет отдавать данные в zabbix, и такой вариант не подойдет, попробовал в /etc/sudoerc прописать пользователя с правами root: vbox ALL=(ALL) ALL, но что-то все равно не работает

Как будет отдавать? Может быть, наоборот, zabbix-agent будет сам забирать? Тогда и пользователь должен быть другой. zabbix, как ни странно.

Re: запуск скрипта от имени root

Сообщение Kopilov » 19.12.2012 17:43

Если в Slackware документация не теряет актуальности за шесть лет — я буду поражён её консервативностью.

Re: запуск скрипта от имени root

Сообщение liaonau » 19.12.2012 19:22

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

drBatty Сообщения: 8735 Статус: GPG ID: 4DFBD1D6 дом горит, козёл не видит. ОС: Slackware-current Контактная информация:

Re: запуск скрипта от имени root

Сообщение drBatty » 20.12.2012 11:37

Если в Slackware документация не теряет актуальности за шесть лет — я буду поражён её консервативностью.

смотря на что. Когда KDE3 сменилась на KDE4 то очевидно и документация поменялась, но вот какой смысл менять загрузочные скрипты — мне непонятно. Ну а раз они не меняются, то и документация к ним тоже.

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

хм. если в этой вашей генте rc.local не только лежит не там, где у всех, но ещё и постоянно меняет своё месторасположение.

Источник

Как выполнить запуск скрипта от суперпользователя без пароля?

Все можно настроить через файл /etc/sudoers . Вот способ как можно перезапускать все службы ( sudo service . ) от пользователя userlogin .

1. Создаем специальную группу для запуска, которой дадим необходимые права:

sudo groupadd sudo-restrict 

2. Добавляем пользователя userlogin в эту группу:

sudo usermod -aG sudo-restrict userlogin 

3. Редактируем файл /etc/sudoers с помощью visudo :

Необходимо ставить в конце следующее:

%sudo-restrict ALL=(ALL) NOPASSWD: /usr/sbin/service 

/usr/sbin/service — путь к программе необходимо указывать абсолютный. В вашем случае это будет путь к вашему скрипту. Я использую служебную команду service

4. Проверяем

Заходим под пользователем userlogin и выполняем

sudo service mysqld restart 

Сервис перезапустится без ввода пароля.

PS

В конце /etc/sudoers можно раскомментировать эту строку: #includedir /etc/sudoers.d , и записывать все настройки в отдельные файлы в каталоге /etc/sudoers.d

Я согласен с ответом Total Pusher, но сам обычно использую более простой и универсальный способ:

  1. Запускаю sudo visudo
  2. Добавляю в конец username ALL=(ALL) NOPASSWD: ALL (укажите свой username)
  3. Сохраняю

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

UPD: Как метко подметил andreymal, этот способ создаёт дыру в безопасности системы и использовать его на постоянной основе не рекомендуется.

Источник

Оцените статью
Adblock
detector