Skip to content

Instantly share code, notes, and snippets.

@sarkrui
Last active May 31, 2023 14:09
Show Gist options
  • Save sarkrui/e8637e64e49c0d50048ed4dd6ebac90e to your computer and use it in GitHub Desktop.
Save sarkrui/e8637e64e49c0d50048ed4dd6ebac90e to your computer and use it in GitHub Desktop.
Scan and Change IP on Alpine Linux
#!/bin/sh
# Parsing command line arguments
while [ "$1" != "" ]; do
case $1 in
--ip ) shift
IP=$1
;;
* ) echo "Invalid argument"
exit 1
esac
shift
done
set_ip() {
# Write IP to /etc/network/interfaces
echo "auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
address $1
netmask 255.255.255.0
gateway 158.132.32.1
dns-nameservers 1.1.1.1" > /etc/network/interfaces
# Restart networking
/etc/init.d/networking restart
}
find_free_ip() {
for i in $(seq 1 254)
do
IP="$1.$i"
if ! ping -c 1 -W 1 "$IP" > /dev/null
then
set_ip "$IP"
exit 0
fi
done
echo "No free IP found"
exit 1
}
# If IP address is not provided, scan the default subnet
if [ -z "$IP" ]; then
echo "IP address not provided. Scanning default subnet."
find_free_ip "158.132.58"
fi
# Count the number of dots in the IP
dots=$(echo $IP | tr -cd '.' | wc -c)
# If the IP address has two dots, it's a subnet
if [ "$dots" -eq 2 ]; then
find_free_ip "$IP"
# If the IP address has three dots, it's a full IP address
elif [ "$dots" -eq 3 ]; then
if ! ping -c 1 -W 1 "$IP" > /dev/null
then
set_ip "$IP"
else
echo "IP address $IP is not available. Please provide another one."
exit 1
fi
else
echo "Invalid IP address or subnet provided."
exit 1
fi
@sarkrui
Copy link
Author

sarkrui commented May 31, 2023

Run the script as follows:

ash ip.sh --ip 158.132.32

or

ash ip.sh --ip 158.132.32.70

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment