没有BASH -C的Sudo Echo的其他方法

发布于 2025-02-04 08:37:11 字数 287 浏览 3 评论 0原文

我必须在脚本my.sh中以sudo在脚本中运行echo,因为许可。 我不想用sudo my.sh执行脚本。 我不想使用bash -c“ ...”,因为逃脱了。

还有其他解决方案吗?

我的

#!/usr/bin/bash
>/file.tmp \
echo '
a="S T"
z=\a\b\c\
'

I must run the echo in the script my.sh with sudo because permission.
I do not want to execute the script with sudo my.sh.
I do not want to use bash -c "..." because escaping.

Are there no other solutions?

my.sh

#!/usr/bin/bash
>/file.tmp \
echo '
a="S T"
z=\a\b\c\
'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷离° 2025-02-11 08:37:11

您在这里遇到的问题是,输出重定向>/file.tmp必须在提升特权时发生。这意味着您要么必须像sudo my.sh一样启动脚本,要么以赋予其提升特权的方式执行重定向。这还不足以运行sudo echo,因为只有echo具有提高的特权,但是输出重定向将作为您的非root用户运行,因为它是一个shell buildin indentin noundin interiin interion interion inter不是外部命令。

有一个称为TEE的标准工具可以帮助您解决这个问题。该方法通常在运行curl以获取需要添加为root的数据时通常使用,例如安装debian apt存储库配置和签名键

$ whoami
dho
$ whoami | sudo tee whoami.txt >/dev/null
$ ls -la whoami.txt
-rw-r--r-- 1 root root 4 2022-06-03T09:08:22 whoami.txt

因此,您可以看到我与我自己的用户启动了whoami,但是由于tee,该文件最终被编写,因为tee,它取代了您的原始示例的输出重定向,以sudo tee启动。

The problem you are encountering here is that the output redirection >/file.tmp has to happen with elevated privileges. This means that you either have to launch the script as it is with sudo my.sh, or perform the redirection in a way that gives it elevated privileges. It is not enough to run sudo echo because only echo would have elevated privileges, but the output redirection would run as your non-root user because it is a shell builtin feature, not an external command.

There is a standard tool called tee that can help with this. This method is commonly used when running curl to fetch data that needs to be fed to root, such as installing debian apt repository configurations and signing keys.

$ whoami
dho
$ whoami | sudo tee whoami.txt >/dev/null
$ ls -la whoami.txt
-rw-r--r-- 1 root root 4 2022-06-03T09:08:22 whoami.txt

So you can see that I launched whoami with my own user, but the file ended up being written with root permissions because tee, which replaces the output redirection from your original example, was launched as sudo tee.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文