繁体   English   中英

在 shell 脚本中编辑 sudo 文件

[英]Editing the sudo file in a shell script

我想通过在特定行上删除#或在其中添加#来编辑 Solaris 中的 sudoers 文件,那么我该如何为此编写脚本? 我的 sudoer 示例文件如下:

# The following line allows su without options/arguments and sux to user root
Cmnd_Alias SU_ROOT = /usr/bin/su "",\
                     /usr/local/bin/sux - root

# Defaults specification
Defaults:%saptb !authenticate

# User privilege specification
%saptb  ALL=(root)SU_SAP
#Uncomment this line when SAP requires root access
%saptb ALL=(root)SU_ROOT
##### END SAP-TB specific  ######
#
#
#Tivoli ITM Tools Team Sudo Right
#
%cgtools        ALL=(root)       NOPASSWD: /opt/IBM/ITM/bin/*

在上面的 sudoers 文件中,我想在%saptb ALL=(root)SU_ROOT的唯一行之前添加#

sed替换:

# Comment out the line %saptb ALL=(root)SU_ROOT
sudo sed -Ei 's/^(%saptb.*SU_ROOT.*)/#\1/' /etc/sudoers

解释:

-E使用扩展regex

-i就地编辑文件。

s/         # Substitution
^          # Match the start of the line
(          # Capture the following
%saptb     # Followed by %saptb
.*         # Followed by anything
SU_ROOT    # Followed by SU_ROOT
.*         # Followed by anything
)          # Close capture
/          # Replace with 
#          # A hash 
\1         # Followed by the captured line

取消注释行的原则是相同的:

  1. 匹配行的开头
  2. 后跟一个#
  3. 捕获该行的其余部分
  4. 用捕获的部分行替换整行(扔掉# )。

所以:

# Uncomment the line %saptb ALL=(root)SU_ROOT
sudo sed -Ei 's/^#(%saptb.*SU_ROOT.*)/\1/' /etc/sudoers

您可以使用以下脚本通过运行sudo ./toggle.sh来注释/取消注释

#!/bin/bash

# Is the line already commented out
grep -q '#%saptb ALL=(root)SU_ROOT' /etc/sudoers

if [ $? -eq 0 ]; then 
    # Uncomment the line %saptb ALL=(root)SU_ROOT
    sed -Ei 's/^#(%saptb.*SU_ROOT.*)/\1/' /etc/sudoers
else 
    # Comment out the line %saptb ALL=(root)SU_ROOT
    sed -Ei 's/^(%saptb.*SU_ROOT.*)/#\1/' /etc/sudoers
fi

暂无
暂无

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

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