ifup-nat 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/bin/bash
  2. # 设置 bridge 名称
  3. BRIDGE=dragonos-bridge
  4. # 设置网络信息
  5. NETWORK=192.168.137.0
  6. NETMASK=255.255.255.0
  7. GATEWAY=192.168.137.1
  8. DHCPRANGE=192.168.137.100,192.168.137.200
  9. # 启用PXE支持的可选参数
  10. TFTPROOT=
  11. BOOTP=
  12. function check_bridge()
  13. {
  14. if brctl show | grep "^$BRIDGE" &> /dev/null; then
  15. return 1
  16. else
  17. return 0
  18. fi
  19. }
  20. function create_bridge()
  21. {
  22. brctl addbr "$BRIDGE"
  23. brctl stp "$BRIDGE" on
  24. brctl setfd "$BRIDGE" 0
  25. ifconfig "$BRIDGE" "$GATEWAY" netmask "$NETMASK" up
  26. }
  27. function enable_ip_forward()
  28. {
  29. echo 1 > /proc/sys/net/ipv4/ip_forward
  30. }
  31. function add_filter_rules()
  32. {
  33. iptables -t nat -A POSTROUTING -s "$NETWORK"/"$NETMASK" \
  34. ! -d "$NETWORK"/"$NETMASK" -j MASQUERADE
  35. }
  36. function start_dnsmasq()
  37. {
  38. # 禁止重复运行dnsmasq
  39. ps -ef | grep "dnsmasq" | grep -v "grep" &> /dev/null
  40. if [ $? -eq 0 ]; then
  41. echo "dnsmasq 已经在运行"
  42. return 1
  43. fi
  44. dnsmasq \
  45. --strict-order \
  46. --except-interface=lo \
  47. --interface=$BRIDGE \
  48. --listen-address=$GATEWAY \
  49. --bind-interfaces \
  50. --dhcp-range=$DHCPRANGE \
  51. --conf-file="" \
  52. --pid-file=/var/run/qemu-dhcp-$BRIDGE.pid \
  53. --dhcp-leasefile=/var/run/qemu-dhcp-$BRIDGE.leases \
  54. --dhcp-no-override \
  55. ${TFTPROOT:+"--enable-tftp"} \
  56. ${TFTPROOT:+"--tftp-root=$TFTPROOT"} \
  57. ${BOOTP:+"--dhcp-boot=$BOOTP"}
  58. }
  59. function setup_bridge_nat()
  60. {
  61. check_bridge "$BRIDGE"
  62. if [ $? -eq 0 ]; then
  63. create_bridge
  64. fi
  65. enable_ip_forward
  66. add_filter_rules "$BRIDGE"
  67. start_dnsmasq "$BRIDGE"
  68. }
  69. # 安装前需要检查$1参数
  70. if [ -n "$1" ]; then
  71. setup_bridge_nat
  72. brctl addif "$BRIDGE" "$1"
  73. ifconfig "$1" 0.0.0.0 up
  74. exit 0
  75. else
  76. echo "发现错误:没有指定接口"
  77. exit 1
  78. fi