簡體   English   中英

如何從netstat抓取字符串(ip)管道將字符串(ip)傳遞給whois命令,如何從whois輸出抓取字符串(國家/地區)。 並使用iptables禁止ip

[英]How to grab string(ip) from netstat pipe the string(ip) to whois command, grab a string(country) from whois output. And use iptables to ban the ip

我想做的是使用netstat -an | grep ESTABLISHED netstat -an | grep ESTABLISHED ,可以通過whois搜索檢查我系統中的所有IP地址,並禁止任何屬於中國的IP地址。

所以我想知道如何實現這一目標? 可能通過將字符串通過管道傳遞到彼此的命令中? 但是我該怎么辦呢?

(試圖在不增加ssh安全性的情況下禁止中國,我希望通過bash或python實現此目的)

我到目前為止的代碼:

#!/bin/bash
netstat -an | grep ESTABLISHED > log.txt;
myvar=$(awk -F"|" '{print $NF}' log.txt)
whois $myvar

我正在努力自動化檢查該國是否為中國並禁止ip的過程。

這是用bash編寫的示例,


    #!/bin/bash
    # shellcheck disable=SC2155
    # Automatically ban IP from country
    # Copyright (C) 2019 Lucas Ramage <ramage.lucas@protonmail.com>
    # SPDX-License-Identifier: MIT
    set -euo pipefail
    IFS=$'\n\t'

    # netstat output:
    # Proto Recv-Q Send-Q Local Address Foreign Address State

    get_ip_addr() {
      # Awk splits the 5th column, Foreign Address, to get the IP
      echo "${1}" | awk '{ split($5, a, ":"); print a[1] }'
    }

    # whois output:
    # OrgName:        Internet Assigned Numbers Authority
    # OrgId:          IANA
    # Address:        12025 Waterfront Drive
    # Address:        Suite 300
    # City:           Los Angeles
    # StateProv:      CA
    # PostalCode:     90292
    # Country:        US <-- We want this one
    # RegDate:
    # Updated:        2012-08-31
    # Ref:            https://rdap.arin.net/registry/entity/IANA

    get_country() {
      # Returns nothing if Country not set
      whois "${1}" | awk '/Country/ { print $NF }'
    }

    check_country() {
      # Implements a whitelist, instead of a blacklist
      local COUNTRIES="US"

      # Iterate through whitelist
      for country in $COUNTRIES; do
        # Check entry to see if its in the whitelist
        if [ "${country}" == "${1}" ]; then
          echo 1 # true
        fi
      done
    }

    block_ip() {
      # Remove the `echo` in order to apply command; must have proper privileges, i.e sudo
      echo sudo iptables -A INPUT -s "${1}" -j "${2}"
    }

    main() {

      # Established Connections
      local ESTCON=$(netstat -an | grep ESTABLISHED)

      for entry in $ESTCON; do
        local ip=$(get_ip_addr "${entry}")
        local country=$(get_country "${ip}")
        local is_allowed=$(check_country "${country}")
        local policy='DROP' # or REJECT

        if [ ! "${is_allowed}" -eq "1" ]; then
          block_ip "${ip}" "${policy}"
        fi
      done
    }

    main

我親自對其運行shellcheck ,然后對其進行進一步測試。

另外,您可能想研究一下fail2ban或類似的東西。

感謝您的詢問。

您的追求是產品范圍。 人們正在以此為生。 這里

該問題涉及很少的無關實踐。

  1. 地理位置連接。

  2. 維護黑名單和白名單來源的列表。

  3. 實施列表更新策略。

  4. 實現日志記錄和通知。

任務1和2被用作網絡服務(谷歌搜索)。 許多商業DRM解決方案還可以實現您的請求並維護其功能。

我建議在進入技術設計之前先研究成本/工作量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM