【问题标题】:Trying to filter users out of /etc/passwords then adding them into some text that would then go to an output file尝试从 /etc/passwords 中过滤掉用户,然后将它们添加到一些文本中,然后这些文本将转到输出文件
【发布时间】:2020-08-06 17:43:29
【问题描述】:

到目前为止的脚本(不工作):

#!/bin/bash
while read line
uname="cat /etc/passwd | grep bash | sed 's/:.*//'"
echo "config system admin 
for each line $uname >
if $uname = "root" then
echo "skipping $uname 'root'" else
echo "edit '$uname'/n
set remote-auth enable/n
set trusthost1 8.8.8.8 255.255.255.255/n
set accprofile "admin"/n
set vdom "root"/n
set remote-group "foobar"/n
set password ENC potatoes/n
next/n" > output.txt

“cat /etc/passwd | grep bash | sed 's/:.*//'”的输出

foo
root
bar

“output.txt”中的预期输出,“/etc/password”中列出的三个用户是 foo、root 和 bar:

config system admin 
edit foo 
set remote-auth enable
set trusthost1 8.8.8.8 255.255.255.255
set accprofile "admin"
set vdom "root"
set remote-group "foobar"
set password ENC potatoes
next
edit bar
set remote-auth enable
set trusthost1 8.8.8.8 255.255.255.255
set accprofile "admin"
set vdom "root"
set remote-group "foobar"
set password ENC potatoes
next

【问题讨论】:

    标签: linux bash ubuntu ubuntu-16.04


    【解决方案1】:

    你的语法有问题。我猜你想要

    #!/bin/bash
    
    echo "config system admin" >output.txt
    
    sed -n '/bash/s/:.*//p' /etc/passwd |
    while read -r uname; do
      if [ "$uname" = "root" ]; then
        echo "skipping '$uname'" >&2
      else
        cat <<____
    edit $uname
    set remote-auth enable
    set trusthost1 8.8.8.8 255.255.255.255
    set accprofile "admin"
    set vdom "root"
    set remote-group "foobar"
    set password ENC potatoes
    next
    ____
      fi
    done >>output.txt
    

    您可能尝试输入 \n(而不是 /n)来指示文字换行符,但该字符串已包含您需要的所有换行符。

    我进行了重构以避免useless catuseless grep,但是如果您只是学习基础知识,那么基本的语法修复可能更需要注意。

    echo 上使用带有 here-document 的 cat 在这里可能不是一个关键的变化,但可以简化您遇到的嵌套引用难题。

    如果(如评论中所示)您想跳过许多用户,而不仅仅是 root,也许切换到 case 语句:

    while read -r uname; do
      case $uname in
        "root" | "fred" | "barney" | "dino")
          echo "skipping '$uname'" >&2;;
      *)
        cat <<____;;
    ...
    ____
      esac
    done 
    
    

    这种语法起初看起来令人困惑,但并不危险,只是与大多数其他语言的外观不同。 * 的情况就像前面脚本中的 else 一样,每个分支都需要用双分号终止。

    【讨论】:

    • 绝对的传奇伴侣。我知道我在那里做错了什么。一百万票给你。
    • 还有一个问题。对于,如果 [ "$uname" = "root" ];然后 echo "skipping $uname 'root'" >&2 如果我想在这里添加多个用户除了 "root" 我如何使 echo "skipping $uname 'root'" >&2 "root" 位变量,然后添加多个用户在这里?如果 [ "$uname" = "root" ];那么
    • 切换到case 语句可能更容易,它可以让您轻松列出一堆替代方案。我会用更多代码更新答案。
    • 啊,我想通了。它是: if [ "$uname" = "root" ] || [“$uname”=“测试”]|| [ "$uname" = "用户" ];然后回显“跳过$uname”>&2
    • 但我仍然希望看到“案例”选项。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    相关资源
    最近更新 更多