【问题标题】:Trying to get specific field from read in Ksh试图从 Ksh 中读取特定字段
【发布时间】:2021-06-21 01:24:30
【问题描述】:

我正在尝试在 Ksh 中编写一个简单的脚本来查看失败的尝试并查看 IP 地址。我正在将 lastb 输出转储到文件中,并且只想获取尝试过的用户名和它来自的 IP 地址。

最后一个输出

    user     ssh:notty    143.244.175.142  Mon Jun 21 01:04 - 01:04  (00:00)
    user     ssh:notty    143.244.175.142  Mon Jun 21 00:57 - 00:57  (00:00)

我的脚本是这样的

    #!/usr/bin/ksh
    FailedLogins="$HOME/sshattempts.txt

    if [ -e "$FailedLogins" ]
    then 
    echo "yes file exists"
    fi

    # while loop 

    while IFS=  read user tty ip
    do
    printf "$user $ip"
    done <"$FailedLogins"

【问题讨论】:

  • 您在FailedLogins="$HOME/sshattempts.txt 中缺少"。我将文件命名为ssh_attempts.txt,现在它看起来像ss_hat_tempts.txt

标签: while-loop ksh


【解决方案1】:

你可以使用这样的东西

#!/bin/ksh

if [[ -r $HOME/sshattempts.txt ]]; then
    print "yes file $HOME/sshattempts.txt exists"
else
    exit
fi


while read line; do
    parts=( $line )
    print "${parts[0]} ${parts[2]}"
done < $HOME/sshattempts.txt

【讨论】:

    【解决方案2】:

    在处理过程中,每一行将被解析为 10 个单独的(空格分隔)字段。当没有足够的变量(在这种情况下为 3 个)时,read 会将“行的其余部分”填充到最后一个变量中。

    处理来自sshattempts.txt 的第一行将导致以下变量赋值:

    user='user'
    tty='ssh:notty'
    ip='143.244.175.142  Mon Jun 21 01:04 - 01:04  (00:00)'
    

    虽然您可以编辑代码以向 read 提供 10 个变量,但您可以通过添加一个变量来保存所有出现在ip字段,例如:

    while IFS= read user tty ip rest_of_line
    

    现在在处理来自sshattempts.txt 的第一行时,您应该会看到:

    user='user'
    tty='ssh:notty'
    ip='143.244.175.142'
    rest_of_line='Mon Jun 21 01:04 - 01:04  (00:00)'
    

    【讨论】:

      【解决方案3】:

      一行的第一个和第三个条目:

      awk '{print $1, $3}' "$FailedLogins"
      

      【讨论】:

        猜你喜欢
        • 2021-02-04
        • 1970-01-01
        • 2018-04-09
        • 2016-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-13
        • 2021-09-15
        相关资源
        最近更新 更多