Initial commit: OpenWrt firewall management scripts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-08 18:19:24 +08:00
commit 0359abb7dc
6 changed files with 560 additions and 0 deletions

214
README.md Normal file
View File

@@ -0,0 +1,214 @@
# OpenWrt 管理指令
**目標設備**`192.168.42.10`OpenWrt 24.10.4
**WAN IP**`125.229.110.50`PPPoE
---
## 系統狀態確認
```sh
# 開機時間與負載
uptime
# 記憶體用量
free -m
# 磁碟空間
df -h
# 近期系統紀錄
logread -l 50
# 即時追蹤紀錄
logread -f
```
---
## 套件管理
```sh
# 更新套件列表
opkg update
# 安裝套件
opkg install <package_name>
# 移除套件
opkg remove <package_name>
# 列出已安裝套件
opkg list-installed
# 升級所有套件
opkg list-upgradable | cut -f 1 -d ' ' | xargs -r opkg upgrade
```
---
## 防火牆nftables / fw4
```sh
# 列出所有規則
nft list ruleset
# 列出特定 table
nft list table inet fw4
# 重新載入防火牆設定
fw4 restart
# 備份目前規則
nft list ruleset > /etc/nftables.backup
# 清除特定集合
nft flush set inet fw4 taiwan_ips
# 查看 Taiwan IP 集合(元素數量)
nft list set inet fw4 taiwan_ips | grep -c elements
```
---
## 網路診斷
```sh
# 介面清單與狀態
ip -br addr
# 路由表
ip route show
# 測試對外網路
ping -c 4 8.8.8.8
# DNS 查詢
nslookup google.com
# 查看監聽 Port
netstat -tuln
# 測試指定 Port 是否可到達
nc -zv -w 5 <target_ip> <port>
```
---
## 日誌
```sh
# 查看系統紀錄
logread
# 即時監控
logread -f
# 最近 50 筆
logread -l 50
# 過濾防火牆相關
logread | grep -i firewall
```
---
## 服務管理
```sh
# 啟動 / 停止 / 重啟
/etc/init.d/<service> start
/etc/init.d/<service> stop
/etc/init.d/<service> restart
# 查看狀態
/etc/init.d/<service> status
# 開機自動啟動 / 停用
/etc/init.d/<service> enable
/etc/init.d/<service> disable
```
---
## 設定備份與還原
```sh
# 備份整個系統設定
sysupgrade -b /tmp/backup-$(date +%Y%m%d).tar.gz
# 還原設定
sysupgrade -r /tmp/backup-YYYYMMDD.tar.gz
# 備份防火牆設定
cp /etc/config/firewall /etc/config/firewall.bak
# 編輯設定檔
vi /etc/config/firewall
```
---
## Taiwan IP 集合管理
```sh
# 重新抓取並更新 Taiwan IP 清單
sh /root/42_10/update_tw_ip.sh
# 確認目前集合內容
nft list set inet fw4 taiwan_ips
# 手動補充單一 IP如 VPS 未被涵蓋)
nft add element inet fw4 taiwan_ips { <ip_address> }
```
**資料來源**`https://www.ipdeny.com/ipblocks/data/countries/tw.zone`
建議搭配 cron 定期執行 `update_tw_ip.sh`,例如每月一次:
```sh
# crontab -e
0 3 1 * * sh /root/42_10/update_tw_ip.sh
```
---
## 防火牆規則驗證
```sh
# 本機執行SSH 進路由器並格式化輸出規則
sh /root/42_10/show_nft_rules.sh
# 驗證台灣 IP 通行、非台灣 IP 攔截
sh /root/42_10/test_connection.sh
```
`test_connection.sh` 會:
1. 查詢目前出口 IP 所在地(透過 `https://ip.lotimmy.com/json`
2.`125.229.110.50` 的指定 Port`51433`, `31433`)發起測試
3. 判斷結果是否符合預期(台灣 IP 應通過,非台灣 IP 應被攔截)
---
## 轉發規則調整
若需移除已失效的 Port 轉發(如原本指向不存在主機),執行:
```sh
sh /root/42_10/remove_mysql_forward.sh
```
手動移除流程:
```sh
# 找出目標規則
ssh root@192.168.42.10 "uci show firewall | grep <port>"
# 刪除並提交
ssh root@192.168.42.10 "uci delete firewall.<rule_id> && uci commit firewall"
# 重載防火牆
ssh root@192.168.42.10 "fw4 restart"
# 確認規則已移除
ssh root@192.168.42.10 "nft list chain inet fw4 dstnat_wan | grep <port>"
```