|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +# Ensure the script is run as root |
| 4 | +if [ "$EUID" -ne 0 ]; then |
| 5 | + echo "This script requires root permissions. Please run with sudo." |
| 6 | + exit 1 |
| 7 | +fi |
| 8 | + |
| 9 | +# Check if sufficient arguments are passed |
| 10 | +if [ "$#" -lt 2 ]; then |
| 11 | + echo "Usage:" |
| 12 | + echo "$0 add <hostname> <IP> - to add an entry" |
| 13 | + echo "$0 delete <hostname> - to delete an entry" |
| 14 | + exit 1 |
| 15 | +fi |
| 16 | + |
| 17 | +ACTION=$1 |
| 18 | +HOSTNAME=$2 |
| 19 | +IP=$3 |
| 20 | + |
| 21 | +# Validate the IP address format (basic validation) |
| 22 | +if [[ $ACTION == "add" && ! $IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then |
| 23 | + echo "Error: Invalid IP address format." |
| 24 | + exit 1 |
| 25 | +fi |
| 26 | + |
| 27 | +case $ACTION in |
| 28 | + add) |
| 29 | + if [ -z "$HOSTNAME" ] || [ -z "$IP" ]; then |
| 30 | + echo "Error: IP and hostname required to add an entry." |
| 31 | + echo "Usage: $0 add <hostname> <IP>" |
| 32 | + exit 1 |
| 33 | + fi |
| 34 | + |
| 35 | + # Check if the hostname already exists |
| 36 | + if grep -q "$HOSTNAME" /etc/hosts; then |
| 37 | + echo "$HOSTNAME already exists in /etc/hosts." |
| 38 | + else |
| 39 | + # Add the new entry |
| 40 | + echo "$IP $HOSTNAME" | tee -a /etc/hosts > /dev/null |
| 41 | + echo "$HOSTNAME added to /etc/hosts." |
| 42 | + fi |
| 43 | + ;; |
| 44 | + |
| 45 | + delete) |
| 46 | + if [ -z "$HOSTNAME" ]; then |
| 47 | + echo "Error: Hostname required to delete an entry." |
| 48 | + echo "Usage: $0 delete <hostname>" |
| 49 | + exit 1 |
| 50 | + fi |
| 51 | + |
| 52 | + # Check if the hostname exists |
| 53 | + if grep -q "$HOSTNAME" /etc/hosts; then |
| 54 | + # Remove the line containing the hostname |
| 55 | + sed -i "/$HOSTNAME/d" /etc/hosts |
| 56 | + echo "$HOSTNAME removed from /etc/hosts." |
| 57 | + else |
| 58 | + echo "$HOSTNAME not found in /etc/hosts." |
| 59 | + fi |
| 60 | + ;; |
| 61 | + |
| 62 | + *) |
| 63 | + echo "Invalid action. Use 'add' or 'delete'." |
| 64 | + echo "Usage:" |
| 65 | + echo "$0 add <hostname> <IP> - to add an entry" |
| 66 | + echo "$0 delete <hostname> - to delete an entry" |
| 67 | + exit 1 |
| 68 | + ;; |
| 69 | +esac |
0 commit comments