简体   繁体   English

如何在一行命令中将密码应用于 sudo 并执行 su root?

[英]How can I apply password to sudo in one line command and execute su root?

I've created an user named samX with root privilege (have appended "samX ALL=(ALL:ALL) ALL" in visudo ).我创建了一个名为 samX 的具有 root 权限的用户(在visudo附加了“samX ALL=(ALL:ALL) ALL”)。

I'm trying to apply password to sudo , then su root and execute whoami sequentially in one line command.我正在尝试将密码应用于sudo ,然后su root并在一行命令中依次执行whoami My current command is somewhat as follows, but it complains error: sudo: su root;我当前的命令有点如下,但它抱怨错误: sudo: su root; whoami: command not found 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.非常感谢。

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;应该工作 - -c为 su 指定一个命令,而在您的示例中,您似乎正在运行一个命令 'root; whoami' which does not exist - there is no shell to break that up into two separate commands. whoami' 不存在 - 没有外壳将其分解为两个单独的命令。

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.而不是将您的密码保存在 bash 历史记录或任何其他文件中。 With that, there is no need to enter the password at all.这样,根本不需要输入密码。

If you want to perform a different command, add that.如果要执行不同的命令,请添加该命令。

当您通过 putty 或 moba 登录到 shell 会话时,您在其中存储了非 root 帐户的登录凭据,只需添加此命令以在 putty 或 moba 登录时执行,它会立即将您的访问权限切换到 root。

echo "PASSWORD" | sudo -S su - && sudo su

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.注意:像这样传递密码是个坏主意。

这应该有效。

echo CbEYKFKt | sudo -S; whoami

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

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