目录

「Linux」从上车到翻车

记录Linux各发行版配置及使用技巧。

安装

Ubuntu

切换软件源
安装Rime输入法
  1. 【如果需要】安装语言包

  2. 【如果需要】安装Ibus,并启用

    sudo apt-get install ibus ibus-clutter ibus-gtk ibus-gtk3 ibus-qt4
    im-config -s ibus
    # 注销或重启计算机以应用更改
  3. 安装Rime

    sudo apt-get install ibus-rime
    # 注销或重启计算机以应用更改
  4. 设置ibus框架

    ibus-setup
    # 添加需要的输入法
  5. 配置Text Entry

    18.04 LTS在Settings $\to$ Region & Language $\to$ Input Sources下,無需安裝Text Entry

    • System Settings -> Text Entry
    • 左下角添加需要的输入法
    • 配置快捷键
  6. 切换输入法

    • ctrl +
修改快捷键
  1. 打開資源管理器
    1. 搜索shortcuts $\to$ launchers $\to$ Home folder [PS: For 18.04 LTS]
时间同步
  1. 缘起

    Windows 10Ubuntu双系统在对待硬件时间的方式不同1

  2. 解决

    # 安装`ntpdate`
    sudo apt-get install ntpdate
    # 校准时间
    sudo ntpdate time.yirami.xyz
    # 更新时间到硬件
    sudo hwclock --localtime --systohc
  3. 引申

    1. Linux时钟设置
      # 判断硬件时钟是否设置为本地时区
      timedatectl | grep local
      # 将硬件时钟设置为本地时区
      timedatectl set-local-rtc 1
      # 将硬件时钟设置为协调世界时(UTC)
      timedatectl set-local-rtc 0
      # 开始自动时间同步到远程NTP服务器
      timedatectl set-ntp true
      # 禁用NTP时间同步
      timedatectl set-ntp false
    2. Linuxntpdntpdate的区别
      1. ntpd平滑同步
      2. ntpdate立刻同步
配置科学上网
美化
  1. cairo-dock

  2. macbuntu

  3. 手動 Ref:给Ubuntu18.04安装mac os主题

    1. 安裝TweakTool
      sudo apt-get update # 先跳過
      sudo apt-get install gnome-tweak-tool
      # 配置見參考
      # 需要
      sudo apt-get install gnome-shell-extensions # 需要註銷或重啓,修改完還得註銷
    2. 安裝GTK
      1. 下載主題到指定目錄
        sudo mv ./McOS-MJV /usr/share/themes/
      2. Tweak下應用主題
      3. 下載圖標到指定目錄
        sudo mv ./macOS11 /usr/share/icons/
开启 RDP 远程桌面

Ubuntu 22.04 LTS PASSED;

配置方法可参考回答

sudo apt update
sudo apt install xrdp gnome-session -y

# allow log in after xrdp setup
sudo adduser xrdp ssl-cert

sudo systemctl restart xrdp

Pop!_OS

24.04 LTS passed;

安装 Rime 输入法
# install
sudo apt update
sudo apt install fcitx5 fcitx5-rime fcitx5-frontend-gtk4 fcitx5-frontend-gtk3 fcitx5-frontend-qt5 fcitx5-frontend-qt6

# config
im-config -n fcitx5

# log out and log back in

# check status
fcitx5-diagnose

# add rime
fcitx5-configtool

# [test only] start manually
fcitx5 -dr

# disable hot key
cat > ~/.local/share/fcitx5/rime/default.custom.yaml <<'EOF'
patch:
  switcher:
    hotkeys: []
EOF

# redeploy or restart rime
修改快捷键
  • Win + E 打开文件夹
    • Settings -> 输入设备 -> 键盘 -> 键盘快捷键 -> 系统快捷键
时间同步

本质是 WindowsLinux 对硬件时钟(RTC)使用方式不同导致 Linux: 硬件时钟 = UTC Windows: 硬件时钟 = Local Time

推荐在 Windows 端修改注册表解决:

# run with administrator
reg add "HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation" `
/v RealTimeIsUniversal /t REG_DWORD /d 1 /f
配置科学上网
美化
配置 RDP 远程桌面
sudo apt update
sudo apt install remmina remmina-plugin-rdp
SAMBA 挂载
# GNOME 桌面用户:可以显示在文件浏览器左侧栏
gio mount smb://your.domain.or.ip:port/YArk

# systemd
创建归档
#!/bin/bash
# create_iso.sh
#
# 用法:
#   ./create_iso.sh <source_dir> [output_dir] [volume_label] [iso_filename]
#
# 示例:
#   ./create_iso.sh /data/media/2023
#   ./create_iso.sh /data/media/2023 /archive/iso MEDIA_2023
#   ./create_iso.sh /data/media/2023 /archive/iso MEDIA_2023 media_2023_photos_v1.iso

set -e

# -------- 参数解析 --------
SRC="$1"
if [[ -z "$SRC" ]]; then
    echo "Usage: $0 <source_dir> [output_dir] [volume_label] [iso_filename]"
    exit 1
fi

OUTPUT_DIR="${2:-/archive/iso}"
mkdir -p "$OUTPUT_DIR"

# 判断是否是 ZIP 或 7z 文件
EXT="${SRC##*.}"
SRC_DIR="$SRC"  # 默认情况,直接使用输入目录

if [[ -f "$SRC" && ( "$EXT" == "zip" || "$EXT" == "7z" ) ]]; then
    DIRNAME="${SRC%.*}"
    TMP_UNPACK="${DIRNAME}.tmp"

    mkdir -p "$TMP_UNPACK"

    echo "解压中..."
    [[ "$EXT" == "zip" ]] && unzip -q -X "$SRC" -d "$TMP_UNPACK" || 7z x "$SRC" -o"$TMP_UNPACK" -y

    # 获取解压后的唯一子项。如果是目录且只有一个,则将其内容上提
    SUB_ITEMS=("$TMP_UNPACK"/*)
    if [[ ${#SUB_ITEMS[@]} -eq 1 && -d "${SUB_ITEMS[0]}" ]]; then
        echo "检测到冗余层级,正在优化结构..."
        mv "${SUB_ITEMS[0]}" "$DIRNAME"
        rmdir "$TMP_UNPACK"
    else
        mv "$TMP_UNPACK" "$DIRNAME"
    fi

    SRC_DIR="$DIRNAME"
fi

# 卷标
VOL_LABEL="${3:-$(basename "$SRC_DIR")}"

# ISO 文件名
ISO_NAME="${4:-$(basename "$SRC_DIR")}.iso"

OUT="$OUTPUT_DIR/$ISO_NAME"

# -------- 信息提示 --------
echo "源目录     : $SRC_DIR"
echo "输出目录   : $OUTPUT_DIR"
echo "卷标       : $VOL_LABEL"
echo "ISO 文件名 : $ISO_NAME"
echo "完整路径   : $OUT"
echo "----------------------------------"

# -------- 生成 ISO --------
xorriso \
    -outdev "$OUT" \
    -volid "$VOL_LABEL" \
    -joliet on \
    -rockridge on \
    -map "$SRC_DIR" /

# -------- 校验 --------
sha256sum "$OUT" > "${OUT}.sha256"

echo "完成 ✔"
echo "SHA256     : ${OUT}.sha256"
  • ISO

    # install
    sudo apt update
    sudo apt install -y xorriso
    
    # create
    xorriso -as mkisofs -iso-level 3 -J -R -udf -V "MEDIA_ARCHIVE_01" -o media_01.iso /path/to/media
    
    # script
    ./create_iso.sh /data/media/2023
    ./create_iso.sh /data/media/2023 /mnt/backup/iso
    ./create_iso.sh /data/media/2023 /mnt/backup/iso "MEDIA_2023"
    
    # load
    sudo mount -o loop media_01.iso /mnt/iso
其他修复
  • 插入耳机后,声音仍从扬声器出
    # check the device is detected
    sudo apt install -y pavucontrol
    pavucontrol
    
    # set usb device as default
    pactl list short sinks
    pactl set-default-sink  alsa_output.usb-Microsoft_Microsoft_Modern_USB-C_Headset_0Y333FG220834W-00.analog-stereo

命令

Linux

  1. 文件权限
ll  # 查看文件权限,小写LL
chmod 777 xxx  # 修改权限
chmod +x xxx # 赋予可执行权限
chown -R user:group xxx  # 更改目录所有者和所属组
  1. 管道符号|

前面(命令)的输出作为后面(命令)的输入

  1. 任務管理

    • &

    命令后加上&可以使腳本進入後臺執行

    • ctrl+z

    将一个正在前台执行的命令放到后台,并且处于暂停状态。

    • fg

    将后台中的命令调至前台继续运行。如果后台中有多个命令,可以用fg %jobnumber(命令编号非进程号)将选中的命令调出。

    • bg

    将一个在后台暂停的命令,变成在后台继续执行。如果后台中有多个命令,可以用bg %jobnumber将选中的命令调出。

    • jobs

    查看当前终端有多少在后台运行的命令

    • nohup

    在你退出帐户/关闭终端之后继续运行相应的进程 关闭终端后,在另一个终端使用jobs已经无法看到后台跑得程序了,此时可以利用ps查看

    ps -aux | grep "xxx.sh"  
    #a: 显示所有程序
    #u: 以用户为主的格式来显示
    #x: 显示所有程序,不以终端机来区分
  2. 添加腳本到開機啓動

    1. 新建腳本
      #!/bin/sh
      ### BEGIN INIT INFO
      # Provides:          startfile
      # Required-Start:    $all
      # Required-Stop:     $all
      # Default-Start:     2 3 4 5
      # Default-Stop:      0 1 6
      # Short-Description: Start the brook  service
      # Description:       Used to Turn over the GFW to access the Internet.
      ### END INIT INFO
      nohup <command> & # back run and don't killed when terminal exit or log out.
    2. 修改可執行權限
      # solution 1:
      chmod +x xxx.sh
      # solution 2:
      sudo chmod 755 xxx.sh
    3. 移動到啓動腳本目錄
      sudo mv xxx.sh /etc/init.d/
    4. 更新自啓動目錄
      sudo update-rc.d xxx.sh defaults 90 #90爲啓動優先級,數值越大,啓動越晚
  3. lib

    • ldconfig | 查找库

      ldconfig -p | grep xxx
    • ldd | 查看库依赖

      ldd [-r] xxx
  4. ip | ip 命令来自 iproute2 套件,用于取代 net-tools 套件(包含ifconfig)

    # 查询ip
    ip addr show
  5. mount.cifs

  6. df (disk free) | 查看磁盘分区剩余

  7. update-alternatives | 软件版本切换

update-alternatives --list python
update-alternatives --install /usr/bin/python python /usr/... 1
update-alternatives --install /usr
  1. screen 远程会话管理
# 创建新会话
screen -S yirami
# 会话分离
ctrl+a +d
# 会话列表
screen -ls
# 会话恢复
screen -r [id]
  1. ffmpeg 多媒体处理
  • 图片转视频
ffmpeg -pattern_type glob -i './*.jpeg' -vcodec libx264 -r 20 output.h264
ffmpeg -i ./camera_1_%9d.jpeg -vcodec libx264 -r 20 output.mp4
ffmpeg -pattern_type glob -i './camera_1_*[0-9].*[0-9].jpeg' -vcodec libx264 -r 20 output.mp4
  • 视频重编码/压缩
ffmpeg -i vin.mp4 -vcodec libx265 vout.mp4
ffmpeg -i vin.mp4 -c:v libx265 -crf 32 -c:a copy vout.mp4
# crf 在[0-51]之间选取,0为无损,通常18~28较合理
  • 裁剪视频
ffmpeg -ss 00:00:00 -t 00:00:30 -accurate_seek -i test.mp4 -vcodec copy -acodec copy -avoid_negative_ts 1 output.mp4
# -ss 指定从什么时间开始
# -t 指定需要截取多长时间
# -i 指定输入文件
  • 视频拼接
ffmpeg -f concat -i list.txt -c copy concat.mp4
  • 调整音量
# 查看音量
ffmpeg -i vin.mp4 -filter_complex volumedetect -c:v copy -f null /dev/null
# 调整音量
ffmpeg -i vin.mp4 -af volume=+30dB -vcodec copy -y vout.mp4
# -af 创建由filtergraph指定的过滤器图,并使用它来过滤流
# -y 覆盖输出文件且不询问
  1. 定时执行任务

reference to blog

  1. at

      # install
      apt install -y at
      # daemon
      service atd start  # or
      systemctl start atd
      # 检查开机启动
      chkconfig --list | grep atd  # or
      systemctl list-unit-files | grep atd
      # 设置开机启动
      chkconfig --level 235 atd on  # or
      systemctl enable atd
      # 交互式创建任务
      at now +2 minutes  # 2分钟后执行
      # 查询任务
      atq
      # 删除任务
      at -d [task number]
  2. crontab

      # 列出当前用户的任务
      crontab -l
      # 列出指定用户的任务
      crontab -l -u yirami_debian
      # 编辑用户任务列表
      crontab -e
      # 删除定时任务
      crontab -r
    • 另外,对于某些可能错过执行的任务,可以参考补充命令 anacron
  3. systemd

    • 相比上述命令,该工具支持精确到秒的任务

    • config systemd.service

        touch /usr/lib/systemd/system/you_shell_start.service
      
        [Unit]
        Description=do something
        [Service]
        Type=simple
        ExecStart=path_to_your_shell
    • config systemd.timer

        touch /usr/lib/systemd/system/you_shell_start.timer
      
        [Timer]
        # Time to wait after enable this unit
        OnActiveSec=60
        # Time between running each consecutive time
        OnUnitActiveSec=30
        Unit=you_shell_start.service
        [Install]
        WantedBy=multi-user.target
    • start

        systemctl enable you_shell_start.timer
        systemctl start you_shell_start.timer
    • 查看状态

        systemctl status you_shell_start.timer
        systemctl status you_shell_start
    • 停用

        systemctl disable you_shell_start.timer
        systemctl stop you_shell_start.timer
  4. 存储设备的 S.M.A.R.T (Self-Monitoring, Analysis, and Reporting Technology)

smartctl -a /dev/sda  # 查看指定硬盘的全部 S.M.A.R.T 信息
smartctl -t [short|long] /dev/sda  # 执行测试
  1. 磁盘空间分析工具 ncdu

NCDU (NCurses Disk Usage) 是一款使用 C 编写的适用于 POSIX-like 系统的图形化磁盘空间分析工具。它依赖 ncurses 库提供的基于文本终端的“类 GUI”以实现与 du 工具相似的目的。

# install
sudo apt install ncdu  # Debian/Ubuntu
sudo yum install ncdu  # RHEL/CentOS
sudo pacman -S ncdu  # Arch

# use
sudo ncdu /  # scan from /
sudo ncdu / --exclude=/opt --exclude=/tmp  # scan but exclude

Debian

  1. shell

Debian docker 中默认使用dash

rm /bin/sh && ln -s /bin/bash /bin/sh
  1. iptables
# 查看规则
iptables -L
# 从文件恢复规则
sudo iptables-restore < file
  1. rc.local
# 确认发行版具备rc.local.service
cat /lib/systemd/system/rc.local.service
# 查看服务是否是默认关闭
systemctl status rc-local
# 手动添加 `/etc/rc.local`
cat <<EOF >/etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

exit 0
EOF
# 赋予执行权限
chmod +x /etc/rc.local
# 启动服务
systemctl start rc-local
# 确认服务运行
systemctl status rc-local
# 添加开机启动命令到 `exit 0` 之前

Ubuntu

  1. apt-get
apt-get install ...
  1. apt-file

use apt-file to look for a particular file and don’t know which package provides it

apt-file search mount.cifs
  1. ufw
sudo apt install ufw
# reset all (禁止任意入站,允许任意出站)
sudo ufw default deny incoming
sudo ufw default allow outgoing
# allow ssh
sudo ufw allow ssh
# allow web
sudo ufw allow http
sudo ufw allow https
# 或
sudo ufw allow 80
sudo ufw allow 443
# enable
sudo ufw enable
# check
sudo ufw status

CentOS

CentOS 7

  1. semanage
yum provides semanage
yum -y install policycoreutils-python
# 如果提示`Could not open kernel policy /etc/selinux/targeted/active/policy.kern for reading.`错误
yum install selinux-policy-targeted

防火墙

iptables

/ Debian Buster(10) /

配置模板
*filter

# accept loopback
-A INPUT -i lo -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
# accept established
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# icmp
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
# other input
#-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 32722 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

# output
-A OUTPUT -j ACCEPT

# deny other
-A INPUT -j REJECT --reject-with icmp-port-unreachable
-A FORWARD -j REJECT --reject-with icmp-port-unreachable
# -A OUTPUT -p udp -j REJECT --reject-with icmp-port-unreachable
COMMIT
持久化
1. backup iptables to file
# 1
iptables-save | tee /etc/iptables.conf
# sudo iptables-save | sudo tee /etc/iptables.conf
2. restore the file
# 1.
vim /etc/rc.local
 ## and then insert lines for loading iptables rules from this file
iptables-restore < /etc/iptables.conf
# 2. edit after saving the iptable's rules
vim /etc/network/interfaces
 ## and then insert a line in /etc/network/interfaces
post-up iptables-restore < /etc/iptables.up.rules
Reference
  1. How can I make a specific set of iptables rules permanent?
  2. Debian Iptables 配置教程

内核

cgroups

控制组 (control groups, cgroups) 是 Linux Kernel 的一项功能,旨在对运行的一组进程进行资源分配与限制。

美团技术团队这篇文章对该内核特性做了比较详细的介绍,而 LWN.net 上的这篇文章基于早期内核(3.15)对 cgroup 的演变和细节做了不少介绍。

cgroup v1 vs v2
特性cgroup v1cgroup v2
层次结构每个子系统(cpu/memory/blkio等)独立树单一统一层次树,所有控制器在同一树下
控制器挂载独立挂载,如 /sys/fs/cgroup/memory统一挂载 /sys/fs/cgroup,通过 cgroup.controllers 查看
进程绑定同一进程可加入不同子系统的不同 cgroup每个进程只能属于树中的一个 cgroup
CPU 控制cpu.shares + cpu.cfs_quota_uscpu.max + cpu.weight(统一计算 CPU 权重)
内存控制memory.limit_in_bytes, memory.memsw.limit_in_bytesmemory.max, memory.swap.max
IO 控制blkio.throttle.* 文件io.max(统一速率限制)
PID 控制需要单独 pids 子系统pids.max(统一管理)
事件通知各子系统独立统一事件通知 cgroup.events
灵活性子系统独立,组合复杂统一管理,更一致,但组合灵活性略低
容器兼容性Docker 默认支持 v1Docker 20+ 支持 v2,需要 newer runtime
资源计数不统一,可能重复统计统一计数,资源限制更精确
易用性文件接口多,学习成本高文件接口统一,操作更简洁

实践中,使用 Docker 配合 --cpus--memory 等参数限制容器资源时,基于 v2 比基于 v1 的程序慢 $2\sim3$ 倍,可能在高性能程序中,使用 v2 配合 v1 的混合模式更能发挥性能。