萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

SecureCRT 中文亂碼徹底解決方案:編碼、字體、伺服器端三層配置指南

前言

SecureCRT 顯示中文亂碼,核心原因只有一個:**終端機編碼與伺服器端實際輸出編碼不一致**。解決需從SecureCRT 客戶端設定、字體支援、Linux/Unix 伺服器端 locale 環境三層同步入手。本文提供完整排查步驟與永久生效配置。

一、SecureCRT 客戶端設定(核心)

步驟 1:設定工作階段編碼為 UTF-8

  1. 開啟 選項 → 工作階段選項 → 終端機 → 外觀
  2. 字元編碼 選擇 UTF-8
  3. 勾選 使用 UTF-8 顯示行繪字元(避免框線字元亂碼)

步驟 2:選擇支援中文的等寬字體

  • Windows:新細明體、Microsoft JhengHei、Consolas + 微軟正黑體(需啟用字體連結)
  • macOS/Linux:Monospace、DejaVu Sans Mono、Noto Sans Mono CJK、Sarasa Mono
  • 字體大小建議 10~14pt,啟用 抗鋸齒。

步驟 3:設為預設值(所有新工作階段自動套用)

  1. 選項 → 全域選項 → 終端機 → 外觀
  2. 同樣設定編碼 UTF-8 與中文字體
  3. 既有工作階段需逐一修改或匯出/匯入 INI 檔批次更新。

二、伺服器端 Locale 環境配置(根本解決)

客戶端設定 UTF-8 後,伺服器端必須實際輸出 UTF-8,否則仍會亂碼。

1. 檢查當前 locale

$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_ALL=
...

2. 產生並設定 zh_TW.UTF-8 / en_US.UTF-8

# Ubuntu/Debian
sudo apt-get install -y locales
sudo locale-gen zh_TW.UTF-8 en_US.UTF-8
sudo update-locale LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8

# CentOS/RHEL/Rocky/Alma
sudo dnf install -y glibc-langpack-zh
sudo localectl set-locale LANG=en_US.UTF-8

# 重新登入或重啟生效
exec bash

3. 臨時測試(不修改系統設定)

export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
# 或
export LANG=zh_TW.UTF-8
export LC_ALL=zh_TW.UTF-8

三、Shell 設定檔永久生效

Bash (~/.bashrc 或 ~/.bash_profile)

export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
export LC_CTYPE=en_US.UTF-8

Zsh (~/.zshrc)

export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

SSH 伺服器端 (/etc/ssh/sshd_config)

AcceptEnv LANG LC_*  # 允許客戶端傳遞 locale 環境變數
# 重啟 sshd
sudo systemctl restart sshd

SSH 客戶端 (~/.ssh/config)

Host *
    SendEnv LANG LC_*

四、常見軟體特定配置

MySQL / MariaDB

[client]
default-character-set = utf8mb4

[mysql]
default-character-set = utf8mb4

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
init_connect = 'SET NAMES utf8mb4'

vim (~/.vimrc)

set encoding=utf-8
set fileencodings=utf-8,ucs-bom,big5,gbk
set termencoding=utf-8

tmux (~/.tmux.conf)

set -g default-terminal "screen-256color"
set -g terminal-overrides ',xterm-256color:Tc'

五、排查檢查清單(由客戶端至伺服器端)

  1. SecureCRT 編碼 = UTF-8?
  2. 字體支援中文?
  3. locale 輸出含 UTF-8?
  4. echo $LANG 非 C 或 POSIX?
  5. cat 中文檔.txt 正常顯示?
  6. mysql -e "SELECT '中文測試'" 正常?
  7. vim 中文檔.txt 正常編輯?

六、進階:檔案編碼轉換工具

# 檢測編碼
file -i filename.txt
enca filename.txt

# Big5/GBK → UTF-8
iconv -f big5 -t utf-8 big5.txt > utf8.txt
iconv -f gbk -t utf-8 gbk.txt > utf8.txt

# 批次轉換
find . -name '*.txt' -exec sh -c 'iconv -f big5 -t utf-8 "$1" > "$1.utf8" && mv "$1.utf8" "$1"' _ {} \;

結語

中文亂碼本質是編碼不一致。遵循 SecureCRT UTF-8 + 中文字體 → 伺服器 locale UTF-8 → Shell 環境變數固定 → SSH 傳遞環境變數 → 資料庫/編輯器/多工器同步設定 的完整鏈路,即可徹底解決。建議將此配置納入伺服器初始化腳本,新機器一鍵到位。

copyright © 萬盛學電腦網 all rights reserved