博客 / 詳情

返回

第一章—Linux新手入門:從零開始的初始化配置指南

初學linux得一些初始化配置詳細步驟

1. 配置SSH(遠程連接)

CentOS/Rocky Linux

① 編輯SSH配置文件

vim /etc/ssh/sshd_config

② 配置SSH登錄方式

# 允許root登錄(學習環境)
PermitRootLogin yes

# 生產環境建議使用密鑰登錄,禁用密碼登錄
# PasswordAuthentication no
# PubkeyAuthentication yes

③ 重啓SSH服務

systemctl restart sshdS

Ubuntu

① 安裝SSH服務

# 檢查SSH狀態
systemctl status sshd

# 安裝OpenSSH服務端
apt install openssh-server

# 啓動SSH服務
systemctl start ssh

# 設置root密碼
passwd root

② 配置SSH(同CentOS)

編輯 /etc/ssh/sshd_config 並重啓服務:

systemctl restart ssh

SSH安全加固(擴展)

# 修改默認端口(可選)
Port 2222

# 禁用空密碼
PermitEmptyPasswords no

# 限制最大嘗試次數
MaxAuthTries 3

# 設置空閒超時
ClientAliveInterval 300
ClientAliveCountMax 2

配置防火牆

Ubuntu:

  • 查看防火牆狀態
    status ufw
    
  • 臨時開啓/關閉防火牆
    ufw start/stop
    
  • 永久開啓/關閉防火牆
    ufw enable/disable
    

Rocky:

  • 查看防火牆狀態

    systemctl status firewalld
    
  • 開啓/關閉防火牆

    systemctl enable/disable firewalld
    
  • 關閉selinux

    # 永久關閉Selinux
    [root@localhost ~]# nano /etc/selinux/config
    SELINUX=disabled # SELINUX的值改為disabled
    # 臨時關閉selinux
    [root@localhost ~]# setenforce 0
    
    # 關閉防火牆
    [root@localhost ~]# systemctl disable firewalld.service
    Removed "/etc/systemd/system/multi-user.target.wants/firewalld.service".
    Removed "/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service".
    

2、換源

  • Ubuntu換源

    [root@magedu-VMware-Virtual-Platform]# vim /etc/apt/sources.list
    # Ubuntu sources have moved to /etc/apt/sources.list.d/ubuntu.sources
    deb https://mirrors.aliyun.com/ubuntu/ noble main restricted universe multiverse
    deb https://mirrors.aliyun.com/ubuntu/ noble-updates main restricted universe multiverse
    deb https://mirrors.aliyun.com/ubuntu/ noble-backports main restricted universe multiverse
    deb https://mirrors.aliyun.com/ubuntu/ noble-security main restricted universe multiverse
    [root@magedu-VMware-Virtual-Platform]# apt update
    
  • Centos換源

    • 更改配置文件
    [root@localhost /etc/yum.repos.d]# mkdir -p /etc/yum.repos.d/backup
    [root@localhost /etc/yum.repos.d]# mv /etc/yum.repos.d/*.reop /etc/yum.repos.d/backup
    [root@localhost /etc/yum.repos.d]# vim rocky.repo 
    # rocky.repo
    #
    # The mirrorlist system uses the connecting IP address of the client and the
    # update status of each mirror to pick current mirrors that are geographically
    # close to the client.  You should use this for Rocky updates unless you are
    # manually picking other mirrors.
    #
    # If the mirrorlist does not work for you, you can try the commented out
    # baseurl line instead.
    [baseos]
    name=Rocky Linux $releasever - BaseOS
    #mirrorlist=https://mirrors.rockylinux.org/mirrorlist?
    arch=$basearch&repo=BaseOS-$releasever$rltype
    baseurl=https://mirrors.aliyun.com/rockylinux/10/BaseOS/x86_64/os/
    gpgcheck=1
    enabled=1
    gpgkey=https://mirrors.aliyun.com/rockylinux/RPM-GPG-KEY-Rocky-10
    [AppStream]
    name=Rocky Linux $releasever - AppStream - Debug
    #mirrorlist=https://mirrors.rockylinux.org/mirrorlist?
    arch=$basearch&repo=BaseOS-$releasever-debug$rltype
    baseurl=https://mirrors.aliyun.com/rockylinux/10/AppStream/x86_64/os/   
    gpgcheck=1
    enabled=1
    gpgkey=https://mirrors.aliyun.com/rockylinux/RPM-GPG-KEY-Rocky-10
    [extras]
    name=Rocky Linux $releasever - Extras - Source
    #mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=source&  repo=BaseOS-$releasever
    source$rltype
    baseurl=https://mirrors.aliyun.com/rockylinux/10/extras/x86_64/os/
    gpgcheck=1
    enabled=1
    gpgkey=https://mirrors.aliyun.com/rockylinux/RPM-GPG-KEY-Rocky-10
    [epel]
    name=Rocky Linux $releasever - EPEL - Source
    #mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=source&  repo=BaseOS-$releasever
    source$rltype
    baseurl=https://mirrors.aliyun.com/epel/10/Everything/x86_64/
    gpgcheck=1
    enabled=1
    gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-10
    
  • 生成元數據緩存

    yum makecache
    
  • 安裝epel-release

    yum install epel-release
    
  • 更新源

    yum update
    
    
  • 一鍵更新源

    wget https://www.mysticalrecluse.com/script/Shell/switchsource
    bash switchsource -h 查看幫助
    Options:
      -h, --help           Show this help message and exit
      -a, --ali            Specify alibaba software source#阿里
      -1, --163            Specify 163-wangyi software source#網易
      -t, --tsinghua       Specify tsinghua software source#清華
      -H, --huawei         Specify huawei software source#華為
      -u, --ustc           Specify ustc-zhongkeda software source#中科院
    
    

3、配置提示符

  • 格式:

    • 提示符格式為:[\u@\h \W]\$

    • 其中:

      • \u 表示當前用户
      • \h 表示主機名
      • \W 表示當前工作目錄
      • \$ 表示提示符
    • 添加顏色

      PS1='[\e[32m\u@\h \W\e[0m]\$ ' # 豆包搜自己喜歡的
      
      
  • Centos:

    • 編輯bashrc文件

      sudo vim .bashrc
      
    • 配置提示符

      PS1='[\u@\h \W]\$ '
      
    • 使配置生效

      source/. .bashrc
      
    • 對所有普通用户生效

      # 對所有普通用户生效
      vim /etc/profile.d/env.sh # env.sh自行創建
      PS1="\[\e[1;33m\][\u@\h \w] \$\[\e[0m\]"
      source env.sh #使其生效
      
  • Ubuntu:

    • 編輯bashrc文件

      vim .bashrc
      
    • 修改#force_color_prompt=yes,將#刪除解除註釋

    • 使配置生效

      source/. .bashrc
      
    • 對所有普通用户生效

      # 對所有普通用户生效
      vim /usr/share/bash-completion/bash_completion
      # 在文件下方追加
      PS1="\[\e[1;33m\][\u@\h \w] \$\[\e[0m\]"
      source /usr/share/bash-completion/bash_completion #使其生效
      
  • 注意

    • 全局變量與當前用户的優先級
    • shell類型,不支持sh的用户
    • 注意內核版本

4、配置環境變量

  • 目的:
	將root用户主目錄下的bin文件夾添加到系統的可執行文件搜索路徑,如果你在 `~/bin` 中放置了自定義腳本或程序(如 `mytool`),可以直接在終端輸入命令名運行,而無需指定完整路徑(例如 `./mytool`)。
  • 配置bashrc文件
    sudo vim /etc/bash.bashrc
    
  • 配置環境變量
    export PATH=$PATH:~/bin
    
  • 使配置生效
    source /etc/bash.bashrc
    

5、配置別名

  • 編輯bashrc文件
    sudo vim /etc/bash.bashrc
    
  • 配置別名(顯示高亮)
    #示例
    # 系統管理
    alias stu='systemctl status' # 查看服務狀態
    alias sta='systemctl start'  # 開啓服務
    alias res='systemctl restart'# 重啓服務
    alias sto='systemctl stop'   # 停止服務
    alias sen='systemctl enable'
    alias sdis='systemctl disable'
    
    # 安全操作
    alias rm='rm -i'
    alias cp='cp -i'
    alias mv='mv -i'
    
    # 便捷查看
    alias ll='ls -lh'
    alias la='ls -la'
    alias lt='ls -ltr'
    
    # 網絡相關
    alias myip='curl ipinfo.io/ip'
    alias ports='netstat -tulanp'
    
    # 使配置生效
    source /etc/bash.bashrc
    
  • 使配置生效
    source /etc/bash.bashrc
    

6、修改主機名

hostnamectl set-hostname <主機名>
exit 生效

7、日期與時間

7.1 設置時區

# 查看當前時區
timedatectl status

# 設置上海時區
timedatectl set-timezone Asia/Shanghai

# 驗證
date

7.2 時間同步

# Ubuntu
sudo apt install chrony
sudo systemctl enable --now chrony

# Rocky/CentOS
sudo yum install chrony
sudo systemctl enable --now chronyd

# 查看同步狀態
chronyc sources -v

7、配置登陸前提示(區別虛擬終端和偽終端)

  • ubuntu(遠程ssh):
  • 在ubuntu中修改登錄前提示,通常涉及兩個部分
    • 1、motd (Message Of The Day):這是用户成功登錄後看到的歡迎信息。

    • 2、issue / issue.net:這是在登錄提示符出現之前顯示的系統標識或歡迎信息,本地登錄看 issue,遠程 SSH 登錄看 issue.net

    • 編輯/etc/issue.net文件

      sudo vim /etc/issue.net
      
    • 配置登陸前提示

      歡迎來到ubuntu 24.04
      
    • SSH 默認可能不會顯示 issue.net 的內容。你需要修改 SSH 配置文件來啓用它。

      sudo vim /etc/ssh/sshd_config
      
    • 找到 #Banner none 這一行,將其修改為:

      Banner /etc/issue.net
      
    • 重啓 SSH 服務

      sudo systemctl restart ssh
      
    • 關於顯示其他登錄前提示
      Ubuntu 的登錄提示(MoTD)是由/etc/update-motd.d/目錄下的可執行腳本生成的,不同腳本對應不同提示內容:
      以下是 /etc/update-motd.d/ 目錄下常見腳本的 詳細説明表格,包含腳本文件名、對應提示內容、作用及備註,方便精準禁用:

      腳本文件名 對應提示內容 作用 備註
      00-header 顯示歡迎標題,例如:
      Welcome to Ubuntu 22.04.3 LTS (GNU/Linux 5.15.0-107-generic x86_64)
      包含系統版本、內核信息
      系統登錄歡迎頭 默認啓用,展示系統基本信息
      10-help-text 顯示幫助鏈接信息:
      Documentation: https://help.ubuntu.com
      Management: https://landscape.canonical.com
      Support: https://ubuntu.com/advantage
      提供官方文檔、管理工具、支持服務入口 對新手友好,老用户可禁用
      50-motd-news 顯示 Ubuntu 官方新聞或推廣信息,例如:
      Welcome to Ubuntu Pro (Infra-only subscription).
      或活動通知、軟件更新提示
      推送官方動態、商業服務(如 Ubuntu Pro) 可通過 sudo pro disable motd-news 單獨禁用
      80-esm 顯示擴展安全維護(ESM)提示,例如:
      Ubuntu Pro: ESM Inactive - You are not receiving security updates for critical packages.
      或啓用後的狀態提示
      提醒 ESM 服務狀態(適用於 LTS 版本) 僅當系統未啓用 ESM 時顯示,禁用後不再提示
      90-updates-available 顯示系統待更新數量及命令提示:
      12 updates can be applied immediately.
      To see these updates run: apt list --upgradable
      包含安全更新、普通更新的數量
      提醒系統更新,保障安全性 核心提示,建議保留;若無需提醒可禁用
      91-release-upgrade 提示系統版本升級信息,例如:
      New release '24.04 LTS' available.
      Run 'do-release-upgrade' to upgrade to it.
      通知可用的系統版本升級(如從 22.04 到 24.04) 僅當有新版本時顯示,禁用後不再提醒
      95-hwe-eol 顯示硬件啓用棧(HWE)生命週期結束提示,例如:
      Your Hardware Enablement Stack (HWE) will reach end of life on 2025-04-30.
      提醒更換內核版本
      針對使用 HWE 內核的系統,提示內核支持期限 若未使用 HWE 內核,該腳本可能不生效
      98-fsck-at-reboot 提示系統重啓後需執行文件系統檢查(fsck),例如:
      The system will check the filesystem on reboot.
      通知文件系統存在問題,需重啓檢查 僅當系統檢測到 fsck 需求時顯示,禁用後可能錯過重要提示
      98-reboot-required 提示系統需要重啓以應用更新,例如:
      *** System restart required ***
      提醒用户重啓系統,確保更新生效 核心提示,建議保留;若臨時無法重啓,可暫時禁用
      99-footer 部分系統可能存在的尾註腳本,顯示空行或版權信息 優化提示格式,與其他提示分隔 部分 Ubuntu 版本無此腳本,作用較小

      補充説明:

      1. 禁用方法:對不需要的腳本執行 sudo chmod -x 腳本名(如 sudo chmod -x 50-motd-news),重啓會話即可生效。
      2. 恢復方法:若需恢復提示,執行 sudo chmod +x 腳本名 重新賦予執行權限。
      3. 用户級關閉:在用户主目錄創建 .hushlogin 文件(touch ~/.hushlogin),可關閉當前用户的所有登錄提示(優先級高於系統級配置)。
      • 刪除 / 關閉登錄提示的方法
        根據需求選擇對應的方式:
      • 方法 1:按需禁用特定提示(推薦)
        只關閉不需要的提示,保留有用信息(比如更新提醒):
        進入/etc/update-motd.d/目錄:
        cd /etc/update-motd.d/
        
      • 查看所有腳本(數字開頭的文件):
        ls -l
        
      • 禁用不需要的腳本(移除執行權限):
        例如,禁用 “幫助鏈接” 和 “新聞推廣”:
        sudo chmod -x 10-help-text 50-motd-news
        
      • (其他腳本同理,比如90-updates-available對應更新提示)
      • 方法 2:完全關閉所有 MoTD 提示
        如果希望登錄時無任何提示:
        禁用/etc/update-motd.d/下所有腳本:
        sudo chmod -x /etc/update-motd.d/*
        
      • (可選)修改 SSH 配置(僅對 SSH 登錄生效):
        編輯/etc/ssh/sshd_config,將PrintMotd設為no:
        sudo nano /etc/ssh/sshd_config
        
      • 添加 / 修改:
        ini
        PrintMotd no
        
      • 重啓 SSH 服務:
        sudo systemctl restart sshd
        
      • 方法 3:用户級關閉(僅對當前用户生效)
        在當前用户主目錄創建.hushlogin文件,即可關閉該用户的登錄提示:
        touch ~/.hushlogin
        

8、修改登錄後的歡迎信息 (motd)

簡單方法:直接編輯motd文件

bash

sudo vim /etc/motd

添加內容示例:

text

=====================================================
  歡迎回來!今天是 $(date +"%Y年%m月%d日 %A")
  系統負載:$(uptime | awk '{print $10,$11,$12}')
=====================================================

推薦方法:動態腳本

① 創建自定義腳本

bash

sudo vim /etc/update-motd.d/99-custom-message

② 腳本內容

bash

#!/bin/bash
echo "====================================================="
echo "  歡迎使用 $(hostname) 服務器"
echo "  系統版本: $(lsb_release -d | cut -f2 2>/dev/null || cat /etc/redhat-release)"
echo "  當前時間: $(date '+%Y-%m-%d %H:%M:%S %Z')"
echo "  運行時間: $(uptime -p)"
echo "  系統負載: $(uptime | awk -F'load average:' '{print $2}')"
echo "  內存使用: $(free -h | awk '/^Mem:/ {print $3"/"$2}')"
echo "  磁盤空間: $(df -h / | awk 'NR==2 {print $3"/"$2 " ("$5")"}')"
echo "====================================================="

③ 添加執行權限

bash

sudo chmod +x /etc/update-motd.d/99-custom-message

④ 測試效果

bash

sudo /etc/update-motd.d/99-custom-message

9、man實現高亮顯示與實時翻譯(擴展瞭解)

  • 編輯bashrc文件

    sudo vim .bashrc
    輸入export MANPAGER='vim -M +MANPAGER -'        
    
  • wq保存退出. .bashrc使配置生效

  • 連接代理服務器

    export http_proxy=http://101.35.250.82:18888
    
  • 下載minpaccha插件

    git clone https://github.com/k-takata/minpac.git ~/.vim/pack/minpac/opt/minpac
    
  • 編輯vimrc文件

    sudo vim .vimrc
    
  • 添加以下內容

    colorscheme murphy
    runtime! ftplugin/man.vim
    if exists('*minpac#init')
    " Minpac is loaded.
    call minpac#init()
    call minpac#add('k-takata/minpac', {'type': 'opt'})
    " Other plugins
    call minpac#add('tpope/vim-eunuch')
    call minpac#add('yegappan/mru')
    call minpac#add('bujnlc8/vim-translator')
    endif
    if has('eval')
    " Minpac commands
    command! PackUpdate packadd minpac | source $MYVIMRC | call minpac#update('', {'do': 'callminpac#status()'})
    command! PackClean packadd minpac | source $MYVIMRC | call minpac#clean()
    command! PackStatus packadd minpac | source $MYVIMRC | call minpac#status()
    endif
    if !has('gui_running')
    " 設置文本菜單
    if has('wildmenu')
    set wildmenu
    set cpoptions-=<
    set wildcharm=<C-Z>
    nnoremap <F10> :emenu <C-Z>
    inoremap <F10> <C-O>:emenu <C-Z>
    endif
    endif
    let g:translator_cache=1
    let g:translator_cache_path='~/.cache'
    let g:translator_channel='baidu'
    let g:translator_target_lang ='zh' " 目標語言為中文
    let g:translator_source_lang ='auto'
    let g:translator_outputype='popup'
    " 普通模式翻譯光標所在單詞
    noremap <leader>tc :<C-u>Tc<CR>
    " 可視模式翻譯選中內容
    vnoremap <leader>tv :<C-u>Tv<CR>
    autocmd FileType man setlocal readonly
    
  • 保存退出.vimrc使配置生效重新進入man頁面即可看到高亮顯示,翻譯功能需輸入PackUpdate按q推出再輸入更新插件

10、Linux中更改靜態IP(非DHCP環境下)

Rocky

①、命令行(掌握)

nmcli con mod 連接名(ens160) ipv4.method manual
nmcli con mod 連接名(ens160) ipv4.addresses 10.0.0.20/24
nmcli con mod 連接名(ens160) ipv4.gateway 10.0.0.2
nmcli con mod 連接名(ens160) ipv4.dns "8.8.8.8,114.114.114.114"
nmcli con mod 連接名(ens160) ipv4.ignore-auto-dns yes

#重啓網絡連接配置使其生效(沒有立即生效再打命令)
nmcli con down ens160 && nmcli con up ens160

②、修改NetworkManager配置文件(掌握)

1、進入配置文件目錄並編輯對應文件

cd /etc/NetworkManager/system-connections
vim 連接名.nmconnection

2、修改 | 添加 [ipv4] 段內容

[ipv4]
method=manual
addresses=10.0.0.20/24,10.0.0.2
dns=8.8.8.8,114.114.114.114;
ignore-auto-dns=yes

3、保存並重啓網絡服務

systemctl restart NetworkManager #重啓服務之後reboot主機
reboot  

③、文本界面nmtui(推薦)

#1、啓動nmtui
nmtui
#2、根據節面內容設置
#3、保存後退出,重啓網絡連接
nmcli con down 連接名 && nmcli con up 連接名

openEuler

編輯配置文件(掌握)

 同rocky

Ubuntu

①、修改配置文件(推薦)

# 首先查查詢網卡名稱,Ubuntu為ens33
ip a

#配置文件路徑為
cd /etc/netplan/
ls查看該目錄下有.yaml文件
#自行再創建一個00-installer-config.yaml
vim 00-installer-config.yaml
#輸入以下內容
network:
  version: 2
  ethernets:
    ens33:
      addresses:
      - "10.0.0.19/24"
      nameservers:
        addresses:
        - 10.0.0.2
        search: []
      routes:
      - to: "default"
        via: "10.0.0.2"

②、使用 NetworkManager (nmcli)

nmcli connection modify "Wired connection 1" \
    ipv4.addresses "10.0.0.19/24" \
    ipv4.gateway "10.0.0.1" \
    ipv4.dns "8.8.8.8 114.114.114.114" \
    ipv4.method manual \
    connection.autoconnect yes
    
# 激活鏈接
nmcli connection up "static-ens33"

③、文本界面nmtui

image-20260104193739313

#需下載net
apt install network-manager -y
nmtui

11、在Linux中安裝man中文環境

①、Rocky

export https proxy=http://101.35.250.82:18888

# 編譯工具OpenCC的安裝
git clone https://github.com/BYVoid/OpenCC.git
chown -R $USER:$USER OpenCC
cd OpenCC/
mkdir build
cd build
# 需要安裝 cmake, gcc-c++, python3
# yum install -y cmake gcc-c++ python3
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j"$(nproc)"
make install

# 把 /usr/local/lib(或 lib64)加入動態庫搜索路徑

bash -c 'cat >/etc/ld.so.conf.d/opencc.conf <<EOF
/usr/local/lib
/usr/local/lib64
EOF'
ldconfig
# 查看
ldconfig -p | grep opencc

# GitHub 項目: man-pages-zh :

git clone https://github.com/man-pages-zh/manpages-zh
cd manpages-zh
mkdir build
cd build
cmake ..
make
make install

②、Ubuntu

  • 安裝中文語言包
apt install language-pack-zh-hans language-pack-zh-hans-base
  • 驗證:
dpkg -l | grep language-pack-zh
  • 安裝中文 man 文檔
apt install manpages-zh
user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.