bash 如何在一行命令中将密码应用于 sudo 并执行 su root?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29938453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I apply password to sudo in one line command and execute su root?
提问by Judking
I've created an user named samX with root privilege (have appended "samX ALL=(ALL:ALL) ALL" in visudo
).
我创建了一个名为 samX 的具有 root 权限的用户(在 中附加了“samX ALL=(ALL:ALL) ALL” visudo
)。
I'm trying to apply password to sudo
, then su root
and execute whoami
sequentially in one line command. My current command is somewhat as follows, but it complains error: sudo: su root; whoami: command not found
我想申请密码sudo
,然后su root
并执行whoami
一个命令行的顺序。我当前的命令有点如下,但它抱怨错误:sudo: su root; whoami:找不到命令
echo 'CbEYKFKt' | sudo -S 'su root; whoami'
In which, 'CbEYKFKt' is the password for user samX.
其中,'CbEYKFKt'是用户samX的密码。
Is there anyway to solve this problem? Thanks a lot.
有没有办法解决这个问题?非常感谢。
回答by martin
You should really add a line to your sudoers file such as
您真的应该在 sudoers 文件中添加一行,例如
samX ALL=(ALL:ALL) NOPASSWD: /sbin/su
instead of saving your password in the bash history or any other file. With that, there is no need to enter the password at all.
而不是将您的密码保存在 bash 历史记录或任何其他文件中。这样,根本不需要输入密码。
If you want to perform a different command, add that.
如果要执行不同的命令,请添加该命令。
回答by DavidC
echo 'CbEYKFKt' | sudo -S su -c whoami
should work - -c
specifies a command for su whereas in your example you seem to be running a command 'root; whoami' which does not exist - there is no shell to break that up into two separate commands.
应该工作 --c
为 su 指定一个命令,而在您的示例中,您似乎正在运行一个命令 'root; whoami' 不存在 - 没有外壳将其分解为两个单独的命令。
回答by Andy
When you login into a shell session via putty or moba where you have stored the login credentials for a non root account, simply add this command to be executed upon login in by putty or moba and it will switch your access to root right away.
当您通过 putty 或 moba 登录到 shell 会话时,您在其中存储了非 root 帐户的登录凭据,只需添加此命令以在 putty 或 moba 登录时执行,它会立即将您的访问权限切换到 root。
echo "PASSWORD" | sudo -S su - && sudo su
echo "PASSWORD" | sudo -S su - && sudo su
回答by Jahid
Instead of putting all commands in one line, you can write codes normally and break it into several lines:
您可以正常编写代码并将其分成几行,而不是将所有命令放在一行中:
#!/bin/bash
echo "CbEYKFKt" | sudo -S echo && sudo -s <<EOF
#put your code here
#All codes will be executed as sudo
EOF
Note: passing password like that is a bad idea.
注意:像这样传递密码是个坏主意。
回答by Sarat Chandra
This Should Work.
这应该有效。
echo CbEYKFKt | sudo -S; whoami