Skip to content

Instantly share code, notes, and snippets.

@aramosf
Created January 20, 2024 14:32
Show Gist options
  • Save aramosf/634a3ca7a08b7dbf92ad6286f9b6529a to your computer and use it in GitHub Desktop.
Save aramosf/634a3ca7a08b7dbf92ad6286f9b6529a to your computer and use it in GitHub Desktop.
#!/bin/bash
# sharing samba over internet is not cool.
# updating smb.conf/iptables for just one ip, and having dynamic ip...
# dirty as hell
PATH=/usr/sbin:/sbin:/usr/bin:/bin
HOSTNAME="my.myddns.com"
date=$( date )
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
new_ip=""
while ! [[ $new_ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; do
new_ip=$(dig +short $HOSTNAME | head -n2)
sleep 2
done
old_ip=$(/usr/sbin/iptables --line-number -nL OUTPUT | grep Samba | awk '{ print $5}' | head -1)
if [ -z $old_ip ]; then
echo "Error with old_ip"
exit 1
fi
if [ "$new_ip" = "$old_ip" ] ; then
echo "$date IP address has not changed new_ip: $new_ip / old_ip: $old_ip"
exit 0
else
echo "$date IP address has been changed new_ip: $new_ip / old_ip: $old_ip"
echo "$date Updating IPTables now"
DELETERULE=$(/usr/sbin/iptables --line-number -nL OUTPUT | grep Samba | cut -f1 -d ' ' | sort -nr)
for rules in $DELETERULE
do
/usr/sbin/iptables -D OUTPUT "$rules"
done
for ip in $new_ip
do
/usr/sbin/iptables -I OUTPUT -s "$ip"/32 -p tcp -m tcp --dport 139 -m comment --comment "Samba" -j ACCEPT
/usr/sbin/iptables -I OUTPUT -s "$ip"/32 -p tcp -m tcp --dport 445 -m comment --comment "Samba" -j ACCEPT
done
DELETERULE=$(/usr/sbin/iptables --line-number -nL INPUT | grep Samba | cut -f1 -d ' ' | sort -nr)
for rules in $DELETERULE
do
/usr/sbin/iptables -D INPUT "$rules"
done
for ip in $new_ip
do
/usr/sbin/iptables -I INPUT -s "$ip"/32 -p tcp -m tcp --dport 139 -m comment --comment "Samba" -j ACCEPT
/usr/sbin/iptables -I INPUT -s "$ip"/32 -p tcp -m tcp --dport 445 -m comment --comment "Samba" -j ACCEPT
done
sed -i "s|allow hosts = .*|allow hosts = $new_ip|g" /etc/samba/smb.conf
systemctl restart smbd
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment