简体   繁体   English

bash脚本:sudo没有交互式回显重定向到文件

[英]bash script: sudo no interactive echo redirection to a file

in a bash script I'm trying to redirect a text printed with echo with sudo non interactive to a file. 在bash脚本中,我试图将使用sudo非交互式的echo打印的文本重定向到文件。 But I'm not clear about how to do it. 但是我不清楚如何去做。

I tried with this code: 我尝试使用以下代码:

echo $sudopass| sudo -S echo "user ALL=(ALL) NOPASSWD:ALL" >     /etc/sudoers.d/ansible

Output redirection is not affected by elevated sudo permissions. 输出重定向不受提升的sudo权限影响。 The part that you sudo is the echo , not the redirection of that command's output. sudo的部分是echo而不是该命令输出的重定向。

That will still happen with your current user's permission. 在您当前用户的许可下,这仍然会发生。

So you need a way to append a line to a file that does not involve output redirection. 因此,您需要一种将行追加到不涉及输出重定向的文件的方法。


Note: Earlier version of this answer showcasing sed removed as sed balks if the target file is empty or non-existing. 注意: 如果目标文件为空或不存在,则此答案的较早版本将sed删除,因为sed破坏sed As I wanted to keep the gist of the answer intact -- "how to avoid output redirection" -- I added instructions on how to use vi for the same purpose. 我想保持答案的要点不变-“如何避免输出重定向”-我添加了有关如何将vi用于相同目的的说明。


Every POSIX-compliant system needs to have the vi / ex editor. 每个符合POSIX的系统都需要具有vi / ex编辑器。 (On contemporary Linux machines usually a link starting Vim in compatiblity mode.) You can "remote-control" ex / vi / Vim through the command line: (在现代Linux机器上,通常以兼容模式启动Vim的链接。)您可以通过命令行“远程控制” ex / vi / Vim:

vi -es -c "normal! G" -c "normal! ouser ALL=(ALL) NOPASSWD:ALL" -c "x" /etc/sudoers.d/ansible

(This is without the sudo part for clarity.) (为了清楚起见,这没有sudo部分。)

Explanation: 说明:

  • -e starts vi in "ex mode". -e在“ ex模式”下启动vi (Equivalent to calling ex .) (相当于致电ex 。)
  • -s means "silent" -- no prompts, no messages. -s表示“静音”-没有提示,没有消息。
  • -c passes a command to the editor to be executed once the first file has been read. -c在读取第一个文件后将命令传递给编辑器以执行该命令。
  • "normal! G" first puts the editor in "normal mode" -- that is what you would find yourself in if you started vi interactively; "normal! G"将编辑器置于“ normal mode”(正常模式),这就是您以交互方式启动vi会遇到的情况; ex is in "command mode" by default (as if you entered : in vi). ex默认情况下处于“命令模式”(就像您在vi中输入: )。 The G moves the cursor to the last line. G将光标移到最后一行。
  • "normal! o..." again activates normal mode, adds a line after the current line, and activates "insert mode". "normal! o..."再次激活正常模式,在当前行之后添加一行,然后激活“插入模式”。 The rest of the string is entered verbatim. 字符串的其余部分按原样输入。
  • "x" saves the file and exits the editor. "x"保存文件并退出编辑器。

The command line including the sudo part: 命令行包括sudo部分:

echo $sudopass | sudo -S vi -es -c "normal! G" -c "normal! ouser ALL=(ALL) NOPASSWD:ALL" -c "x" /etc/sudoers.d/ansible

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

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