Skip to content

Instantly share code, notes, and snippets.

@lamchau
Last active August 29, 2015 14:17
Show Gist options
  • Save lamchau/c8105d6e7647c2558a4d to your computer and use it in GitHub Desktop.
Save lamchau/c8105d6e7647c2558a4d to your computer and use it in GitHub Desktop.
add IPs to access PostgreSQL remotely (Short URL: http://git.io/hiFi)
#!/bin/sh
# prerequisite: sudo su - postgres
CONFIGURATION_FILE="/etc/postgresql/9.4/main/pg_hba.conf"
CURRENT_IP=$(last -i | grep "still logged" | awk '{ print $3 }')
IPV4_REGEX="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
if [ ! -f "$CONFIGURATION_FILE" ]; then
echo "File not found: $CONFIGURATION_FILE"
exit 1
fi
if [ -z $(echo "$CURRENT_IP" | egrep $IPV4_REGEX) ]; then
echo "Invalid IP address: $CURRENT_IP"
exit 1
fi
if grep -Fq "$CURRENT_IP" $CONFIGURATION_FILE; then
echo "$CURRENT_IP was already exists in $CONFIGURATION_FILE"
else
echo "Added '$CURRENT_IP' to $CONFIGURATION_FILE"
echo "host all all $CURRENT_IP/32 trust" >> $CONFIGURATION_FILE
/etc/init.d/postgresql restart
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment