connect_if.sh 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/bin/bash
  2. #
  3. # Copyright (c) 2022 Project CHIP Authors
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # Enable/disable/restart TAP/TUN Open IoT SDK networking environment.
  18. HOST_BRIDGE="ARMhbr"
  19. DEFAULT_ROUTE_IF=""
  20. USER="$(id -u -n)"
  21. INTERFACES=()
  22. declare -A default_if_info
  23. if [ "$EUID" -ne 0 ]; then
  24. echo "Run a script with root permissions"
  25. exit 1
  26. fi
  27. function show_usage() {
  28. cat <<EOF
  29. Usage: $0 command net_if <net_if> ...
  30. Connect specific network interfaces with the default route interface. Create a bridge and link all interfaces to it.
  31. Keep the default route of network traffic.
  32. EOF
  33. }
  34. function get_default_if_info() {
  35. default_if_info[ip]="$(ifconfig "$DEFAULT_ROUTE_IF" | grep -w inet | awk '{print $2}' | cut -d ":" -f 2)"
  36. default_if_info[netmask]="$(ifconfig "$DEFAULT_ROUTE_IF" | grep -w inet | awk '{print $4}' | cut -d ":" -f 2)"
  37. default_if_info[broadcast]="$(ifconfig "$DEFAULT_ROUTE_IF" | grep -w inet | awk '{print $6}' | cut -d ":" -f 2)"
  38. default_if_info[gateway]="$(ip route show 0.0.0.0/0 dev "$DEFAULT_ROUTE_IF" | cut -d\ -f3)"
  39. }
  40. function connect_with_host() {
  41. ip link add name "$HOST_BRIDGE" type bridge
  42. ip link set "$DEFAULT_ROUTE_IF" master "$HOST_BRIDGE"
  43. ip addr flush dev "$DEFAULT_ROUTE_IF"
  44. for interface in "${INTERFACES[@]}"; do
  45. ip link set "$interface" master "$HOST_BRIDGE"
  46. ip addr flush dev "$interface"
  47. done
  48. ifconfig "$HOST_BRIDGE" "${default_if_info[ip]}" netmask "${default_if_info[netmask]}" broadcast "${default_if_info[broadcast]}"
  49. route add default gw "${default_if_info[gateway]}" "$HOST_BRIDGE"
  50. }
  51. if [[ $# -lt 1 ]]; then
  52. show_usage >&2
  53. exit 1
  54. fi
  55. INTERFACES=("$*")
  56. DEFAULT_ROUTE_IF=$(route | grep '^default' | grep -o '[^ ]*$')
  57. echo "Default route interface $DEFAULT_ROUTE_IF"
  58. get_default_if_info
  59. echo "Connect $INTERFACES to $DEFAULT_ROUTE_IF via bridge"
  60. connect_with_host