萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

11 個實用但鮮為人知的 Linux 命令提升運維效率

隱藏神器命令清單

1. sudo !! — 為上一條命令補上 sudo

$ apt-get update
E: Could not open lock file ... Permission denied

$ sudo !!
sudo apt-get update
[sudo] password for user:
# 直接以 root 執行上一條命令

2. python -m SimpleHTTPServer — 秒建 HTTP 檔案服務

# Python 2
python -m SimpleHTTPServer 8000

# Python 3
python3 -m http.server 8000

# 當前目錄即為根目錄,瀏覽器訪問 https://IP:8000
# Ctrl+C 停止

3. mtr — 整合 ping + traceroute 的網路診斷神器

# 安裝
apt-get install mtr    # Debian/Ubuntu
yum install mtr        # RHEL/CentOS

# 使用
mtr google.com
mtr -r -c 10 google.com  # 報告模式,發送 10 個封包

# 關鍵欄位:
# Loss% 丟包率,Snt 發送數,Last/Avg/Best/Wrst 延遲,StDev 標準差

4. Ctrl+X, Ctrl+E — 在編輯器中編輯當前命令列

# 輸入長命令時,按 Ctrl+X 然後 Ctrl+E
# 打開 $EDITOR(vim/nano)編輯
# 存檔離開自動執行

5. nl — 為檔案內容加行號

# 原始檔案
$ cat one.txt
fedora
debian
arch
slack
suse

# 加行號
$ nl one.txt
     1  fedora
     2  debian
     3  arch
     4  slack
     5  suse

# 參數:-ba 為所有行編號(含空行),-bt 僅非空行(預設)

6. shuf — 隨機打亂輸出/抽樣

# 打亂目錄列表
ls | shuf

# 隨機抽取 1 個
ls | shuf -n1

# 隨機抽取 3 個
ls | shuf -n3

# 產生隨機數字
shuf -i 1-100 -n 5  # 1-100 間隨機 5 個不重複數字

# 打亂檔案行順序
shuf file.txt > shuffled.txt

7. ss — 現代 socket 統計工具(替代 netstat)

# 顯示所有 TCP 連線
ss -t -a

# 顯示監聽埠
ss -t -l -n -p

# 顯示連線狀態統計
ss -s

# 過濾特定埠
ss -t -a 'dport = :22'

# 優勢:比 netstat 快、資訊更豐富、支援過濾語法

8. last — 登入歷史稽核

last           # 所有登入記錄
last -n 20     # 最近 20 筆
last -i        # 顯示 IP 而非主機名
last reboot    # 重啟歷史
last -f /var/log/wtmp.1  # 讀取舊日誌檔

9. curl ifconfig.me — 秒查公網 IP

curl ifconfig.me
curl ipinfo.io/ip
curl icanhazip.com
# 都返回公網 IP,適合腳本獲取

10. tree — 目錄樹狀結構視覺化

# 安裝
apt-get install tree / yum install tree

# 使用
tree -L 2           # 只顯示 2 層
tree -d             # 僅目錄
tree -h             # 人類可讀大小
tree -I "node_modules|.git"  # 排除目錄
tree -o output.txt  # 輸出到檔案

11. pstree — 進程樹狀視圖

pstree -p   # 顯示 PID
pstree -u   # 顯示用戶
pstree -a   # 顯示命令參數
pstree -h   # 高亮當前進程
pstree -H PID  # 高亮指定 PID 路徑

效率提升總結

命令核心價值替代傳統方式
sudo !!避免重輸長命令↑ 編輯加 sudo
python -m http.server零配置檔案分享nginx/apache 配置
mtr單工具診斷路徑ping + traceroute
Ctrl+X,E複雜命令舒適編輯命令列直接改
nl快速行號對照cat -n / awk
shuf隨機抽樣/打亂自寫隨機腳本
ss高效連線分析netstat
last登入稽核追蹤手動 grep 日誌
curl ifconfig.me公網 IP 程式化獲取瀏覽器查詢
tree目錄結構可視化ls -R
pstree進程關係一目了然ps -ef 手動分析
copyright © 萬盛學電腦網 all rights reserved