Network - Misc === ###### tags: `OS / Ubuntu / Network` ###### tags: `OS`, `Ubuntu`, `linux`, `command`, `network`, `ssh`, `tunnel`, `curl`, `ip`, `nc`, `netstat`, `route`, `enp2s0`, `rsync` <br> | cmd | package | |-----|---------| | `firewalld` | `apt install firewalld` | | `ifconfig` | `apt install net-tools` | | `ip` | `apt install iproute2` | | `lsof` | `apt install lsof` | | `netstat` | `apt install net-tools` | | `nslookup` | `apt install -y dnsutils` | | `nft` | `apt install nftables` | | `ping` | `apt install -y iputils-ping` | | `route` | `apt install net-tools` | `ss` | `apt install iproute2` | `ufw` | `apt install ufw` | <br> [TOC] <br> # Network ## term - ### [ChatGPT] enp0s3 是什麼?有全名? **`enp0s3`** 是 Ubuntu 中的網路介面名稱,它是根據預設的命名規則命名的。在現代的 Ubuntu 系統中,網路介面名稱通常會使用一個獨特的命名方式,取代了傳統的 **`eth0`**、**`eth1`** 等方式。 網路介面名稱的命名規則是根據 Predictable Network Interface Names 規範來決定的。這樣做是為了確保網路介面在不同系統上的名稱不會因為硬體配置改變而變動,增加網路設定的穩定性。 **`enp0s3`** 的全名是 **`en`** 為 Ethernet,**`p0`** 為 PCI bus 0 上的網路裝置,**`s3`** 為 slot 3,表示這是 PCI bus 0 上的第三個網路裝置。 請注意,網路介面名稱可能因為不同硬體或虛擬環境而有所不同,所以在設定網路時,建議使用 **`ip`** 指令或 **`ifconfig`** 指令查詢實際的網路介面名稱,再根據這個名稱來設定 IP 地址。您可以使用以下指令查詢網路介面名稱: ```bash ip link ``` 或 ```bash ifconfig -a ``` ![](https://hackmd.io/_uploads/SkP3-7Lsn.png) ``` $ ip link 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: enp2s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000 link/ether 5c:92:5e:d1:ea:ac brd ff:ff:ff:ff:ff:ff 3: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000 link/ether 9c:5c:8e:52:b2:34 brd ff:ff:ff:ff:ff:ff 4: wlx74da3864f35f: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DORMANT group default qlen 1000 link/ether 74:da:38:64:f3:5f brd ff:ff:ff:ff:ff:ff 5: gpd0: <POINTOPOINT,MULTICAST,NOARP> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 500 link/none 6: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN mode DEFAULT group default link/ether 02:42:7d:f8:54:d5 brd ff:ff:ff:ff:ff:ff ``` ``` $ ifconfig -a docker0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500 inet 172.17.0.1 netmask 255.255.0.0 broadcast 172.17.255.255 ether 02:42:7d:f8:54:d5 txqueuelen 0 (Ethernet) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 eno1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet6 fe80::a45b:cbcd:d177:b448 prefixlen 64 scopeid 0x20<link> ether 9c:5c:8e:52:b2:34 txqueuelen 1000 (Ethernet) RX packets 5227 bytes 532963 (532.9 KB) RX errors 0 dropped 4614 overruns 0 frame 0 TX packets 28574 bytes 4814544 (4.8 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 device interrupt 20 memory 0xf7d00000-f7d20000 enp2s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 ether 5c:92:5e:d1:ea:ac txqueuelen 1000 (Ethernet) RX packets 397446 bytes 35861743 (35.8 MB) RX errors 0 dropped 93704 overruns 0 frame 0 TX packets 11600 bytes 2168802 (2.1 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 gpd0: flags=4240<POINTOPOINT,NOARP,MULTICAST> mtu 1500 unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 500 (UNSPEC) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 inet6 ::1 prefixlen 128 scopeid 0x10<host> loop txqueuelen 1000 (Local Loopback) RX packets 11060390 bytes 914444850 (914.4 MB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 11060390 bytes 914444850 (914.4 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 wlx74da3864f35f: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 10.78.154.107 netmask 255.255.255.0 broadcast 10.78.154.255 inet6 fe80::bda8:b0b4:a449:1ae7 prefixlen 64 scopeid 0x20<link> ether 74:da:38:64:f3:5f txqueuelen 1000 (Ethernet) RX packets 8398822 bytes 4954339501 (4.9 GB) RX errors 0 dropped 118639 overruns 0 frame 0 TX packets 7690444 bytes 1487603285 (1.4 GB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 ``` - ### gateway4 是什麼? **`gateway4`** 是在 Ubuntu 中用於設定 IPv4 網路介面的預設閘道器(Gateway)的屬性。閘道器是一個網路裝置,它在不同網段之間轉發封包,使得資料能夠在不同網段之間流通。在 IPv4 網路中,每個網段通常都有一個預設閘道器,用於轉發封包到其他網段。 當您的裝置需要連接到其他網段或連接到外部網際網路時,資料包將會先發送到預設閘道器,然後由閘道器轉發到目的地。這樣,您的裝置就能夠與其他網段的裝置通訊。 在 Ubuntu 中,您可以在網路配置檔案中使用 **`gateway4`** 屬性來指定 IPv4 的預設閘道器。在上一個回答中提到的配置檔案範例中,我們使用了以下設定: ```yaml network: version: 2 ethernets: <interface_name>: addresses: [10.78.153.136/24] gateway4: 10.78.153.1 nameservers: addresses: [8.8.8.8, 8.8.4.4] ``` 其中,**`gateway4: 10.78.153.1`** 就是指定了 IPv4 的預設閘道器為 10.78.153.1。 請注意,設定正確的預設閘道器對於網路連線是非常重要的。如果沒有設定正確的預設閘道器,您的裝置可能無法正確連接到其他網段或連接到外部網際網路。確保您的閘道器設定正確且可用,這樣才能順利進行網路連線。 <br> ## Q & A ### 設定 IP 和 switch - ### [ChatGPT] 在 ubuntu , 如何設定 ip 為 10.78.153.136,並將 gateway 設置為 10.78.153.1? 在 Ubuntu 中設定 IP 地址為 10.78.153.136 並將 gateway 設置為 10.78.153.1,您可以使用編輯網路配置檔案的方式來進行設定。以下是使用編輯配置檔案的步驟: 開啟網路配置檔案: ```bash sudo nano /etc/netplan/01-netcfg.yaml ``` 在編輯器中,添加以下配置: ```yaml= network: version: 2 ethernets: <interface_name>: addresses: [10.78.153.136/24] gateway4: 10.78.153.1 nameservers: addresses: [8.8.8.8, 8.8.4.4] # 這裡是示範使用 Google 的 DNS 伺服器,您可以更換為其他 DNS 伺服器 IP 地址 ``` 請將 <interface_name> 替換為您要設定的網路介面名稱。 儲存並關閉檔案後,執行以下指令應用新的配置: ```bash sudo netplan apply ``` 請確保您有適當的權限來執行這些指令(使用 sudo)。儲存並應用配置後,您的網路介面就會被設定為 IP 地址 10.78.153.136,並且 gateway 設定為 10.78.153.1。 請注意,以上範例假設您的子網遮罩為 255.255.255.0(/24),這樣可以將 IP 地址 10.78.153.136 視為同一個網段。如果您的網路環境不同,請根據實際情況調整子網遮罩。另外,nameservers 的部分可以設定為您的 DNS 伺服器 IP 地址,以便正確解析域名。 - ### [ChatGPT] 若要取消 netplan 設定,改用系統預設,要如何操作? 如果您想要取消使用 Netplan 設定並改回使用系統預設的方式來配置網路介面,可以遵循以下步驟: 開啟網路配置檔案: ```bash sudo nano /etc/netplan/01-netcfg.yaml ``` 或者,如果您使用的是舊版的 Ubuntu,可能是: ```bash sudo nano /etc/network/interfaces ``` 將 Netplan 的配置刪除或註解掉:將整個 network 區塊刪除或註解掉。例如,將整個 network 區塊改成下面的形式: ```yaml= # network: # version: 2 # ethernets: # <interface_name>: # ... ``` 或者,在舊版的 Ubuntu 上,將整個 iface 區塊刪除或註解掉。 儲存並關閉檔案後,應用新的配置: ```bash sudo netplan apply ``` 或者,在舊版的 Ubuntu 上,重新啟動網路服務: ```bash sudo service networking restart ``` 這樣您就取消了 Netplan 的配置,改回使用系統預設的方式來設定網路介面。 請注意,取消 Netplan 配置後,網路介面的配置可能回到系統預設,您可能需要檢查 /etc/network/interfaces 檔案(如果存在)或其他網路配置檔案,確保網路介面的設定符合您的需求。請特別注意在取消 Netplan 配置之後,確保網路連線仍然正常運作。 - ### [How to Configure Networking in Ubuntu 20.04 with NetPlan](https://www.serverlab.ca/tutorials/linux/administration-linux/how-to-configure-networking-in-ubuntu-20-04-with-netplan/) - How to Set Static IP Address - How to set DHCP Addresses - How to Set DNS ```yaml= ethernets: en01: [...] nameservers: search: [lab, home] addresses: [8.8.8.8, "FEDC::1"] ``` - **search** is a list of search domains, which are used when a non-fully qualified hostname is given. For example, if you were to ping server1 rather than server1.lab. - **addresses** is a list of IPv4 or IPv6 ip addresses for the DNS name servers. IPv6 must be quoted. - How to set WiFi Authentication - Configuring WPA and EAP WiFi Connections - ### [How to Set the Default Gateway on Ubuntu](https://linuxhint.com/set-default-gateway-ubuntu/) - 永久性生效 ``` $ sudo gedit /etc/netplan/01-network-manager-all.yaml ``` ![](https://hackmd.io/_uploads/SkePZrIo3.png) ``` $ sudo netplan try ``` <br> ### domain to IP ``` $ dig +short stackoverflow.com 151.101.1.69 151.101.129.69 151.101.193.69 151.101.65.69 ``` ``` $ host stackoverflow.com stackoverflow.com has address 151.101.1.69 stackoverflow.com has address 151.101.193.69 stackoverflow.com has address 151.101.65.69 stackoverflow.com has address 151.101.129.69 ``` ``` $ ping stackoverflow.com PING stackoverflow.com (151.101.193.69) 56(84) bytes of data. # ping 只會顯示一筆 IP ``` ``` $ nslookup stackoverflow.com Server: 10.78.26.44 Address: 10.78.26.44#53 Non-authoritative answer: Name: stackoverflow.com Address: 151.101.193.69 Name: stackoverflow.com Address: 151.101.129.69 Name: stackoverflow.com Address: 151.101.1.69 Name: stackoverflow.com Address: 151.101.65.69 ``` ``` $ nmap -sn stackoverflow.com Starting Nmap 7.01 ( https://nmap.org ) at 2022-04-21 18:21 CST Nmap scan report for stackoverflow.com (151.101.65.69) Host is up (0.00055s latency). Other addresses for stackoverflow.com (not scanned): 151.101.129.69 151.101.193.69 151.101.1.69 Nmap done: 1 IP address (1 host up) scanned in 5.52 seconds ``` - [Linux Commands to Translate Domain Name to IP](https://www.baeldung.com/linux/domain-name-to-ip) <br> ## curl ### 指令大全 - [Sending Header with Curl Request](https://reqbin.com/req/c-ea0d5rlb/curl-send-header-example) :+1: :+1: - [Downloading a File with Curl](https://reqbin.com/req/c-egazzayq/curl-download-file) <br> ### noproxy - [How do I make curl ignore the proxy?](https://stackoverflow.com/questions/800805/) ```bash $ curl --noproxy '*' http://www.stackoverflow.com ``` - [Curl does not parse NO_PROXY environment variable same as --noproxy flag as expected #2477](https://github.com/curl/curl/issues/2477) ```bash= $ curl --noproxy "127.0.0.1,localhost" http://127.0.0.1:8080 $ curl --noproxy "127.0.0.1,localhost" http://localhost:8080 # 底下會失敗 $ curl --noproxy "127.0.0.1" http://localhost:8080 $ curl --noproxy "localhost" http://127.0.0.1:8080 ``` <br> ## dig - [Linux command to translate domain name to IP](https://stackoverflow.com/questions/3963085) ``` $ dig +short stackoverflow.com 151.101.1.69 151.101.129.69 151.101.193.69 151.101.65.69 ``` <br> ## firewall-cmd - ### 安裝方式 ``` sudo apt install firewalld ``` - ### 服務狀態確認 ``` # 確認 firewalld 是否在跑 sudo firewall-cmd --state ``` - ### 公網區域(public)臨時開 38888/tcp ``` # 公網區域(public)臨時開 38888/tcp sudo firewall-cmd --zone=public --add-port=38888/tcp ``` - ### 常用操作 ```bash # 看有哪些 Zone sudo firewall-cmd --get-zones # 看預設 Zone sudo firewall-cmd --get-default-zone # 設定預設 Zone(影響未綁定的介面/來源) sudo firewall-cmd --set-default-zone=public # 看哪些 Zone 正在用 & 對應介面/來源 sudo firewall-cmd --get-active-zones # 把介面綁到某 Zone(runtime) sudo firewall-cmd --zone=public --change-interface=ens10f0 # 持久化(建議加 --permanent,再 reload) sudo firewall-cmd --permanent --zone=public --change-interface=ens10f0 sudo firewall-cmd --reload # 在某 Zone 開服務/連接埠 sudo firewall-cmd --zone=public --add-service=ssh sudo firewall-cmd --zone=public --add-port=48888/tcp # 永久化 sudo firewall-cmd --permanent --zone=public --add-port=48888/tcp sudo firewall-cmd --reload # 查看某 Zone 目前完整設定 sudo firewall-cmd --zone=public --list-all ``` <br> ## host - [Linux command to translate domain name to IP](https://stackoverflow.com/questions/3963085) ``` $ host stackoverflow.com stackoverflow.com has address 151.101.1.69 stackoverflow.com has address 151.101.193.69 stackoverflow.com has address 151.101.65.69 stackoverflow.com has address 151.101.129.69 ``` <br> ## hostname - [How to get the hostname from /etc/hostname & DNS domain name?](https://askubuntu.com/questions/836502/) ``` $ hostname -I tj-M52AD-M12AD-A-F-K31AD ``` - [How To Check Your IP Address in Ubuntu [Beginner’s Tip]](https://itsfoss.com/check-ip-address-ubuntu/) ``` $ hostname -I 10.78.154.119 10.78.153.136 192.168.49.1 172.17.0.1 ``` <br> ## ifconfig > `apt install net-tools` <br> ## ip - ### 安裝方式 ```apt install -y iproute2``` - 參考資料 - [在Linux中,如何查找您的IP地址](https://ubuntuqa.com/zh-tw/article/8531.html) - [Docker容器中bash: ip: command not found](https://blog.csdn.net/qq_27706119/article/details/108548839) - ### 查看 ip ``` $ ip addr show ``` - ### 查看路由 ``` $ route -n $ ip route show ``` - ### 新增預設閘道 ```sudo ip route add default via 10.78.153.1 dev eno1``` ```sudo ip route add default via 10.78.26.241 dev eth0``` - ### [刪除預設閘道](https://unix.stackexchange.com/questions/180553/proper-syntax-to-delete-default-route-for-a-particular-interface) 刪除前的狀態 ``` $ route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 10.78.153.1 0.0.0.0 UG 100 0 0 eno1 0.0.0.0 10.78.154.1 0.0.0.0 UG 600 0 0 wlx74da3864f35f 10.0.0.0 10.78.153.1 255.0.0.0 UG 0 0 0 eno1 10.78.153.0 0.0.0.0 255.255.255.0 U 100 0 0 eno1 10.78.154.0 0.0.0.0 255.255.255.0 U 600 0 0 wlx74da3864f35f 169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 docker0 172.16.0.0 10.78.153.1 255.240.0.0 UG 0 0 0 eno1 172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0 172.21.128.230 10.78.153.1 255.255.255.255 UGH 100 0 0 eno1 192.168.0.0 10.78.153.1 255.255.0.0 UG 0 0 0 eno1 203.145.218.0 10.78.154.1 255.255.255.0 UG 0 0 0 wlx74da3864f35f ``` 刪除預設閘道 ``` sudo ip route del default via 10.78.153.1 ``` 刪除後的狀態 ``` $ route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 10.78.154.1 0.0.0.0 UG 600 0 0 wlx74da3864f35f 10.0.0.0 10.78.153.1 255.0.0.0 UG 0 0 0 eno1 10.78.153.0 0.0.0.0 255.255.255.0 U 100 0 0 eno1 10.78.154.0 0.0.0.0 255.255.255.0 U 600 0 0 wlx74da3864f35f 169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 docker0 172.16.0.0 10.78.153.1 255.240.0.0 UG 0 0 0 eno1 172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0 172.21.128.230 10.78.153.1 255.255.255.255 UGH 100 0 0 eno1 192.168.0.0 10.78.153.1 255.255.0.0 UG 0 0 0 eno1 203.145.218.0 10.78.154.1 255.255.255.0 UG 0 0 0 wlx74da3864f35f ``` - ### [ip route add network command examples](https://www.cyberciti.biz/faq/ip-route-add-network-command-for-linux-explained/) ``` ip route add {NETWORK/MASK} via {GATEWAYIP} ip route add {NETWORK/MASK} dev {DEVICE} ip route add default {NETWORK/MASK} dev {DEVICE} ip route add default {NETWORK/MASK} via {GATEWAYIP} ``` 我的範例 ``` $ sudo ip route add 59.124.220.27/32 via 10.78.153.1 $ route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 10.78.154.1 0.0.0.0 UG 600 0 0 wlx74da3864f35f 10.0.0.0 10.78.153.1 255.0.0.0 UG 100 0 0 eno1 10.78.153.0 0.0.0.0 255.255.255.0 U 100 0 0 eno1 10.78.154.0 0.0.0.0 255.255.255.0 U 600 0 0 wlx74da3864f35f 59.124.220.27 10.78.153.1 255.255.255.255 UGH 0 0 0 eno1 ``` 辦公室範例 ```bash= sudo route del default gw 10.78.153.1 sudo route del -net 169.254.0.0 netmask 255.255.0.0 sudo route add -net 169.254.0.0 netmask 255.255.0.0 enp2s0 sudo route add -net 172.16.0.0 gw 10.78.153.1 netmask 255.240.0.0 eno1 sudo route add -net 10.0.0.0 gw 10.78.153.1 netmask 255.0.0.0 eno1 ``` - ### [How To Check Your IP Address in Ubuntu [Beginner’s Tip]](https://itsfoss.com/check-ip-address-ubuntu/) ``` $ ip addr show $ ip a $ curl ifconfig.me ``` - 查網頁 https://ifconfig.me/ - ### [How To Add Route on Linux](https://devconnected.com/how-to-add-route-on-linux/) :+1: :100: - 相關指令 ```bash= $ ip r default via 10.78.154.1 dev wlx74da3864f35f proto dhcp metric 600 10.78.154.0/24 dev wlx74da3864f35f proto kernel scope link src 10.78.154.107 metric 600 169.254.0.0/16 dev wlx74da3864f35f scope link metric 1000 172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1 linkdown 192.168.49.0/24 dev br-663358669efc proto kernel scope link src 192.168.49.1 linkdown ``` <br> ## iptables - ### [ChatGPT] 如何查看 iptables 的 CHAIN INPUT? ``` $ sudo iptables -L INPUT ``` - -L `--list -L [chain [rulenum]]` `List the rules in a chain or all chains` 這個命令將列出目前在 CHAIN INPUT 中設定的 iptables 規則。您可以查看該鏈中的規則、源 IP、目標 IP、端口和動作等相關資訊。如果有設定規則,它們將按照先後順序顯示。 請確保以管理員或具有足夠權限的使用者身份執行該命令,以查看 iptables 規則。 執行結果: ``` $ sudo iptables -L INPUT Chain INPUT (policy ACCEPT) target prot opt source destination ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED,DNAT ACCEPT all -- anywhere anywhere INPUT_direct all -- anywhere anywhere INPUT_ZONES all -- anywhere anywhere DROP all -- anywhere anywhere ctstate INVALID REJECT all -- anywhere anywhere reject-with icmp-host-prohibited ``` --- ``` $ sudo iptables -L INPUT --line-numbers ``` - `--line-numbers` print line numbers when listing 執行結果: ``` $ sudo iptables -L INPUT --line-numbers Chain INPUT (policy ACCEPT) num target prot opt source destination 1 ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED,DNAT 2 ACCEPT all -- anywhere anywhere 3 INPUT_direct all -- anywhere anywhere 4 INPUT_ZONES all -- anywhere anywhere 5 DROP all -- anywhere anywhere ctstate INVALID 6 REJECT all -- anywhere anywhere reject-with icmp-host-prohibited 7 ACCEPT tcp -- anywhere anywhere tcp dpt:38888 ``` - ### [ChatGPT] 我要讓區網的另一台電腦連線<br>目標電腦 ip 是 10.78.153.240, port 是 38888<br>我要如何在目標電腦設定 iptable, 好讓其他台電腦可以連到目標電腦? ```bash # Before $ sudo iptables -L INPUT $ sudo iptables -A INPUT -p tcp --dport 38888 -j ACCEPT # After $ sudo iptables -L INPUT ``` - `-A`: `--append -A chain Append to chain` - `-p`: `--protocol -p proto protocol: by number or name, eg. `tcp'` - `-j`: `-j, --jump target` This specifies the target of the rule; i.e., what to do if the packet matches it. The target can be a user-defined chain (other than the one this rule is in), one of the special builtin targets which decide the fate of the packet immediately, or an extension (see EXTENSIONS below). If this option is omitted in a rule (and -g is not used), then matching the rule will have no effect on the packet's fate, but the counters on the rule will be incremented. 此選項指定規則的目標,即如果封包符合規則,要執行的動作。目標可以是使用者定義的鏈(與此規則所在的鏈不同),也可以是特殊的內建目標,它們立即決定封包的命運,或者是擴充功能(參見下面的擴充功能)。如果在規則中省略此選項(且未使用 -g),則符合該規則對封包的命運不產生影響,但是規則上的計數器將被增加。 - 這個命令將在目標電腦的 iptables 設定中新增一個規則,允許透過 TCP 連接到端口 38888 的連線。 - ### [ChatGPT] 要如何將 CHAIN INPUT 某個規則,提高優先權? 要提高 CHAIN INPUT 中某個規則的優先權,可以使用 iptables 的 --insert(或 -I)參數來插入新規則到指定的位置。以下是一個示例命令: ``` iptables -I INPUT <rule_number> -m <match_criteria> -j <target_action> ``` - `-I`: `--insert <chain_name> <rule_number>` Insert in chain as rulenum (default 1=first) 請替換 - **<rule_number>** 為您要插入的規則的位置 ``` sudo iptables -L INPUT --line-numbers ``` 這個命令將列出 INPUT 鏈中的規則,並顯示它們的編號(行號)。根據需要,您可以選擇在指定的位置使用 -I 參數來插入新規則。 - **<match_criteria>** 為匹配條件 match_criteria 是指您希望用於匹配規則的條件或選項。這可以是以下之一: - `-s <source_ip>`:指定源 IP 地址進行匹配。 - `-d <destination_ip>`:指定目標 IP 地址進行匹配。 - `-p <protocol>`:指定協議進行匹配,例如 TCP、UDP、ICMP 等。 - `--sport <source_port>`:指定源端口進行匹配。 - `--dport <destination_port>`:指定目標端口進行匹配。 - **<target_action>** 為目標動作 **範例1** ``` $ sudo iptables -I INPUT 2 -s 192.168.1.100 -j ACCEPT ``` - `-I INPUT 2` 表示將新規則插入到 INPUT 鏈的第 2 列(位置)。 - `-s 192.168.1.100` 指定來源 IP 地址為 `192.168.1.100` 進行匹配 - `-j ACCEPT` 指定目標動作為接受(ACCEPT)該請求。 **範例2** ```bash $ sudo iptables -I INPUT 6 -p tcp --dport 38888 -j ACCEPT $ sudo iptables -L INPUT --line-numbers Chain INPUT (policy ACCEPT) num target prot opt source destination 1 ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED,DNAT 2 ACCEPT all -- anywhere anywhere 3 INPUT_direct all -- anywhere anywhere 4 INPUT_ZONES all -- anywhere anywhere 5 DROP all -- anywhere anywhere ctstate INVALID 6 ACCEPT tcp -- anywhere anywhere tcp dpt:38888 7 REJECT all -- anywhere anywhere reject-with icmp-host-prohibited ``` - 這邊的 `-m <match_criteria>` 就是 `-p tcp --dport 38888` - ### 如何只允許特定網域(比如 10.78.153.0/24)的電腦連入? ``` $ sudo iptables -A INPUT_direct -s 10.78.153.0/24 -p tcp -j ACCEPT ``` - 讓ip為內網的電腦放行 - 當前設定 ```bash $ sudo iptables --list INPUT_direct Chain INPUT_direct (1 references) target prot opt source destination ACCEPT tcp -- 10.78.153.0/24 anywhere ACCEPT tcp -- 10.80.0.0/16 anywhere ACCEPT tcp -- 172.22.0.0/16 anywhere ``` - ### [ChatGPT] 如何只允許特定網域(比如 10.78.153.0/24)的電腦連入? 若要僅允許特定網域(例如 10.78.155.0/24)的電腦連入,您可以使用以下規則設定: ```shell $ sudo iptables -A INPUT -s 10.78.153.0/24 -m state --state NEW,ESTABLISHED -j ACCEPT $ sudo iptables -A OUTPUT -m state --state ESTABLISHED -j ACCEPT ``` 這些規則中的 -s 10.78.153.0/24 指定了來源 IP 地址為 10.78.153.0/24,表示僅允許該網域的電腦連入。這些規則同時允許所有新的連線(NEW)和已建立的連線(ESTABLISHED)進入或離開您的系統。 請注意,上述的規則僅提供基本的連線控制,並不涵蓋進一步的安全性考量。在實際應用中,建議根據您的需求和安全策略進行更具體的規則設定,例如僅允許特定的服務或應用程式使用特定的端口。同時,也要確保您的網絡配置正確,以便僅允許受信任的網域訪問您的系統。 - ### [ChatGPT] 如何設定 iptables 讓外部的連線都可以連進來? 要設定 iptables 允許外部的連線進入您的系統,您可以透過以下的規則設定來實現: ```shell $ sudo iptables -A INPUT -m state --state NEW,ESTABLISHED -j ACCEPT $ sudo iptables -A OUTPUT -m state --state ESTABLISHED -j ACCEPT ``` 這些規則將允許所有的新連線(NEW)和已建立的連線(ESTABLISHED)進入或離開您的系統。請確保以管理員或具有足夠權限的使用者身份執行這些命令。 請注意,這些規則只是最基本的設定,並不涵蓋進一步的安全性考慮。在實際應用中,建議根據您的需求和安全策略進行更具體的規則設定。 - ### 參考資料 - [Ubuntu Server 如何永久儲存iptables的設定?](https://magiclen.org/ubuntu-server-iptables-save-permanently/) <br> ## lsof > 安裝:`sudo apt-get install lsof` ### `lsof -iTCP:9999 -sTCP:LISTEN -P -n` > 情境:Port 9999: Address already in use,誰用了這個 port ? > - `-i`: select IPv[46] files > - `-P`: no port names > - `-n`: no host names --> numeric - ### gpt-5 (2025/08/22) 下面這條指令會「找出目前正在**監聽** TCP 9999 埠口的行程」: ``` lsof -iTCP:9999 -sTCP:LISTEN -P -n ``` ### 參數說明 * `lsof`:列出系統開啟的檔案(含「網路連線/Socket」)。 * `-iTCP:9999`:只篩選 **TCP 協定**、**埠號 9999** 的連線/Socket。 * 也可寫成 `-i TCP:9999` 或 `-i :9999`(後者不限定 TCP/UDP)。 * `-sTCP:LISTEN`:只顯示 TCP **LISTEN** 狀態(也就是「占著埠在等連線」的服務)。 * 想看已建立連線可用 `-sTCP:ESTABLISHED`。 * `-P`:**不要**把埠號轉成服務名(保留數字,如 9999,不顯示 http、ssh 之類)。 * `-n`:**不要**做 DNS 反查(不把 IP 反查成主機名,查詢更快)。 ### 典型輸出長怎樣(如何讀) ``` COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME python3 21234 root 3u IPv4 ... 0t0 TCP *:9999 (LISTEN) ``` * **COMMAND**:程式名稱 * **PID**:行程號 * **USER**:擁有者 * **FD**:檔案描述符(`u`=讀寫開啟) * **TYPE**:`IPv4` 或 `IPv6` * **NAME**:位址與狀態(`*:9999 (LISTEN)` 代表綁在所有位址的 9999 埠) > 有時會看到兩行:一行 IPv4、一行 IPv6(同一程式以雙協定堆疊方式監聽)。 - **備註**:實際測試結果 ``` COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME python 21553 root 3u IPv4 2520662 0t0 TCP *:9999 (LISTEN) ``` ### 看到 PID 後怎麼關 * 溫和終止: ``` kill -TERM <PID> ``` * 還不下線就強制: ``` kill -KILL <PID> ``` * 一行流(只取 PID 然後關): ``` lsof -tiTCP:9999 -sTCP:LISTEN | xargs -r kill -TERM # 失敗再: lsof -tiTCP:9999 -sTCP:LISTEN | xargs -r kill -KILL ``` ### 常用變體 * 找「誰在用 9999」(不限定 LISTEN,也可能是**連到別人 9999 的用戶端連線**) ``` lsof -i :9999 -P -n ``` * 限定程式名(例如只看 python) ``` lsof -iTCP:9999 -sTCP:LISTEN -c python -P -n ``` * 只顯示 PID(好接其他指令) ``` lsof -tiTCP:9999 -sTCP:LISTEN ``` ### 補充:在容器 vs. 主機 * **容器內**跑 `lsof` 只會看到**容器內**的行程;若找不到,可能是**主機**在占用 9999。這時請到主機執行同樣的 `lsof`(或 `ss -ltnp | grep :9999`)來查 PID 再處理。 <br> ## nc > 測試連線指令 - ### 全名 `nc` 是「netcat」的縮寫,netcat 是一個強大的網路工具,用來在 TCP 或 UDP 之間讀寫資料,常用於連線測試、端口掃描、簡易的伺服器/客戶端模擬等用途。 - ### 範例 ``` $ nc -vz www.google.com 80 Connection to www.google.com 80 port [tcp/http] succeeded! $ nc -vz 10.78.26.241 8080 Connection to 10.78.26.241 8080 port [tcp/http-alt] succeeded! ``` - `-v` Verbose - `-z` Zero-I/O mode [used for scanning] - 沒有 `-z` ``` $ nc -v 10.78.26.241 8080 Connection to 10.78.26.241 8080 port [tcp/http-alt] succeeded! HTTP/1.1 400 Bad Request content-type: text/plain; charset=utf-8 Connection: close Invalid HTTP request received. ``` - ### 為何出現 Invalid HTTP request received? 當你直接用 `nc -v 10.78.26.241 8080` 開一個 TCP 連線,卻沒有送出任何合法的 HTTP 請求(例如請求行、Host 標頭,最後還要以空行結束),伺服器的 HTTP 解析器就會回應 400 並顯示「Invalid HTTP request received」。換句話說,TCP 層連線成功了,但在應用層(HTTP)根本沒看到符合規範的請求訊息,所以才回你錯誤。 --- ### 正確範例 ```bash # 用 printf 將完整 HTTP/1.1 請求送給 nc printf 'GET / HTTP/1.1\r\nHost: 10.78.26.241\r\n\r\n' \ | nc 10.78.26.241 8080 ``` 以上會送出: ``` GET / HTTP/1.1 Host: 10.78.26.241 ``` (注意每行必須以 `\r\n` 結尾,最後還要一個空行告訴伺服器請求結束),這樣伺服器才會回傳正常的 200 OK 或其他有效回應。 --- ### 小結 - **400 Invalid HTTP request** = 伺服器已經收到 TCP 連線,但解析不到合法的 HTTP 請求。 - 使用 `nc` 測試時,必須**手動**輸入或管道送出符合 HTTP 規範的請求行、必要標頭(至少有 Host)及結尾空行。 - 否則就只是在「打開連線」卻沒「講 HTTP 語法」,伺服器自然回 400。 ### [測試] 實際回應結果 ``` HTTP/1.1 404 Not Found date: Thu, 08 May 2025 02:42:19 GMT server: uvicorn content-length: 22 content-type: application/json {"detail":"Not Found"} ``` <br> ## netstat - ### 安裝 ``` apt install net-tools ``` - [netstat or alternative in docker ubuntu server 16.04 container](https://askubuntu.com/questions/813579) - ### 掃目前主機的 port ``` # t: -t|--tcp # -l, --listening display listening server sockets # -n, --numeric don't resolve names # -p, --programs display PID/Program name for sockets $ netstat -tlnp ``` - 範例:[Connection refused when connecting to the exposed port on docker container](https://stackoverflow.com/questions/58454601/https://stackoverflow.com/questions/58454601/) ``` $ sudo netstat -nlp | grep 9999 Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:9999 0.0.0.0:* LISTEN 51064/docker-proxy ``` - 範例:[url (56) Recv failure: Connection reset by peer - when hitting docker container [closed]](https://serverfault.com/questions/769578/) ``` $ sudo netstat -an|grep LISTEN tcp 0 0 0.0.0.0:9999 0.0.0.0:* LISTEN ``` ``` $ netstat -an Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 0.0.0.0:9999 0.0.0.0:* LISTEN Active UNIX domain sockets (servers and established) Proto RefCnt Flags Type State I-Node Path ``` - [好用netstat指令]() - 計算每一個 ip 在主機上建立的連線數量。 ``` netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n ``` - 列出每個 ip 建立的 ESTABLISHED 連線數量。 ``` netstat -ntu | grep ESTAB | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr ``` <br> ## nameserver (DNS Servers) ### 如何測試 DNS Server 是否正常? - ### [How to Configure BIND9 DNS Server on Ubuntu 20.04](https://serverspace.io/support/help/configure-bind9-dns-server-on-ubuntu/) - **`eip.asus.com`** ```sh= $ nslookup eip.asus.com 8.8.8.8 Server: 8.8.8.8 Address: 8.8.8.8#53 ** server can't find eip.asus.com: NXDOMAIN $ nslookup eip.asus.com 10.78.26.44 Server: 10.78.26.44 Address: 10.78.26.44#53 Non-authoritative answer: Name: eip.asus.com Address: 172.20.169.230 $ nslookup eip.asus.com 172.22.44.53 Server: 172.22.44.53 Address: 172.22.44.53#53 Non-authoritative answer: Name: eip.asus.com Address: 172.20.169.230 $ nslookup eip.asus.com 172.22.44.54 Server: 172.22.44.54 Address: 172.22.44.54#53 Non-authoritative answer: Name: eip.asus.com Address: 172.20.169.230 $ nslookup eip.asus.com 172.20.168.53 Server: 172.20.168.53 Address: 172.20.168.53#53 Non-authoritative answer: Name: eip.asus.com Address: 172.20.169.230 $ nslookup eip.asus.com 172.20.168.54 ;; connection timed out; no servers could be reached ``` - `172.20.168.54` 不存在 - dig 指令也可以 ``` $ dig eip.asus.com ``` - **`oneai.twcc.tw`** (https://oneai.twcc.tw) https://oneai.twcc.tw/user/ai_maker/inference/list | DNS Server | Response | | ------------- | --------------- | | 8.8.8.8 | 140.110.147.178 | | 10.78.26.44 | 140.110.147.178 | | 172.20.168.53 | 140.110.147.178 | | 172.20.168.54 | no servers could be reached | | 172.22.44.53 | 140.110.147.178 | - **`cvat.oneai.twcc.tw`** | DNS Server | Response | | ------------- | --------------- | | 8.8.8.8 | no servers could be reached | | 10.78.26.44 | 140.110.147.178 | | 172.20.168.53 | 140.110.147.178 | | 172.20.168.54 | no servers could be reached | | 172.22.44.53 | 140.110.147.178 | ### 如何查看 DNS Servers - ### Ubuntu 20.04 ```bash $ systemd-resolve --status | grep -i "dns server" -A4 ``` - ### 參考資料 - ### [How to set DNS Nameserver on Ubuntu 20.04](https://phoenixnap.com/kb/ubuntu-dns-nameservers) - ### `$ cat /etc/resolv.conf` 亦會顯示如下的指令: ``` $ resolvectl status ``` <br> ### 如何加 DNS Servers - ### Ubuntu 16.04 ```bash= # 添加 DNS (範例) $ sudo nano /etc/network/interfaces #+---------------------+ #| DNS Name Server | (2020/12/18) #+---------------------+ dns-nameserver 172.20.168.53 dns-nameserver 172.20.168.54 dns-nameserver 172.22.44.53 172.22.44.54 dns-search corpnet.asus # 重啟 DNS /etc/init.d/networking restart # 測試 ping ping tp-deep-v01 # 2023/08/21: TP-DEEP-V01.corpnet.asus (172.22.26.21) ``` - 有找到 ```bash= $ ping tp-deep-v01 -c 3 PING tp-deep-v01.corpnet.asus (172.22.26.21) 56(84) bytes of data. 64 bytes from TP-DEEP-V01.corpnet.asus (172.22.26.21): icmp_seq=1 ttl=121 time=9.47 ms 64 bytes from TP-DEEP-V01.corpnet.asus (172.22.26.21): icmp_seq=2 ttl=121 time=9.96 ms 64 bytes from TP-DEEP-V01.corpnet.asus (172.22.26.21): icmp_seq=3 ttl=121 time=10.7 ms ^C --- tp-deep-v01.corpnet.asus ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 6046ms rtt min/avg/max/mdev = 9.466/10.032/10.675/0.496 ms ``` - 找不到 ```bash= $ ping tp-deep-v01 -c 3 ping: tp-deep-v01: Name or service not known ``` - ### Ubuntu 18.04 ```bash= # 添加 DNS (範例) $ sudo nano /etc/netplan/50-cloud-init.yaml nameservers: addresses: [172.22.44.53,172.22.44.54] search: [corpnet.asus] # 重啟 DNS $ sudo netplan apply # 測試 ping $ ping tp-deep-v01 ``` - ### Ubuntu 20.04 (尚未驗證) ```bash= $ cat /etc/network/interfaces # interfaces(5) file used by ifup(8) and ifdown(8) auto lo iface lo inet loopback #+---------------------+ #| DNS Name Server | (2020/12/18) #+---------------------+ dns-nameserver 172.20.168.53 dns-nameserver 172.20.168.54 dns-nameservers 172.22.44.53 172.22.44.54 dns-search corpnet.asus ``` #dns #nameservers #172.20.168.53 #172.20.168.54 #172.22.44.53 #172.22.44.54 - ### Ubuntu 20.04 (可確定) - 使用 wireless 連 ALAB 出不去 (2023/07/25) - /etc/resolv.conf - 添加 nameserver 8.8.8.8 就能連出去 - 即時套用 ```bash= $ cat /etc/resolvconf/resolv.conf.d/head # DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN nameserver 8.8.8.8 ``` ```bash= $ cat /etc/resolv.conf # DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN nameserver 8.8.8.8 nameserver 172.20.168.53 nameserver 172.20.168.54 nameserver 172.22.44.53 search corpnet.asus ``` - ### 參考資料 - ### [How to set DNS Nameserver on Ubuntu 20.04](https://phoenixnap.com/kb/ubuntu-dns-nameservers) - ### [設定 /etc/resolv.conf 檔案](http://dns-learning.twnic.net.tw/bind/intro4.html) - 此檔案可用來設定 DNS 用戶端要求名稱解析時,所定義的各項內容。 - **“domain”** 指定本地的網域名稱,如果查詢時的名稱沒有包含小數點,則會自動補上此處的網域名稱為字尾再送給DNS伺服器。 - **“nameserver”** 指定用戶端要求進行名稱解析的 nameserver IP位址,在此可指定多部DNS伺服器,則用戶端將會依序提出查詢要求。 - **“search”** 這個選項為非必要選項,而功能在於若使用者指定主機名稱查詢時,所需要搜尋的網域名稱。 - ### [How do I add a DNS server via resolv.conf?](https://askubuntu.com/questions/130452/) <br> ### secondary DNS server > #multiple dns servers - ### [How to Configure BIND9 DNS Server on Ubuntu 20.04](https://serverspace.io/support/help/configure-bind9-dns-server-on-ubuntu/) - ### [How to Configure BIND9 as a Secondary DNS Server on Ubuntu 20.04](https://serverspace.io/support/help/bind9-as-a-secondary-dns-server-on-ubuntu/) - ### [How to Install and Configure DNS Server in Linux](https://www.thegeekstuff.com/2014/01/install-dns-server/) <br> ## nftables (Netfilter tables) > - nftables 是 Linux 預設建議的防火牆系統,功能完整。 > - ufw 是 Ubuntu 系的簡化防火牆工具,底層其實還是用 iptables/nftables - ### nftables 全稱是? > by gpt-5 (2025/08/21) nftables 是 Linux **Netfilter** 的新世代封包過濾框架;在核心裡的子系統名稱是 **`nf_tables`**(可理解為 *netfilter tables*),對應的指令是 **`nft`**。 - ### 安裝與使用方式 ``` # 安裝 nftables $ sudo apt install nftables $ sudo nft list ruleset ``` - ### 教學 - [nftables 简明教程](https://www.hi-linux.com/posts/29206.html) <br> ### Ubuntu 常見:iptables 用的是 nft 後端,或是兩套規則不同步 - ### gpt-5 (2025/08/21) > 「Ubuntu 常見:iptables 用的是 **nft 後端**,或是**兩套規則不同步**」 意思是: * **iptables 有兩種後端** * **legacy**:舊的 iptables 模式。 * **nf\_tables(nft)**:新的後端,規則實際存放在 nftables 裡。 * 在 Ubuntu(尤其 20.04+)很常見 **iptables 指令其實是「iptables-nft」**(走 nft 後端)。 但有些環境/套件(或你手動切換)會使用 **iptables-legacy**。 * 如果系統上**同時存在** nft 與 legacy 的規則,而且你查看/修改的是**另一套**,就會出現「看起來放行了,但實際仍被擋」的狀況──這就是「兩套規則不同步」。 換句話說: 你下的 `iptables` 指令**可能改到「沒在用」的那一套表**,真正生效的是另一套,所以封包仍被擋。 --- ### 怎麼確認你現在用哪個後端? ```bash # 1) 看 iptables 版本字樣:會出現 (nf_tables) 或 (legacy) iptables --version # 2) 看 alternatives 指到哪個 binary readlink -f $(command -v iptables) # 3) 如果有 alternatives 機制,會顯示目前設定 sudo update-alternatives --display iptables sudo update-alternatives --display ip6tables sudo update-alternatives --display arptables sudo update-alternatives --display ebtables ``` 典型輸出示例: * `iptables v1.8.x (**nf_tables**)` → 你在用 **nft 後端**。 * `.../iptables-legacy` → 你在用 **legacy 後端**。 > 補充:即使你沒安裝 `nft` 指令,**也可能**是在用 nft 後端;`iptables-nft` 會透過相容層直接寫入 nftables。 --- ### 建議作法:**統一到 nft 後端**(避免不同步) 1. **切換到 nft 後端**(四兄弟一起切:iptables/ip6tables/arptables/ebtables) ```bash # 切到 nft 後端(若 alternatives 可用) sudo update-alternatives --set iptables /usr/sbin/iptables-nft sudo update-alternatives --set ip6tables /usr/sbin/ip6tables-nft sudo update-alternatives --set arptables /usr/sbin/arptables-nft sudo update-alternatives --set ebtables /usr/sbin/ebtables-nft ``` 2. (可選但建議)**安裝 nftables 工具**,方便檢查/偵錯: ```bash sudo apt-get update sudo apt-get install -y nftables # 之後可以用 nft list ruleset ``` 3. **重新加入你需要的放行規則**(現在它會寫到真正生效的表): ```bash # 舉例:允許 10.78.153.0/24 存取 48888/38888 sudo iptables -I INPUT 1 -p tcp -s 10.78.153.0/24 --dport 48888 -j ACCEPT sudo iptables -I INPUT 1 -p tcp -s 10.78.153.0/24 --dport 38888 -j ACCEPT sudo iptables -I OUTPUT 1 -p tcp -d 10.78.153.0/24 --sport 48888 -j ACCEPT sudo iptables -I OUTPUT 1 -p tcp -d 10.78.153.0/24 --sport 38888 -j ACCEPT ``` 4. 驗證**計數器有在跳**(代表命中規則): ```bash watch -n1 'sudo iptables -vnL INPUT | grep -E "48888|38888"; echo; sudo iptables -vnL OUTPUT | grep -E "48888|38888"' ``` --- ### 如果你目前在用 legacy,但 Docker/其他服務用的是 nft 就會出現你看到的情況:你用 `iptables` 插規則無效(因為改到 legacy),而真正擋你的是 nft 規則。 **統一成 nft 後端**後,再加白名單規則,通常就會恢復正常。 需要我幫你看 `iptables --version` 與 `readlink -f $(which iptables)` 的輸出來判斷你現在是哪種組合,並給出對應的一鍵指令嗎? --- ### 測試指令 ``` $ iptables --version iptables v1.8.7 (nf_tables) $ readlink -f $(command -v iptables) /usr/sbin/xtables-nft-multi ``` <br> ## nslookup - ### 安裝方式 ``` $ apt install dnsutils ``` - ### 查詢 domain name 所對應的 IP ``` $ nslookup www.google.com.tw Server: 10.78.26.44 Address: 10.78.26.44#53 Non-authoritative answer: Name: www.google.com.tw Address: 172.217.160.99 Name: www.google.com.tw Address: 2404:6800:4012:1::200 ``` - ### [troubleshooting] 無回應,查不到? - ### 如何查看特定的 DNS server 是否有在運作? ``` $ nslookup google.com 8.8.8.8 $ nslookup google.com 8.8.4.4 # 其他類似用法 $ dig @ip domain $ dig @8.8.8.8 google.com $ dig @8.8.4.4 google.com ``` - ### 用 ping 測主機聯通性 ``` $ ping -c 3 8.8.8.8 $ ping -c 3 172.22.44.53 ``` - ### [情境] DNS server 有回應,也連得到 ``` $ nslookup google.com 172.20.168.53 Server: 172.20.168.53 Address: 172.20.168.53#53 Non-authoritative answer: Name: google.com Address: 142.250.198.78 Name: google.com Address: 2404:6800:4012:6::200e $ ping -c 3 172.20.168.53 PING 172.20.168.53 (172.20.168.53) 56(84) bytes of data. 64 bytes from 172.20.168.53: icmp_seq=1 ttl=251 time=0.283 ms 64 bytes from 172.20.168.53: icmp_seq=2 ttl=251 time=0.300 ms 64 bytes from 172.20.168.53: icmp_seq=3 ttl=251 time=0.277 ms --- 172.20.168.53 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2042ms rtt min/avg/max/mdev = 0.277/0.286/0.300/0.009 ms ``` - ### [情境] DNS server 無回應,也連不到 ``` $ nslookup google.com 172.20.168.54 ;; communications error to 172.20.168.54#53: timed out ;; communications error to 172.20.168.54#53: timed out ;; communications error to 172.20.168.54#53: timed out ;; no servers could be reached $ ping -c 3 172.20.168.54 PING 172.20.168.54 (172.20.168.54) 56(84) bytes of data. From 172.20.161.254 icmp_seq=1 Time to live exceeded From 172.20.161.254 icmp_seq=2 Time to live exceeded From 172.20.161.254 icmp_seq=3 Time to live exceeded --- 172.20.168.54 ping statistics --- 3 packets transmitted, 0 received, +3 errors, 100% packet loss, time 2003ms ``` <br> ## ping > `$ apt install iputils-ping` - demo ``` $ ping www.google.com.tw -c3 PING www.google.com.tw (172.217.160.99) 56(84) bytes of data. 64 bytes from tsa03s06-in-f3.1e100.net (172.217.160.99): icmp_seq=1 ttl=57 time=8.56 ms 64 bytes from tsa03s06-in-f3.1e100.net (172.217.160.99): icmp_seq=2 ttl=57 time=7.76 ms 64 bytes from tsa03s06-in-f3.1e100.net (172.217.160.99): icmp_seq=3 ttl=57 time=9.05 ms --- www.google.com.tw ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2003ms rtt min/avg/max/mdev = 7.758/8.456/9.051/0.532 ms ``` <br> ## route, ifconfig - ### 安裝方式 ```sudo apt install net-tools``` - ### 基礎操作 ``` $ route -n ``` ![](https://i.imgur.com/hwk3yfg.png) - 預設 metric - 10.78.154.1: 101 - 10.78.153.1: 101 - 調高 metric ``` $ sudo ifmetric eno1 100 ``` - [如何在Ubuntu中設置網絡連接的優先級?](https://ubuntuqa.com/zh-tw/article/8377.html) - 設置網絡連接的使用順序 - [How do I set the priority of network connections in Ubuntu?](https://superuser.com/questions/331720/) - ### [Linux下route add route del 用法](https://www.jianshu.com/p/1495b4165b12) - ### [route命令- Linux命令大全教程教學 - 億聚網](https://www.1ju.org/linux/route) - ### [[Win] [教學]手動新增路由表,三網段設定方式](https://a7432186.pixnet.net/blog/post/350239567) #route add del 教學 <br> ## ss > - `ss`: socket statistics > - 安裝:`sudo apt install iproute2 -y` ### intro - ### Google AI 摘要 The ss command in Linux is a utility used to display socket statistics. It provides information about various types of sockets, including TCP, UDP, RAW, DCCP, and Unix domain sockets. It is often considered a modern and faster alternative to the netstat command for monitoring network connections and troubleshooting network-related issues. > Linux 的 `ss` 指令是一個用來顯示通訊端(socket)統計的工具。它提供各種類型通訊端的資訊,包括 TCP、UDP、RAW、DCCP,以及 Unix 網域通訊端。相較於 `netstat`,`ss` 常被視為較新且更快的替代方案,可用於監控網路連線與疑難排解網路相關問題。 ### `ss -tlnp` - ### gpt-4 (2025/06/09) 這條指令的用途是: 👉 **列出目前系統所有正在「監聽」的 TCP 連接(Listening TCP ports)**,並顯示對應的程式與執行緒資訊。 ### 🔍 逐個參數說明: | 參數 | 意義 | |------|------| | `-t` | 只顯示 TCP 連線(TCP 協定)。 | | `-l` | 只顯示正在「監聽」的連接(listening sockets),不是已建立的連線。| | `-n` | 以「數字」顯示 IP 與埠號(不進行主機名或服務名的 DNS 解析)。| | `-p` | 顯示每個連接對應的「行程(process)」資訊(需要 root 權限)。 | --- ### 📌 補充: - 通常這個指令需要 `sudo` 權限才能完整顯示 `-p` 的行程資訊,例如: ``` sudo ss -tlnp ``` - **常用於**: - 檢查某服務是否有啟動並正在監聽特定埠號。 - 偵錯網路連線或 port 被佔用的問題。 --- ### 📘 範例輸出: ``` State Recv-Q Send-Q Local Address:Port Peer Address:Port Process LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=1234,fd=3)) ``` 這表示: - 有一個 `sshd` 程式(pid 為 1234)在所有網卡上監聽 TCP 22 port(SSH)。 <br> ### 「監聽」與「連線」的差別是什麼? - ### gpt-4 (2025/06/09) 這裡的關鍵差異在於 **「監聽 (LISTEN)」** 與 **「連線 (ESTABLISHED)」** 是 TCP 網路通訊中兩個完全不同的狀態。 以下用簡單的方式解釋兩者差異: --- ### 🔊 監聽(LISTEN)是什麼? - 表示某個程式(像是 web server、SSH server)正在**等待連線**。 - 它開了一個 port,在「**等待別人來連我**」。 - 像是你在門口站著等朋友來找你,門是開的,但還沒有人進來。 📌 範例: - `sshd` 正在監聽 port 22,準備接受 SSH 連線。 - `nginx` 正在監聽 port 80,準備接受網頁請求。 --- ### 🔗 連線(ESTABLISHED)是什麼? - 表示已經**有人連進來了**,雙方建立了 TCP 連線。 - 這是雙方成功握手(TCP 3-way handshake)後的狀態。 - 像是朋友已經進門,你們正在聊天中。 📌 範例: - 一個使用者從 IP `192.168.1.100` 透過 SSH 登入了你的主機。 - 你的主機和一個遠端網站正在互傳 HTTP 資料。 --- ### 🔍 指令的差別(以 `ss` 為例): | 指令 | 顯示內容 | |------------------|------------------------------| | `ss -tln` | **監聽中**的 TCP port | | `ss -tn` | **所有 TCP 連線**(已建立) | | `ss -tan` | 所有 TCP 連線(含 LISTEN) | --- ### 總結比喻: | 狀態 | 比喻 | |------------|----------------------------------| | LISTEN | 「店開門等客人」 | | ESTABLISHED| 「客人進來坐下開始點餐」 | 如有需要,我也可以補充其他 TCP 狀態(如 `CLOSE_WAIT`, `TIME_WAIT` 等)。需要嗎? <br> ## tcpdump ``` sudo tcpdump -ni any host 10.78.153.144 and tcp port 38888 -vv ``` - 在所有網路介面上,擷取「與 10.78.153.144 往來、且 TCP 連接埠為 38888」的封包,並用較詳細的輸出顯示。 - 參數說明: * `sudo`:以管理者身分執行(抓封包通常需要)。 * `tcpdump`:封包擷取工具。 * `-n`:不做 DNS/服務名稱解析,直接顯示數字 IP 與連接埠(較快、較準)。 * `-i any`:在所有介面上抓(含 VLAN/虛擬介面)。 * `host 10.78.153.144`:只抓來源或目的 **IP 為 10.78.153.144** 的封包(雙向)。 * `and`:BPF 過濾器的「且」邏輯。 * `tcp port 38888`:只抓來源或目的 **TCP 連接埠為 38888** 的封包(雙向)。 * `-vv`:加強詳細度(比預設更詳盡的標頭欄位、旗標等)。 <br> ## traceroute - ### 用途 - 用來追蹤封包使用的路由(路徑) - Windows 用法 - 使用 tracert (```trace rt```, ```trace route```) - 網路異常檢測 其他用法 - https://lys0604.pixnet.net/blog/post/24094455 - ### 安裝方式 ```sudo apt-get install traceroute``` - ### 操作範例 ```bash $ traceroute www.google.com traceroute to www.google.com (172.217.160.68), 30 hops max, 60 byte packets 1 10.78.153.1 (10.78.153.1) 1.046 ms 1.349 ms 1.337 ms 2 192.168.2.217 (192.168.2.217) 0.924 ms 0.921 ms 0.909 ms 3 192.168.2.213 (192.168.2.213) 6.356 ms 6.353 ms 6.333 ms 4 192.168.2.41 (192.168.2.41) 9.164 ms 9.525 ms 10.051 ms 5 po-channel13.HQ-C6807XL.corpnet.asus (192.168.2.25) 6.225 ms 6.207 ms 6.198 ms 6 * * * 7 * * * 8 * * * 9 * * * 10 * * * 11 * * * 12 * * * 13 * * * 14 * * * 15 * * * 16 * tsa01s09-in-f4.1e100.net (172.217.160.68) 9.549 ms 9.982 ms ``` - 透過內網連到 www.google.com ``` $ traceroute 172.217.160.68 traceroute to 172.217.160.68 (172.217.160.68), 30 hops max, 60 byte packets 1 10.78.153.1 (10.78.153.1) 1.209 ms 1.487 ms 1.455 ms 2 192.168.2.217 (192.168.2.217) 0.976 ms 0.970 ms 0.937 ms 3 192.168.2.213 (192.168.2.213) 6.368 ms 6.337 ms 6.306 ms 4 192.168.2.41 (192.168.2.41) 7.560 ms 7.776 ms 7.995 ms 5 po-channel13.HQ-C6807XL.corpnet.asus (192.168.2.25) 6.133 ms 6.093 ms 6.379 ms 6 * * * 7 * * * 8 * * * 9 * * * 10 * * * 11 * * * 12 * * * 13 * * * 14 * * * 15 * * * 16 * tsa01s09-in-f4.1e100.net (172.217.160.68) 11.531 ms 9.936 ms ``` - 透過外網連到 www.google.com ```bash $ traceroute 172.217.160.68 traceroute to 172.217.160.68 (172.217.160.68), 30 hops max, 60 byte packets 1 10.78.154.1 (10.78.154.1) 2.062 ms !H 2.502 ms !H 2.698 ms !H ``` <br> ## ufw > - nftables 是 Linux 預設建議的防火牆系統,功能完整。 > - ufw 是 Ubuntu 系的簡化防火牆工具,底層其實還是用 iptables/nftables > - ufw: Uncomplicated Firewall (簡單的防火牆) 的管理工具 ``` # 安裝 UFW $ sudo apt install ufw $ sudo ufw status Status: inactive ``` <br> ## VPN / L2TP ### Ubuntu 18.04 - ### 預設沒有 UI ![](https://i.imgur.com/FjgzFdl.png) 安裝完後: ![](https://i.imgur.com/Iht63Wx.png) - ### [【隨筆】Ubuntu 18.04 的 VPN(L2TP/IPsec) 設定](https://dotblogs.com.tw/shaynling/2020/08/05/233356) 1. 安裝套件 ```bash= sudo apt-get update sudo apt-get install network-manager-l2tp sudo apt-get install network-manager-l2tp-gnome ``` - ### Diatango 版本 ```bash= sudo add-apt-repository ppa:nm-l2tp/network-manager-l2tp sudo apt-get update sudo apt-get install network-manager sudo apt-get install network-manager-l2tp-gnome ``` - 我是這樣下指令,然後重開機 <br> ## net 故障排除 - `System policy prevents modification of personal network settings` - `System policy prevents Wi-Fi scans` - [Remove sudo password when connecting to *new* WiFi network](https://askubuntu.com/questions/244567/) <br> <hr> <br> # remote ## curl - [[HackMD] [Ubuntu] Swagger & curl & postman & python requests](/u63AQ0dVQVOM69407jn9GQ) - [Linux Curl Command 指令與基本操作入門教學](https://blog.techbridge.cc/2019/02/01/linux-curl-command-tutorial/) <br> ## rsync :::warning :bulb: ``` rsync -Ppzr my_folder/ user@host:/path/to/destination/ ``` - 目錄分隔符號 `/`:在 `my_folder` 之後加上 `/` 表示只同步目錄內容,而不是將目錄本身也同步過去。 - 遠端路徑:同樣地,在遠端目錄結尾也加上 `/`,以明確地將檔案同步到該目錄下。 - 補充建議: 若目標端的目錄不存在並且你無法使用 `--mkpath`,可以在遠端手動建立目錄,或使用 SSH 先建立: ```bash ssh user@host 'mkdir -p /path/to/destination/' ``` ::: - [Linux 使用 rsync 遠端檔案同步與備份工具教學與範例](https://blog.gtwang.org/linux/rsync-local-remote-file-synchronization-commands/) - 範例1:帶 -i identity_file ``` $ rsync -e 'ssh -i /home/tj/Asus/software/parabricks/alpr_twcc_key.pem' --progress -zh /home/tj/Asus/workplace/genomes/tools/everythings-misc.zip ubuntu@203.145.218.3:/mnt/parabricks/ ``` - ```-e``` `-e, --rsh=COMMAND` specify the remote shell to use - `-e 'ssh -i xxx.pem'` - [使用 ssh key pair登入Server](https://medium.com/@justin928501/82100e0b711f) - `-e 'ssh -port xxx'` - [rsync + ssh 使用不同 port 執行](https://blog.longwin.com.tw/2012/10/rsync-ssh-different-port-2012/) - ```--progress``` 效果 無進度列 ``` everythings-misc.zip ``` 有進度列 ``` everythings-misc.zip 80.87M 0% 724.87kB/s 28:50:16 ``` - ```-z, --compress compress file data during the transfer``` 壓縮檔案後再上傳 - ```-h``` 檔案大小,易讀 ``` 39,780,352 0% 2.87MB/s 7:07:29 ``` 檔案大小,不易讀 ``` 37.93M 0% 2.87MB/s 7:07:29 ``` - ```--append append data onto shorter files``` ```--partial keep partially transferred files``` - [[Mac/Linux] 使用 rsync --partial --append 續傳大檔案](https://ephrain.net/maclinux-%E4%BD%BF%E7%94%A8-rsync-partial-append-%E7%BA%8C%E5%82%B3%E5%A4%A7%E6%AA%94%E6%A1%88/) - `--partial` 連線中斷時,保留不完整的檔案 - `--append` 續傳不完整的檔案 <br> :::warning :bulb: **換句話說:不中斷+續傳** - `--partial`: 不中斷 斷線後,檔案不完整,只有一部分,不要砍掉 - `--append`: 續傳 繼續附加檔案後半部 ::: - `-r --recursive recurse into directories` 遞迴子目錄 - **範例2** ```bash= $ rsync -e 'ssh -i parabricks-test_key.pem' \ --progress -zh --partial --append \ WGS-LIS-AI018A_R* \ azureuser@70.37.107.238:/mnt/parabricks ``` - **範例3** ```bash= $ rsync -e 'ssh -p 30148' \ --progress -zh --partial --append \ WGS-LIS-AI018A_R* \ root@ctnservice.oneai.twcc.ai:/workspace/datasets ``` - 安裝 ssh 注意事項 ``` $ apt install -y openssh-server $ echo "PermitRootLogin yes" >> /etc/ssh/sshd_config $ echo "root:$PASSWORD" | chpasswd $ service ssh start # test login $ ssh -p 30148 root@ctnservice.oneai.twcc.ai ``` - **Q & A** - ### [rsync 執行時出現 remote command not found](https://xyz.cinc.biz/2016/08/rsync-remote-command-not-found.html) ``` rsync: connection unexpectedly closed (0 bytes received so far) [Receiver] rsync error: remote command not found (code 127) at io.c(226) [Receiver=3.1.2] ``` ``` $ rsync -e "ssh -p 30148" --progress --partial --append -zh D15780_S13_L001_R* root@ctnservice.oneai.twcc.ai:/workspace/datasets root@ctnservice.oneai.twcc.ai's password: bash: rsync: command not found rsync: connection unexpectedly closed (0 bytes received so far) [sender] rsync error: error in rsync protocol data stream (code 12) at io.c(235) [sender=3.1.3] ``` - A: `$ apt install rsync` - ### 是否有 `-a` 就不需要 `-r`? 是的,`-a` (archive) 模式已經包含了 `-r` (recursive) 的功能,因此如果使用了 `-a`,就不需要再單獨指定 `-r`。 具體來說,`-a` 模式包括以下選項: - `-r`:遞迴,傳輸目錄及其內容。 - `-l`:複製符號連結。 - `-p`:保持檔案的權限。 - `-t`:保持檔案的時間戳。 - `-g`:保持檔案的群組。 - `-o`:保持檔案的擁有者(需要有權限)。 - `-D`:保持設備檔案和其他特殊檔案。 因此,當你使用 `-a` 參數時,`-r` 已自動包含在內,你可以省略 `-r`。 <br> ## ssh - 遠端連線軟體 - PieTTY - http://macp.ro/pietty - https://sites.google.com/view/pietty-project - XShell - [How to Enable SSH on Ubuntu 18.04](https://linuxize.com/post/how-to-enable-ssh-on-ubuntu-18-04/) - [How to Enable SSH on Ubuntu 20.04](https://linuxize.com/post/how-to-enable-ssh-on-ubuntu-20-04/) ```bash= # install openssh-server package sudo apt update sudo apt install openssh-server # verify the ssh status sudo systemctl status ssh # 或是 sudo service ssh status # {start|stop|restart|status} ``` - [Ubuntu Linux: Start, Stop, Restart, Reload OpenSSH Server](https://www.cyberciti.biz/faq/howto-start-stop-ssh-server/) - in docker, for docker - [SSH启动报错:Missing privilege separation directory: /run/sshd](https://blog.csdn.net/Magic_Ninja/article/details/88068764) ``` # 建立一個目錄 mkdir /run/sshd # 再啟動 sshd /usr/sbin/sshd # 檢查狀態 service ssh status ``` - 建立 /run/sshd 目錄? ``` # /usr/sbin/sshd Missing privilege separation directory: /run/sshd <--- 此指令需要建立 /run/sshd 目錄 # /etc/init.d/ssh start * Starting OpenBSD Secure Shell server sshd [ OK ] # service ssh start * Starting OpenBSD Secure Shell server sshd ``` - 結論 只有 `/usr/sbin/sshd` 指令需要建立 /run/sshd 目錄 - [想用 SSH 連線到 Docker container](https://bingdoal.github.io/deploy/2021/02/use-ssh-connect-on-docker-container/) - 安裝 ssh ``` apt update apt install openssh-server -y ``` - 設定密碼 ``` passwd root ``` - [Linux命令之passwd、chpasswd](https://www.cnblogs.com/diantong/p/9889034.html) - 設定 ssh ``` echo "Port 22" >> /etc/ssh/sshd_config echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config echo "PermitRootLogin yes" >> /etc/ssh/sshd_config ``` - Dockerfile ```dockerfile= FROM ubuntu:18.04 RUN apt update RUN apt install openssh-server -y RUN echo 'root:password' | chpasswd RUN echo "Port 22" >> /etc/ssh/sshd_config RUN echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config RUN echo "PermitRootLogin yes" >> /etc/ssh/sshd_config EXPOSE 22 CMD /etc/init.d/ssh restart ``` - /etc/ssh/sshd_config - 圖形化用戶介面(GUI)」之參數 - [透過 SSH 連線,開啟遠端的「圖形化用戶介面(GUI)」程式](https://sibsaidinblog-tw.blogspot.com/2012/09/ssh.html) - [解決「透過 SSH 連線,開啟遠端『圖形化用戶介面(GUI)』程式』失敗的問題](https://sibsaidinblog-tw.blogspot.com/2015/10/ssh-gui-x11uselocalhost.html) ``` X11Forwarding yes #X11DisplayOffset 10 X11UseLocalhost no ``` - 備註: 1. `X11Forwarding` 預設為 yes 2. 要添加的只有:`X11UseLocalhost no` 3. ssh 指令要加上 -X 4. gedit 效果 ![](https://i.imgur.com/Qzbki3M.png) 5. 未啟用 GUI 效果 ``` $ gedit README.md Unable to init server: Could not connect: Connection refused (gedit:2770): Gtk-WARNING **: 17:56:06.087: cannot open display: ``` - [SSH X11 Forwarding](http://cypresslin.web.fc2.com/Memo/M-SSH.html) > 由於在Linux的環境下,圖形介面是以X Server為基礎來進行顯示的,所以當我們以一般command-line模式連入時將會無法看到圖形介面,需要另外在本機啟動X Server,讓主機能將圖形介面送過來。 > > 而X11的資料傳輸是採明碼傳輸的方式,因此比較沒那麼安全,透過SSH進行X11 forwarding的主要目的就是將主機要送過來的圖形介面加密後,透過SSH這通訊協定加密再傳到使用者端並顯示在使用者端的 X Server上,以達到保護資料的作用(這也稱為SSH Tunneling)。 > - `X11Forwarding yes` - `X11DisplayOffset 10` - `X11UseLocalhost yes` - [ASUS] ngc-image / ngcTritonserver - [start_ssh.sh](http://10.78.26.44:30000/cloud_infra2/ngc-image/-/blob/runtime/ngctensorflow/ngcTritonserver/system_space/docker/start_ssh.sh) - [Dockerfile](http://10.78.26.44:30000/cloud_infra2/ngc-image/-/blob/runtime/ngctensorflow/ngcTritonserver/system_space/docker/Dockerfile) - [ASUS] AI_Maker_Template / ML_AI_Maker - [[add] add ssh server](http://10.78.26.44:30000/ai_maker_template/ml_ai_maker/-/commit/c28a1e0167371afb6186c443844dfe7166a996a0) - ### ssh 服務指令 (#sshd) (從上面的操作蒐集而來) ```bash # verify the ssh status $ sudo systemctl status ssh # or: # ssh {start|stop|restart|status} $ sudo service ssh status # or: # ssh {start|stop|reload|force-reload|restart|try-restart|status} $ sudo /etc/init.d/ssh status # start | restart $ sudo service ssh restart # {start|stop|restart|status} $ sudo /etc/init.d/ssh restart $ sudo /usr/sbin/sshd -D ``` - [`-D` (daemon, block 當前的 process)](https://www.ssh.com/academy/ssh/sshd) > -D Do not detach and become daemon. This is often used when sshd is run using systemd. This allows easier monitoring of the process in such environments. Without this option, the SSH server forks and detaches from terminal, making itself a background daemon process. The latter has been the traditional way to run the SSH server until recently. Many embedded systems would still use the latter. - [Ubuntu 如何讓兩台 VirtualBox 的 Ubuntu Guest 虛擬機器互相連通 ?](https://www.arthurtoday.com/2010/10/ubuntu-virtualbox-ubuntu-guest.html) - [ Ubuntu Guest 設定 Host Only + NAT 網卡連通內外網路](https://www.arthurtoday.com/2013/07/ubuntu-guest-enables-nat-and-hostonly-adapter.html) <br> ### ssh / scp - ### demo ``` scp -P 30922 -r images root@10.78.26.20:~/tjdataset ``` - ```-P port``` - ```-r``` Recursively copy entire directories. Note that scp follows symbolic links encountered in the tree traversal. - ### [將檔案由本機複製到遠端主機](http://note.drx.tw/2008/03/ubuntuscp-part1.html) ``` # scp -i identity_file src_file remote:/path/dest_file ``` - `-i identity_file` Selects the file from which the identity (private key) for public key authentication is read. This option is directly passed to - 實際範例 ```bash $ scp -i parabricks.pem \ parabricks.tar.gz \ ubuntu@18.139.225.37:/workspace ``` - scp: /parabricks.tar.gz: Permission denied 權限問題,/workspace 是 `root`,上傳的 user 為 `ubuntu` ``` $ sudo chown -R $(id -u):$(id -g) /workspace/ ``` ### ssh / port-forward (tunnel) - [關於 SSH Tunnel 連線 (SSH Proxy, SSH Port Forwarding)](https://yu-jack.github.io/2019/01/08/ssh-tunnel/) - 摘要 - 需求 - 連線到遠端,比如 Ubuntu Server 版、TWCC、AWS、VirtualBox 等 VM,無法使用網頁瀏覽器觀看,只能用 curl, wget 測試 - 如果是 kuard 伺服器 也無法和 liveness probe, readiness probe 互動 - 如何解決 - 建立 SSH Tunnel,就是類似 port-forwarding 的效果 - 是異地主機的 port-forwarding - 操作說明 - 將本機端的 port 8080,導向到遠端的 port 30080 - i.e. 建立通道:```本機端:8080 -> 遠端:30080``` - 就可以透過本機端的8080,用瀏覽器瀏覽遠端的 30080 - 實際操作 ```bash # Step 1: 開啟遠端的 terminal (第1個terminal) $ kubectl run tj-kuard --image=gcr.io/kuar-demo/kuard-amd64:1 --port=8080 pod/tj-kuard created # Step 2: 開啟遠端的 terminal (第2個terminal) $ kubectl port-forward pod/tj-kuard 30080:8080 Forwarding from 127.0.0.1:30080 -> 8080 # Step 3: 開啟本地端的 terminal (第3個terminal),建立 ssh tunnel $ ssh xxx@10.78.26.241 -L 8080:localhost:30080 # Step 4: 開啟本地端的瀏覽器,連線到 http://localhost:8080/ ``` ![](https://i.imgur.com/G5eSBcM.png) - 參數說明 `-L [bind_address:]port:host:hostport` `-L [bind_address:]port:remote_socket` `-L local_socket:host:hostport` `-L local_socket:remote_socket` > Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side. > > This works by allocating a socket to listen to either a TCP port on the local side, optionally bound to the specified bind_address, or to a Unix socket. > > Whenever a connection is made to the local port or socket, the connection is forwarded over the secure channel, and a connection is made to either host port hostport, or the Unix socket remote_socket, from the remote machine. <br> - K8s 範例:[/kD5ynMNsRH-TWq9KUwXfCQ#kubectl-port-foward](/kD5ynMNsRH-TWq9KUwXfCQ#kubectl-port-forward) - [列出目前有的 SSH tunnel](https://xenby.com/b/269-教學-透過-ssh-tunnel-將伺服器內部服務綁定到本機電腦上) ``` # list open files lsof -i -n | egrep '\<ssh\>' ``` - `-n`: inhibits the conversion of network numbers to host names for network files. ![](https://i.imgur.com/2DHtS65.png) - `-i`: selects the listing of files any of whose Internet address matches the address specified in i. (跟 internet 有關的開檔,而不是所有的開檔) - man ssh ``` -L [bind_address:]port:host:hostport Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side. -R [bind_address:]port:host:hostport Specifies that connections to the given TCP port or Unix socket on the remote (server) host are to be forwarded to the local side. ``` - [關於 SSH Tunnel 連線 (SSH Proxy, SSH Port Forwarding)](https://yu-jack.github.io/2019/01/08/ssh-tunnel/) - 把 server 上的 80 port 網頁服務導入到本地端的 8080 port ``` ssh -L 8080:localhost:80 root@127.0.0.1 ``` - 在本地端起了一個 8080 port 的服務 如果要在 server 上 6666 port 讀取的話可以透過以下方式取得! ``` ssh -R 6666:localhost:8080 root@127.0.0.1 ``` - [利用 SSH Tunnel 做跳板(aka. 翻牆)](https://blog.rex-tsou.com/2017/10/利用-ssh-tunnel-做跳板aka.-翻牆/) ```bash # syntax: ssh -L local_port:remote_address:remote_port username@server.com # 經過 ssh://localhost:2323 的連線,會藉由 serverB 作為跳板,再連到 ptt.cc:22 [user@serverA]$ ssh -NfL 2323:ptt.cc:22 user@serverB # 連線 [user@serverA]$ ssh bbsu@localhost -p 2323 ``` ![](https://i.imgur.com/U6L6noA.png) - [SSH Tunneling (Port Forwarding) 詳解](https://johnliu55.tw/ssh-tunnel.html) > SSH Tunneling 就是指利用 SSH 協定來建立這個隧道,所以不但能加密你的通訊,如果中間設有防火牆擋掉某些特定 Port 的連線(例如 HTTP/HTTPS 的 80/443)而沒有擋下 SSH 的 Port 22,這個隧道便會讓防火牆認為是只是一般的 SSH 連線,進而放行,也就達到了「穿透防火牆」的效果。 ![](https://i.imgur.com/3XHerd1.png) - [SSH Tunneling and Proxying](https://www.baeldung.com/linux/ssh-tunneling-and-proxying) ![](https://i.imgur.com/9j3Uwtj.png) 4. **Forward TCP Tunnels** A forward or direct TCP tunnel is the one that follows the direction of the SSH connection from the client to the SSH server. <br> ### ssh / proxy - [SSH Through or Over Proxy](https://daniel.haxx.se/docs/sshproxy.html) - [使用 SSH ProxyCommand/ProxyJump 來連上內網主機](https://city.shaform.com/zh/2017/10/28/ssh-proxycommand/) <br> ### ssh / config - ### [Windows][WSL] 在沒有吐出 log 情況下,很容易被踢出去就斷線 [解決方案] 1. **調整 WSL 中的 SSH 客戶端 KeepAlive 設定** 通過配置 SSH 客戶端以定期發送 keepalive 消息,可以防止連線因不活動而超時。 - **操作步驟**: 1. 打開 WSL 終端:啟動您的 WSL 終端。 2. 編輯 SSH 配置文件:打開或創建 SSH 客戶端配置文件: ```bash nano ~/.ssh/config ``` 3. 添加 KeepAlive 設定:插入以下內容: ```bash Host * ServerAliveInterval 60 ServerAliveCountMax 5 ``` - ServerAliveInterval 60:每 60 秒發送一次 keepalive 包。 - ServerAliveCountMax 5:在沒有響應的情況下,允許客戶端發送 5 次 keepalive 消息,然後才斷開連線。 4. 保存並退出:按 CTRL + O 保存,CTRL + X 退出。 2. **修改 AWS 上的 SSH 服務器設定(如果可能)** 如果您有 AWS 實例的管理權限,可以調整服務器端的 keepalive 配置。 1. 編輯 sshd 配置文件: ```bash sudo nano /etc/ssh/sshd_config ``` 2. 添加或修改以下內容: ```bash ClientAliveInterval 60 ClientAliveCountMax 5 ``` 3. 重啟 SSH 服務: ```bash sudo systemctl restart sshd ``` - ### 保持連線方式(未驗證) `ssh -o ServerAliveInterval=300 xxx@10.78.26.241` - **`-o option`** Can be used to give options in the format used in the configuration file. This is useful for specifying options for which there is no separate command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). - **`man ssh_config`** - **`ServerAliveInterval`** Sets a timeout interval in seconds after which if no data has been received from the server, ssh(1) will send a message through the encrypted channel to request a response from the server. The default is 0, indicating that these messages will not be sent to the server, or 300 if the BatchMode option is set (Debian-specific). ProtocolKeepAlives and SetupTimeOut are Debian-specific compatibility aliases for this option. <br> ## openssh ### 升版 - ### 將 openssh version 升版至 9.7 的過程 (by Diatango) https://ftp.fau.de/pub/OpenBSD/OpenSSH/portable/ 從網站下載 openssh-9.7p1.tar.gz 解壓縮並進行編譯 ``` $> tar zxvf openssh-9.7p1.tar.gz $> cd openssh-9.7p1 $> ./configure --prefix=/usr --sysconfdir=/etc/ssh --with-zlib $> make clean; make $> sudo make install ``` 安裝後, 執行指令確認既有 sshd_config 內容是否有過時的參數 ``` $> /usr/sbin/sshd -t -f /etc/ssh/sshd_config ``` 註: 我遇到 UsePAM yes 這個不支援, 就把它 mark 掉 重新啟動 ssh server ``` $> sudo systemctl restart ssh ``` ssh 版本是否已成功升級 ``` $> telnet 0 22 # 查看訊息是否出現 9.7 版號 $> /usr/sbin/sshd -V # 確認執行檔版本 ``` 其它要修改的地方 ``` $> chmod 644 ~/.ssh/authorized_keys # 新版的權限要求更嚴格, 要將此檔案設成 644, Client 端才能以pubkey連線進來 $> vim /etc/ssh/ssh_config # 註解掉 GSSAPIAuthentication yes 這行 ``` <br> ## ssh-keygen - 產生 rsa ```bash $ ssh-keygen # 不帶任何參數 ``` - 產生 ed25519 ```bash $ ssh-keygen -t ed25519 ``` - [選擇 SSH key 的加密演算法](https://medium.com/@honglong/70ca45c94d8e) - key type - dsa - ecdsa - ed25519 - rsa - rsa1 - DSA 和 RSA 都是基於對兩個極大質數乘積作質因數分解的困難度,細節可見 practical difficulty。 - ECDSA, ED25519 則是基於橢圓曲線的離散對數問題。 <br> - [升級你的 SSH 金鑰!](https://calvertyang.github.io/2016/10/05/upgrade_your_ssh_keys/) (待消化) <br> - 直接登入到遠端 ssh server - 作法 - 顯示本機端的 key ``` $ cat id_ed25519.pub ssh-ed25519 AAAAC......BLL5KG tj@tj-VirtualBox ``` - 將 key 登錄到遠端機器的 authorized_keys 檔案 位於 `~/.ssh/authorized_keys`,在該檔案中新增該 key 的資訊 - 參考資料 - [How to add RSA key to authorized_keys file?](https://stackoverflow.com/questions/12392598/) - [How to Add a Comment to an existing SSH Public Key](https://nixcp.com/add-comment-to-existing-ssh-public-key/) <br> ## file browser - 在網址列上輸入 ``` ssh://ubuntu@203.145.218.3/mnt ``` 通常就會轉成 ``` sftp://ubuntu@203.145.218.3/mnt ``` - 參考資料 - [Browse files on a server or network share](https://help.ubuntu.com/stable/ubuntu-help/nautilus-connect.html.en) ### ssh / Q&A - [How to Fix SSH Failed Permission Denied (publickey,gssapi-keyex,gssapi-with-mic)](https://phoenixnap.com/kb/ssh-permission-denied-publickey) ``` $ ssh tj_tsai@ln01.twcc.ai ##################################################### # # # WELCOME TAIWANIA 2 # # # # The OTP mechanism has been updated # # # # Please type the password and OTP separately # # # # NOTICE : # # If you make a typo in your username, # # you will be refused to login immediately # # # ##################################################### tj_tsai@ln01.twcc.ai: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,keyboard-interactive). ``` <br> ## file system ### cifs (Common Internet File System) - 掛載指令 - 失敗情況: ```bash mkdir cifs sudo mount -t cifs -o username="$CIFS_USER",password="$CIFS_PASSWORD" //10.78.26.44/AMACS_Shared/ai-template/ ./cifs ``` - 成功情況,拿掉password,並加上vers ```bash mkdir cifs sudo mount -t cifs -o username="$CIFS_USER",vers=1.0 //10.78.26.44/AMACS_Shared/ai-template/ ./cifs ``` - Q&A - [解決 mount: cannot mount block device read-only 問題](http://i-pogo.blogspot.com/2010/03/mount-cannot-mount-block-device-read.html) ```bash #舊版安裝方式,已被捨棄 # sudo apt-get install smbfs #新版安裝方式 sudo apt-get install cifs-utils ``` - 卸載指令 ```bash sudo umount cifs ``` - 參考資料 - [Linux 下幾種網芳/Samba 目錄的 mount 方式](http://www.vixual.net/blog/archives/228) <br> ### 分割檔案,方便傳輸 - [Linux 使用 split 指令將大檔案切割成小檔案,方便網路傳輸](https://blog.gtwang.org/linux/split-large-tar-into-multiple-files-of-certain-size/) - `-b, --bytes=SIZE` > put SIZE bytes per output file - `-b 200M` - `-b 30G` (33GB => 30GB + 3GB) - `-a, --suffix-length=N` > generate suffixes of length N (default 2) - `-a 1` => a, b, c, ... - `-a 2` => aa, ab, ac, ... (預設) - `-a 3` => aaa, aab, aac, ... - `-d` > use numeric suffixes starting at 0, not alphabetic - `-n, --number=CHUNKS` > generate CHUNKS output files; see explanation below - `-n 2` => 拆成 2 個檔案 - `-n 3` => 拆成 3 個檔案 - 使用 cat 合併檔案 `cat datafolder.part* > datafolder.tar.gz` <br> <hr> <br> # proxy ## Ubuntu 20.04 - [How to Configure Proxy Settings on Ubuntu 20.04](https://phoenixnap.com/kb/ubuntu-proxy-settings) - `bashrc` ```bashrc export HTTP_PROXY="[username]:[password]@[proxy-web-or-IP-address]:[port-number]" export HTTPS_PROXY="[username]:[password]@[proxy-web-or-IP-address]:[port-number]" export FTP_PROXY="[username]:[password]@ [proxy-web-or-IP-address]:[port-number]" ... export NO_PROXY="localhost,127.0.0.1,::1" ``` ![](https://i.imgur.com/tHCphzz.png)