简体   繁体   English

在Shell脚本中取消sudo提示

[英]Cancel sudo prompts in a shell script

I don't want 'sudo' to prompt me for password while my script is running. 我不希望'sudo'在脚本运行时提示我输入密码。 And i do not want to enter sudo password as well using sudo -S. 而且我也不想使用sudo -S输入sudo密码。 Is there any way to skip sudo lines and run next line of script. 有什么办法可以跳过sudo行并运行脚本的下一行。 Or is there any way to print 'sudo access required' whenever sudo is prompted and running the script further. 或者,无论何时提示sudo并进一步运行脚本,是否有任何方法可以打印“需要sudo访问权限”。

You can test if the current user is root, like: 您可以测试当前用户是否是root用户,例如:

if [ "$(id -u)" != "0" ]; then
    echo "root access required"
    exit -1
fi

If you don't want to prompt a sudo password, just add your current user to /etc/sudoers (edit this file as root). 如果您不想输入sudo密码,只需将当前用户添加到/ etc / sudoers中(以root身份编辑此文件)。

Find there a block, starts from comment: 找到一个块,从注释开始:

# Allow members of group sudo to execute any command

And add there kind of this line: 并添加以下这一行:

YourUserName ALL=(ALL) NOPASSWD: ALL

For the record, a better approach would be to just copy the script and edit it to a non-root version. 作为记录,更好的方法是只复制脚本并将其编辑为非根版本。

That said, if you create a function to implement your sudo 's that requires a flag be set you can activate them at runtime, but skip them by default. 也就是说,如果您创建一个函数来实现需要设置标志的sudo ,则可以在运行时将其激活,但默认情况下将其跳过。

$: cat tst
#! /bin/env bash

dosudo() {
   if (( DOSUDO ))
   then sudo "$@"
   else echo "Skipping: sudo $@"
   fi
}

echo before
dosudo ls -d /tmp
echo after

Running it in default mode: 在默认模式下运行它:

$: tst
before
Skipping: sudo ls -d /tmp
after

Running it active (I CTRL-C break out of the prompt here) - 主动运行它(我在这里按CTRL-C跳出提示)-

$ DOSUDO=1 tst
before
[sudo] password for weblogic:
after

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM