ban_client.sh 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/bin/bash
  2. set -o errexit
  3. set -o nounset
  4. set -o pipefail
  5. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  6. #SCRIPT_DIR="$(dirname "$(realpath "${BASH_SOURCE[0]}")")"
  7. source "$SCRIPT_DIR/functions.sh"
  8. show_usage() {
  9. echo "Usage: $0 <ccd_file> <ban|unban>"
  10. echo "Example: $0 /etc/openvpn/server/server/ccd/login ban"
  11. exit 1
  12. }
  13. main() {
  14. # Check permissions
  15. check_permissions
  16. # Process arguments
  17. [[ $# -lt 2 ]] && show_usage
  18. local ccd_file=$1
  19. local action=$2
  20. # Validate CCD file path
  21. check_ccd_path "$ccd_file"
  22. local username
  23. username=$(basename "${ccd_file}")
  24. touch "${ccd_file}"
  25. chmod 660 "${ccd_file}"
  26. chown ${owner_user}:${owner_group} "${ccd_file}"
  27. local is_banned=""
  28. if grep -q "^disable$" "$ccd_file"; then
  29. is_banned="disable"
  30. fi
  31. case "$action" in
  32. ban)
  33. if [[ -z "$is_banned" ]]; then
  34. log "Ban user: ${username}"
  35. echo -e "disable\n$(cat "$ccd_file")" > "$ccd_file"
  36. log "User ${username} banned successfully"
  37. else
  38. log "User ${username} is already banned"
  39. fi
  40. ;;
  41. unban)
  42. if [[ -n "$is_banned" ]]; then
  43. log "Unban user: ${username}"
  44. sed -i '/^disable$/d' "${ccd_file}"
  45. log "User ${username} unbanned successfully"
  46. # if the file is empty or only blank lines, we erase it.
  47. if [[ ! -s "${ccd_file}" ]] || ! grep -q '[^[:space:]]' "${ccd_file}"; then
  48. log "CCD file ${ccd_file} is empty after unban, removing"
  49. rm -f "${ccd_file}"
  50. fi
  51. else
  52. log "User ${username} is not banned"
  53. fi
  54. ;;
  55. *)
  56. log "Error: Invalid action. Use 'ban' or 'unban'"
  57. show_usage
  58. ;;
  59. esac
  60. exit 0
  61. }
  62. main "$@"