在shell脚本中编辑sudo文件

时间:2012-11-29 13:22:31

标签: linux shell unix sed

我想通过删除#或在特定行中添加#来编辑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

1 个答案:

答案 0 :(得分:2)

使用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. 将整条线替换为线的捕获部分(丢弃#)。
  5. 所以:

    # 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