bash - 使用从脚本调用的 vim 编辑 visudo
问题描述
我创建了一个自动安装脚本,在从 chroot 执行时,我想取消注释轮组行。我可以使用它来做到这一点,sed -i "s/# %wheel ALL=(ALL) ALL/%wheel ALL=(ALL) ALL/g" /etc/sudoers
但我读到这不是最佳做法。那么,如何用 vim 做到这一点呢?
该命令是:82 s/# //
我尝试使用管道,重定向标准输入或使用 vim +“命令文件”,但前者不起作用,后者起作用但表明它是只读文件...
谢谢!
解决方案
一种可能性是将您的 sed 命令(不带-i
标志)的输出通过管道传输到此脚本中,以在安全的情况下覆盖 sudoers 文件,而不必尝试以非交互方式运行编辑器。
#!/bin/sh
#
# Replaces /etc/sudoers with a new version supplied
# on standard input, but first performs safety checks
# including with "visudo -c"
#
sudoers=/etc/sudoers
tmp_sudoers=$sudoers.tmp # same tmp file as used by visudo
if [ -e $tmp_sudoers ]
then
echo "someone is editing sudoers"
exit 1
fi
# make new version from data on stdin, preserving permissions
# by creating a copy and then overwriting it
cp $sudoers $tmp_sudoers
cat > $tmp_sudoers
# install the new version if it passes checks
succeeded=0
if [ ! -s $tmp_sudoers ]
then
echo "replacement file is empty"
elif diff -q $sudoers $tmp_sudoers > /dev/null
then
echo "there were no changes"
elif ! visudo -q -c -f $tmp_sudoers
then
echo "replacement file is invalid"
else
mv $tmp_sudoers $sudoers
succeeded=1
fi
if [ $succeeded -eq 0 ]
then
rm $tmp_sudoers
exit 1
fi
推荐阅读
- bash - 每次在选择菜单中显示所有 4 个选项
- java - 赋值时奇怪的 Java 三元行为。Java 在幕后做了什么来实现这一点?
- eclipse-plugin - 尝试在插件中加载 JDBC 驱动程序 jar
- excel - 长时间运行的 VBA 宏被 svchost.exe 中断
- docker - 我正在使用 Azure Devops 构建和推送我的 Docker 映像。如何在使用 Docker 任务进行 buildAndPush 时传递参数?
- python - 相同的数据分为训练集、开发集和测试集
- html - 根据分辨率缩放 Html 列表
- python - Http - 隧道连接失败:Python Web 抓取出现 403 禁止错误
- node.js - 我在 Heroku 上部署应用程序时遇到了 Socket io 问题
- r - 减少 glmnet 中 x 变量之一的权重