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.

76 lines
2.5 KiB

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