-
Notifications
You must be signed in to change notification settings - Fork 1
/
prepare-hosts
53 lines (44 loc) · 1.61 KB
/
prepare-hosts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/bin/bash
WIN_HOSTS="/mnt/c/Windows/System32/drivers/etc/hosts"
TMP_HOSTS="/tmp/prepare-hosts"
WIN_IP=$(grep </etc/resolv.conf 'nameserver' | cut -f 2 -d ' ')
WSL_IP=$(ip addr show eth0 | grep 'inet ' | cut -f 6 -d ' ' | cut -f 1 -d '/')
export WIN_IP
export WSL_IP
check_ip() {
IP_NAME=$1
IP=$2
if [[ "$IP" == "" ]]; then
printf "%s: \x1b[31mIP is empty!\x1b[0m\n" "$IP_NAME"
else
printf "%s: \x1b[32m%s\x1b[0m\n" "$IP_NAME" "$IP"
fi
}
prepare_hosts() {
HOSTS_FILE=$1
TMP_HOSTS_FILE=$2
MARK=$3
IP=$4
if [[ "$IP" != "" ]]; then
if grep -q "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\s\{1,\}$MARK" "$HOSTS_FILE"; then
printf "\x1b[32mFound %s marks!\x1b[0m\n" "$MARK"
rm -f "$TMP_HOSTS_FILE"
cp "$HOSTS_FILE" "$TMP_HOSTS_FILE"
sed -i -e "s/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\(\s\{1,\}\)$MARK/$IP\1$MARK/g" "$TMP_HOSTS_FILE"
sed -i -e "s/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\(\s\{1,\}\)\(.*\)\(\s\{1,\}\)#$MARK/$IP\1\2\3#$MARK/g" "$TMP_HOSTS_FILE"
cat "$TMP_HOSTS_FILE" >"$HOSTS_FILE"
else
printf "%s %s\n" "$IP" "$MARK" >>"$HOSTS_FILE"
fi
fi
}
check_ip "Windows IP" "$WIN_IP"
check_ip "WSL IP" "$WSL_IP"
prepare_hosts $WIN_HOSTS $TMP_HOSTS "wsl2" "$WSL_IP"
prepare_hosts $WIN_HOSTS $TMP_HOSTS "winhost" "$WIN_IP"
printf "\nNew hosts file: \n\n"
printf "\x1b[34m=====================================================================\x1b[0m\n"
cat "$WIN_HOSTS"
printf "\x1b[34m=====================================================================\x1b[0m\n"
rm -f "$TMP_HOSTS"
printf "\n\x1b[32mDONE!\x1b[0m\n\n"