Useful CLI tools (bash) for Arch Linux administration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.5 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. #!/usr/bin/env bash
  2. #
  3. # SSH timezone - Automatically retrieve timezone information for SSH users
  4. #
  5. # Copyright (C) 2018 Pekka Helenius
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. #####################################
  20. # This script is meant to be used as a part of provided 'bash.custom' file
  21. #####################################
  22. REQ_PKGS=(geoip2-database mmdblookup systemd openssh bind-tools)
  23. PACMAN_EXEC="/usr/bin/pacman"
  24. for pkg in ${REQ_PKGS[*]}; do
  25. if [[ ! $("${PACMAN_EXEC}" -Q | grep $pkg) ]]; then
  26. echo -e "\nMissing package $pkg\n"
  27. kill -INT $$
  28. fi
  29. done
  30. GEOIP2_DATABASE="/usr/share/GeoIP/GeoLite2-City.mmdb"
  31. if [[ ! -f $GEOIP2_DATABASE ]]; then
  32. # GeoIP2 database file couldn't be found
  33. kill -INT $$
  34. fi
  35. # If SSH_CONNECTION variable is defined
  36. if [[ $(export -p | grep -o SSH_CONNECTION) ]]; then
  37. # Get IP address of the user
  38. RUSER_IP=$(echo $SSH_CONNECTION | awk '{print $1}')
  39. # If SSH IP is local, try to get public IP.
  40. if [[ $RUSER_IP =~ ^192\.168\. ]] || [[ $RUSER_IP =~ ^10\. ]] || [[ $USER_IP =~ ^172\.{16..31}\. ]]; then
  41. RUSER_WAN_IP=$(dig +short +time=8 +tries=1 myip.opendns.com @resolver1.opendns.com 2>/dev/null)
  42. # If OpenDNS hostname can't be resolved, use local IP as a fallback
  43. if [[ $(echo $RUSER_WAN_IP | wc -w) -eq 0 ]]; then
  44. RUSER_WAN_IP=$RUSER_IP
  45. fi
  46. else
  47. # WAN IP is used IP
  48. RUSER_WAN_IP=$RUSER_IP
  49. fi
  50. else
  51. # Couldn't find IP address from SSH_CONNECTION variable
  52. kill -INT $$
  53. fi
  54. TZ=$(mmdblookup -f $GEOIP2_DATABASE -i $RUSER_WAN_IP location 2>/dev/null | awk '/time_zone/ {getline; print $0}' | awk -F '"' '{print $2}')
  55. # If TZ is empty, then use server default time zone setting as a default value
  56. if [[ $(echo $TZ | wc -w) -eq 0 ]]; then
  57. export TZ=$(timedatectl | sed '/Time zone:/!d' | awk '{print $3}')
  58. else
  59. export TZ
  60. fi