小星的编程笔记

  • VSCode常见颜色与标记含义表

    颜色 / 标记对应含义典型场景说明
    黄色当前打开 / 文件已修改文件名呈黄色代表文件正在编辑器中被打开;如果名字后缀附带 M,则代表该文件被修改但尚未暂存
    绿色新增 / 已暂存名字后缀带有 A 或 U 表示新创建的文件,已经加入暂存区或等待跟踪,处于待提交状态
    红色删除 / 冲突名字后缀带有 D 表示文件已被删除,尚未提交;或者在合并代码时表示存在冲突
    蓝色未跟踪文件后缀带有 U 或 ?,表示这是一个新文件,Git 尚未开始跟踪
    灰色已忽略文件文件后缀带有 !,表示该文件匹配了 .gitignore 规则,不纳入版本控制
    右侧数字/红黄波浪线代码检查问题文件名右侧出现的数字代表该文件存在的异常数量,红黄色系图标分别代表代码错误与警告
  • 自建上网配置

    第 1 步:安装所需软件nginx

    SSH 登录 VPS,执行:

    sudo apt update
    
    sudo apt install -y \
        nginx \
        certbot \
        curl \
        ca-certificates \
        openssl
    
    sudo systemctl enable --now nginx
    sudo nginx -t

    第 2 步:准备证书申请目录

    DOMAIN="test.aspu.top"
    EMAIL="test@aspu.top"
    
    
    创建证书验证目录:
    sudo mkdir -p /var/www/certbot/.well-known/acme-challenge

    先添加仅用于 HTTP 证书验证的 Nginx 配置:

    sudo tee "/etc/nginx/conf.d/${DOMAIN}.conf" >/dev/null <<EOF
    server {
        listen 80;
        server_name ${DOMAIN};
    
        location ^~ /.well-known/acme-challenge/ {
            root /var/www/certbot;
        }
    
        location / {
            return 404;
        }
    }
    EOF
    

    第 3 步:申请正式 TLS 证书 参考 https://www.aspu.top/archives/266 申请证书

    得到 aspu.top_bundle.crt aspu.top.key;

    第 4 步:安装 Xray-core

    curl -fsSL \
      -o /tmp/install-release.sh \
      https://github.com/XTLS/Xray-install/raw/main/install-release.sh
    
    sudo bash /tmp/install-release.sh install

    检查程序是否安装成功:

    sudo /usr/local/bin/xray version
    
    输出类似如下
    Xray 26.10.21 (Xray, Penetrates Everything.) 1b1647c (go1.27.3 linux/amd64)
    A unified platform for anti-censorship.

    第 5 步:生成客户端凭据

    UUID="$(sudo /usr/local/bin/xray uuid)"
    WS_PATH="/$(openssl rand -hex 16)/"
    
    printf '\nDOMAIN=%s\nUUID=%s\nWS_PATH=%s\n' \
      "$DOMAIN" "$UUID" "$WS_PATH"
    
    预期输出类似
    DOMAIN=test.aspu.top
    UUID=12345678-9033-4fbe-b56e-123456789012
    WS_PATH=/1234567890220d61db42ebf704123456/

    第 6 步:写入 Xray 服务端配置

    sudo tee /usr/local/etc/xray/config.json >/dev/null <<EOF
    {
      "log": {
        "loglevel": "warning"
      },
      "inbounds": [
        {
          "listen": "127.0.0.1",
          "port": 10000,
          "protocol": "vless",
          "settings": {
            "clients": [
              {
                "id": "${UUID}",
                "email": "win11-client"
              }
            ],
            "decryption": "none"
          },
          "streamSettings": {
            "network": "ws",
            "security": "none",
            "wsSettings": {
              "path": "${WS_PATH}"
            }
          }
        }
      ],
      "outbounds": [
        {
          "protocol": "freedom",
          "tag": "direct"
        },
        {
          "protocol": "blackhole",
          "tag": "blocked"
        }
      ]
    }
    EOF
    如果要添加多个用户 
    sudo nano /usr/local/etc/xray/config.json
    
    "clients": [
      {
        "id": "原来的UUID",
        "email": "user1"
      },
      {
        "id": "新生成的UUID",
        "email": "user2"
      }
    ]

    ‘先检查 JSON 配置:

    sudo /usr/local/bin/xray run \
      -test \
      -config /usr/local/etc/xray/config.json

    确认没有配置错误,再启动 Xray:

    sudo systemctl enable --now xray
    sudo systemctl restart xray
    sudo systemctl status xray --no-pager

    第7步: 配置 Nginx:443 转发给 Xray

    sudo tee "/etc/nginx/conf.d/${DOMAIN}.conf" >/dev/null <<EOF
    server {
        listen 80;
        server_name ${DOMAIN};
    
        location ^~ /.well-known/acme-challenge/ {
            root /var/www/certbot;
        }
    
        location / {
            return 301 https://\$host\$request_uri;
        }
    }
    
    server {
        listen 443 ssl;
        server_name ${DOMAIN};
    
        ssl_certificate     /etc/nginx/ssl_cert/aspu.top_bundle.crt;
        ssl_certificate_key /etc/nginx/ssl_cert/aspu.top.key;
    
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
    
        location ${WS_PATH} {
            proxy_pass http://127.0.0.1:10000;
            proxy_http_version 1.1;
    
            proxy_set_header Upgrade \$http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host \$host;
            proxy_set_header X-Real-IP \$remote_addr;
            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    
            proxy_read_timeout 3600s;
            proxy_send_timeout 3600s;
            proxy_buffering off;
        }
    
        location / {
            root /var/www/html;
            index index.html;
        }
    }
    EOF

    重启nginx

    sudo nginx -t &&sudo systemctl reload nginx

    重启xray

    sudo systemctl restart xray

    检查 VPS 端口

    sudo ss -lntp | grep -E ':(80|443|10000)\b'
    
    预期看到:
    - Nginx 监听公网地址的 TCP 80、443。
    - Xray 只监听 127.0.0.1:10000。

    启动防火墙

    sudo ufw allow 22/tcp
    sudo ufw allow 80/tcp
    sudo ufw allow 443/tcp

    第8步: windows 客户端 安装 Clash Verge Rev

    从官方 GitHub 下载正式发布版:
    
    Clash Verge Rev Releases
    
    https://github.com/Clash-Verge-rev/clash-verge-rev/releases?utm_source=chatgpt.com
    
    注意选择   Clash Verge_2.5.8_x64-setup.exe  这个版本下载

    配置文件如下

    config.yaml 文件 打开配置目录即可 编辑 config.yaml

    # Generated by Clash Verge
    
    mixed-port: 7897
    allow-lan: false
    mode: rule
    log-level: info
    ipv6: false
    tcp-concurrent: true
    unified-delay: true
    external-controller: 127.0.0.1:9090
    profile:
      store-selected: true
    tun:
      enable: true
      stack: mixed
      auto-route: true
      auto-detect-interface: true
      strict-route: true
      dns-hijack:
      - any:53
      - tcp://any:53
      route-exclude-address:
      - 111.111.111.111/32
      - 111.111.111.112/32
    dns:
      enable: true
      ipv6: true
      enhanced-mode: fake-ip
      fake-ip-range: 198.18.0.1/16
      fake-ip-range6: fdfe:dcba:9876::1/64
      default-nameserver:
      - 223.5.5.5
      - 119.29.29.29
      proxy-server-nameserver:
      - 223.5.5.5
      - 119.29.29.29
      direct-nameserver:
      - https://doh.pub/dns-query
      - https://dns.alidns.com/dns-query
      direct-nameserver-follow-policy: true
      nameserver:
      - https://dns.google/dns-query#PROXY
      nameserver-policy:
        rule-set:cn_domain:
        - https://doh.pub/dns-query
        - https://dns.alidns.com/dns-query
        rule-set:private_domain:
        - https://doh.pub/dns-query
    proxies:
    - name: VPS-VLESS-WS-TLS
      type: vless
      server: 111.111.111.111  #your vps ip
      port: 443
      uuid: 12345678-9033-4fbe-b56e-123456789012
      udp: true
      packet-encoding: xudp
      tls: true
      servername: test.aspu.top
      client-fingerprint: chrome
      network: ws
      ws-opts:
        path: /1234567890220d61db42ebf704123456/
        headers:
          Host: test.aspu.top
      ip-version: ipv4
    proxy-groups:
    - name: PROXY
      type: select
      proxies:
      - VPS-VLESS-WS-TLS
    rule-providers:
      private_domain:
        type: http
        behavior: domain
        format: mrs
        interval: 86400
        proxy: PROXY
        url: https://raw.githubusercontent.com/MetaCubeX/meta-rules-dat/meta/geo/geosite/private.mrs
      cn_domain:
        type: http
        behavior: domain
        format: mrs
        interval: 86400
        proxy: PROXY
        url: https://raw.githubusercontent.com/MetaCubeX/meta-rules-dat/meta/geo/geosite/cn.mrs
      cn_ip:
        type: http
        behavior: ipcidr
        format: mrs
        interval: 86400
        proxy: PROXY
        url: https://raw.githubusercontent.com/MetaCubeX/meta-rules-dat/meta/geo/geoip/cn.mrs
    rules:
    - RULE-SET,private_domain,DIRECT
    - IP-CIDR,10.0.0.0/8,DIRECT,no-resolve
    - IP-CIDR,172.16.0.0/12,DIRECT,no-resolve
    - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve
    - IP-CIDR,127.0.0.0/8,DIRECT,no-resolve
    - IP-CIDR,169.254.0.0/16,DIRECT,no-resolve
    - DOMAIN-SUFFIX,cn,DIRECT
    - RULE-SET,cn_domain,DIRECT
    - RULE-SET,cn_ip,DIRECT
    - GEOIP,CN,DIRECT,no-resolve
    - MATCH,PROXY
    socks-port: 7898
    port: 7899
    external-controller-pipe: \\.\pipe\verge-mihomo-sidecar-release-a1595906cba418580c4329db539544e0fd9deda0f5db071e44d8a08721a708e5
    secret: set-your-secret
    external-controller-cors:
      allow-private-network: true
      allow-origins:
      - tauri://localhost
      - http://tauri.localhost
      - https://yacd.metacubex.one
      - https://metacubex.github.io
      - https://board.zash.run.place
    
    将  
    servername: test.aspu.top
    Host: test.aspu.top
    uuid: 12345678-9033-4fbe-b56e-123456789012
    path: /1234567890220d61db42ebf704123456/
    
    改为之前生成的对应的即可
    
    server: 111.111.111.111  #改为你的vps ip
    
    下面这个很重要  就是说以下服务器ip 不经过虚拟网卡直连  不然一些香港服务器可能会走代理 排除后香港服务器直连就连上了
    也能避免退出clash时 导致终端ssh连接的服务断开链接    111.111.111.111  改成你需要排除的服务器ip即可
    route-exclude-address:
      - 111.111.111.111/32
      - 111.111.111.112/32

    下面很重要 如何对指定ip域名进行直连

    指定域名直连
    rules:
      - DOMAIN-SUFFIX,example.com,DIRECT
      
    指定ip  或 IP段 直连
    
    - IP-CIDR,192.0.2.0/24,DIRECT,no-resolve
    
    指定ipv6 直连
    - IP-CIDR6,2001:db8::1/128,DIRECT,no-resolve  
      
    

    最后 启动虚拟网卡模式 和系统代理 关闭ipv6

    成功

    注意 如果连不上 重启一下 sudo systemctl restart xray

    最后验证

    访问 https://test.aspu.top/1234567890220d61db42ebf704123456/

    返回400 错误就OK

    测试

    curl.exe --max-time 15 -x http://127.0.0.1:7897 https://api.ipify.org
    
    如果代理链路正常,命令会返回经过代理访问互联网时的公网出口 IP,通常应该是 VPS 的出口 IP。
    
    

    如何知道某个网站走代理 还是直连

    在日志页面 输入域名进行过滤 会提示 using DIRECT or Match using PROXY[VPS-VLESS-WS-TLS

    注意: 购买VPS 需要选择带三网优化的

    中国电信回程CMI/CU,中国联通回程CU / NTT / CMI 均衡,中国移动回程Level3/CU 有优化的线路 不然连接特别卡 网速龟速尤其是晚上不好用.

  • 增加windows延迟更新时间

    New-ItemProperty -Path ‘HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings’ -Name ‘FlightSettingsMaxPauseDays’ -PropertyType DWord -Value 3650 -Force

  • Typora激活

    1.首先清除之前的安装

    1. 注册表清理
    
    计算机\HKEY_CURRENT_USER\Software\Typora
    
    删除出 Typora  文件夹
    
    2. 临时文件清理
    %appdata%
    找到 Typora 删除
    
    到这里就可以无限试用了.

    2. 安装Typora 1.9.5

    运行
    [09-17 14:19:26] PS C:\Program Files\Typora> .\node_inject.exe
    extracting node_modules.asar
    adding hook.js
    applying patch
    packing node_modules.asar
    done!
    [09-17 14:19:38] PS C:\Program Files\Typora>
    [09-17 14:19:39] PS C:\Program Files\Typora> .\license-gen.exe
    License for you: R3M9XF-F2G9NV-7PCBUF-F9X511
    
    激活成功

    3. 禁止更新

  • 腾讯云 &阿里云自动申请续费ssl证书

    腾讯云阿里云只要配置一次 API,以后证书就会全自动续期。

    假设你的环境:

    • 域名:aspu.top
    • DNS:腾讯云 DNSPod
    • Nginx 证书目录:/etc/nginx/ssl/aspu.top_nginx
    • 服务器:Linux
    • 使用 acme.sh

    第一步:安装 acme.sh

    curl https://get.acme.sh | sh
    source ~/.bashrc
    
    或者使用github安装
    git clone https://github.com/acmesh-official/acme.sh.git
    cd ./acme.sh
    ./acme.sh --install -m admin@example.com
    
    安装程序会自动执行三件事
    1. 将 acme.sh 复制到用户主目录下的 ~/.acme.sh/。
    2. 创建命令别名,使你可以直接执行 acme.sh。
    3. 创建每日定时任务,自动检查并续期证书。
    注意 安装完成后,需要关闭当前终端,重新打开终端,才能使用命令别名。

    查看版本:

    acme.sh --version
    

    第二步:创建腾讯云 API 密钥

    登录腾讯云控制台:

    访问管理(CAM) → API 密钥管理

    阿里云 访问 RAM 访问控制 添加用户 创建 AccessKey

    创建:

    SecretId
    SecretKey
    

    例如:

    SecretId = AKIDxxxxxxxxxxxxxxxx
    
    SecretKey = xxxxxxxxxxxxxxxxx
    

    建议不要使用主账号,而是创建一个 CAM 子账号,只授予 DNS 相关权限(例如 DNSPod 管理权限),这样更安全。

    阿里云开启  AliyunDNSFullAccess  权限
    
    腾讯云开启 QcloudDNSPodFullAccess  权限

    第三步:配置 API

    执行:

    
    # 1. 切换到 Let's Encrypt
    acme.sh --set-default-ca --server letsencrypt
    
    # 2. 设置腾讯云 API
    export Tencent_SecretId="你的SecretId"
    export Tencent_SecretKey="你的SecretKey"
    
    如果是阿里云
    export Ali_Key="xxxx"
    export Ali_Secret="xxxx"

    例如:

    export Tencent_SecretId="AKIDxxxxxxxxxxxxxxxx"
    export Tencent_SecretKey="xxxxxxxxxxxxxxxxxxxx"
    

    第一次申请成功后,acme.sh 会把这两个值保存到:

    ~/.acme.sh/account.conf
    

    以后不用再 export。


    第四步:申请证书

    如果申请:

    aspu.top
    www.aspu.top
    

    执行:

    直接申请通配符的  支持 aspu.top  和 *.aspu.top  不支持 a.b.aspu.top
    
    腾讯云
    acme.sh --issue \
        --server letsencrypt \
        --dns dns_tencent \
        -d aspu.top \
        -d '*.aspu.top' \
        --keylength 2048 \
        --force
    
    
    如果是阿里云
    acme.sh --issue \
        --server letsencrypt \
        --dns dns_ali \
        -d aspu.top \
        -d '*.aspu.top' \
        --keylength 2048 \
        --force
    
    
    注意这里生成的是一张证书
    为什么是两个 -d,却只有一张证书?
    - -d aspu.com:添加主域名。
    - -d '*.aspu.com':添加泛域名。
    - 两个域名标识被放进同一张证书的 SAN(主题备用名称)中。
    证书在 /root/.acme.sh/aspu.com 下

    acme.sh 会自动:

    调用腾讯云 API
            │
    新增 _acme-challenge TXT
            │
    等待解析
            │
    Let's Encrypt 验证
            │
    删除 TXT
            │
    签发证书
    

    整个过程无需登录腾讯云后台。


    第五步:安装到你的 nginx

    你的 nginx 已经使用:

    ssl_certificate /etc/nginx/ssl/aspu.top_nginx/aspu.top_bundle.crt;
    ssl_certificate_key /etc/nginx/ssl/aspu.top_nginx/aspu.top.key;
    

    因此执行:

    acme.sh --install-cert -d aspu.top \
      --key-file /etc/nginx/ssl/aspu.top_nginx/aspu.top.key \
      --fullchain-file /etc/nginx/ssl/aspu.top_nginx/aspu.top_bundle.crt \
      --reloadcmd "/usr/sbin/nginx -s reload"
    
    注意替换 aspu.top  为你的域名
    两个文件路径为你的文件路径
    

    如果你的 nginx 是 systemd 管理的,则改成:

    --reloadcmd "systemctl reload nginx"
    
    
    验证 
    openssl pkey -in /ewomail/nginx/conf/ssl_cert/aspu.top_nginx/aspu.top.key -text -noout
    
    正常应该看到类似:
    
    Private-Key: (2048 bit)
    

    第六步:以后会发生什么?

    acme.sh 安装时已经创建了定时任务:

    crontab -l
    

    一般能看到:

    35 0 * * * "/root/.acme.sh"/acme.sh --cron --home "/root/.acme.sh" >/dev/null
    

    每天执行一次。

    流程如下:

    每天运行
        │
    检查证书
        │
    剩余约30天
        │
    自动申请新证书
        │
    覆盖:
    
    /ewomail/nginx/conf/ssl_cert/aspu.top_nginx/
    
        │
    执行
    
    /ewomail/nginx/sbin/nginx -s reload
    

    整个过程不需要人工参与。


    最后提醒一个关键点: dns_tencent 使用的是腾讯云 API(CAM 的 SecretId/SecretKey),不是 DNSPod 的 Token。如果你的域名是在腾讯云 DNS 控制台管理,使用上面的方式即可。若你的域名是在独立 DNSPod 平台管理,则需要使用对应的 dns_dp 插件和 DNSPod 的 API Token。

  • Linux 查看 Python 后台进程实际运行路径和文件路径

    在 Linux 服务器中,经常会使用:

    python3 app.py
    

    启动 Python 程序。

    但是运行一段时间后,通过:

    ps -ef | grep app.py
    

    查看进程时,可能只能看到:

    root     17322 23123  0 Mar24 pts/12   05:28:54 python3 app.py
    

    这里看不到:

    • 使用的是哪个 Python 解释器
    • app.py 文件实际在哪个目录

    这时候可以通过 /proc 查看进程真实信息。


    1. 查看 Python 解释器路径

    先获取进程 PID:

    PID = 17322
    

    执行:

    readlink -f /proc/17322/exe
    

    输出:

    /usr/local/python3.9.13/bin/python3.9
    

    说明这个程序实际使用的 Python:

    /usr/local/python3.9.13/bin/python3.9
    

    而不是系统默认的:

    /usr/bin/python3
    

    2. 查看 app.py 所在目录

    执行:

    readlink -f /proc/17322/cwd
    

    输出:

    /root/newapi/222/fastapi2
    

    这里表示程序启动时所在的工作目录。

    因为启动命令是:

    python3 app.py
    

    所以实际运行的文件就是:

    /root/newapi/222/fastapi2/app.py
    

    3. 一条命令查看完整信息

    以后遇到不知道路径的 Python 服务,可以执行:

    PID=17322
    
    echo "Python路径:"
    readlink -f /proc/$PID/exe
    
    echo "运行目录:"
    readlink -f /proc/$PID/cwd
    
    echo "启动命令:"
    cat /proc/$PID/cmdline | tr '\0' ' '
    

    输出类似:

    Python路径:
    /usr/local/python3.9.13/bin/python3.9
    
    运行目录:
    /root/newapi/222/fastapi2
    
    启动命令:
    python3 app.py
    

    最终可以确定:

    /usr/local/python3.9.13/bin/python3.9 /root/newapi/222/fastapi2/app.py
    

    4. 为什么 uvicorn 可以直接看到路径?

    例如:

    uvicorn main:app --host 0.0.0.0 --port 6010
    

    查看:

    ps -ef | grep uvicorn
    

    通常能看到:

    /usr/local/bin/python3 /usr/local/bin/uvicorn main:app
    

    原因是:

    uvicorn 本身是一个可执行入口文件。

    而:

    python3 app.py
    

    只是 Python 解释器加载脚本,Linux 进程参数只记录:

    python3 app.py
    

    不会自动展开成:

    /usr/local/python3.9.13/bin/python3.9 /root/newapi/222/fastapi2/app.py
    

    5. 生产环境建议

    不要直接:

    python3 app.py
    

    建议使用绝对路径:

    /usr/local/python3.9.13/bin/python3.9 \
    /root/newapi/222/fastapi2/app.py
    

    或者虚拟环境:

    /root/newapi/venv/bin/python \
    /root/newapi/222/fastapi2/app.py
    

    这样以后查看:

    ps -ef
    

    就能快速确认运行环境。


    总结

    需求命令
    查看 Python 路径readlink -f /proc/PID/exe
    查看程序目录readlink -f /proc/PID/cwd
    查看启动参数cat /proc/PID/cmdline | tr '\0' ' '

    Linux 中即使 ps 看不到完整路径,也可以通过 /proc/PID 精确找到 Python 程序真实运行位置。

  • Python 程序后台运行与日志自动管理教程

    本文介绍使用 nohup + tail + logrotate 实现简单稳定的 Python 服务日志管理方案。


    一、Python 程序后台运行

    普通执行:

    python3 app.py
    

    当关闭 SSH 连接后,程序会停止运行。

    可以使用 nohup 将程序放到后台运行:

    nohup python3 -u app.py > /root/logs/app.log 2>&1 &
    
    如果是uvicorn   不需要 -u 本来就是实时输出的
    nohup uvicorn main:app --host 0.0.0.0 --port 8000 > /root/logs/app.log 2>&1 &

    参数说明:

    参数作用
    nohup退出 SSH 后程序继续运行
    -uPython 无缓冲模式,日志实时写入
    > app.log保存程序输出日志
    2>&1错误日志一起写入
    &后台运行

    其中:

    -u
    

    表示 Python 使用 unbuffered(无缓冲)模式。

    开启后:

    • print() 输出立即写入日志
    • tail -f 可以实时看到最新内容
    • 更适合长期运行的后台任务

    二、实时查看运行日志

    程序启动后,可以通过:

    tail -f /root/logs/app.log
    

    实时查看运行状态。

    例如:

    正在启动服务...
    连接数据库成功
    任务执行中...
    

    日志会不断刷新。

    退出查看:

    Ctrl + C
    

    三、配置日志自动清理

    如果程序长期运行:

    app.log
    

    会不断增大。

    当日志达到几个 GB 时,会占用大量磁盘空间。

    可以使用 Linux 自带的 logrotate 自动管理。

    创建配置文件:

    vim /etc/logrotate.d/app
    

    写入:

    /root/logs/*.log {
        daily
        rotate 7
        compress
        missingok
        copytruncate
        dateext
        dateformat -%Y-%m-%d
    }
    
    copytruncate 防止 Python 进程还占用旧文件句柄 写入新文件失败 不重启程序切割日志。
    每天一个文件最多7天

    四、logrotate 配置说明

    每天检查日志

    daily
    

    每天执行一次日志检查。


    限制日志大小

    size 100M
    

    当日志超过 100MB 时自动切割。


    保留历史日志

    rotate 7
    

    最多保留 7 个旧日志:

    app.log
    app.log.1.gz
    app.log.2.gz
    ...
    app.log.7.gz
    

    超过后自动删除。


    压缩旧日志

    compress
    

    旧日志自动压缩:

    app.log.1
    
    ↓
    
    app.log.1.gz
    

    减少磁盘占用。


    不重启程序切割日志

    copytruncate
    

    轮转日志时:

    • 复制旧日志
    • 清空当前日志文件

    程序无需停止或重启。

    适合:

    • Python 脚本
    • 爬虫程序
    • 后台任务
    • nohup 启动程序

    五、测试日志轮转

    查看配置是否正确:

    logrotate -d /etc/logrotate.d/app
    

    立即执行轮转:

    logrotate -f /etc/logrotate.d/app
    

    查看日志目录:

    ls -lh /root/logs/
    

    六、完整使用流程

    1. 启动 Python 程序

    nohup python3 -u app.py > /root/logs/app.log 2>&1 &
    

    2. 查看实时日志

    tail -f /root/logs/app.log
    

    3. 自动日志管理

    系统每天自动执行:

    app.log
          |
          | 超过100MB
          ↓
    app.log.1.gz
    app.log.2.gz
    ...
    app.log.7.gz
    

    自动保留最近 7 份日志,避免日志无限增长。

    七、如何一键重启

    kill 是 根据PID查询  pkill是根据 根据进程名/匹配规则搜索(所以最好先ps -ef|grep "xxx"  看一下是不是自己要的进程)
    
    pkill -f "python3 -u app.py"; nohup python3 -u app.py > /root/logs/app.log 2>&1 &
    
    
    pkill -f "uvicorn main:app"; nohup uvicorn main:app --host 0.0.0.0 --port 8000 > /root/logs/app.log 2>&1 &
    

    总结

    通过:

    • nohup 实现 Python 程序后台运行
    • python3 -u 保证日志实时输出
    • tail -f 实时查看运行状态
    • logrotate (log 肉泰特)自动切割和删除日志

    可以快速搭建一个简单可靠的 Python 服务运行环境,适合服务器脚本、爬虫、API 服务和定时任务等场景。

  • ubuntu设置系统时区

    新安装ubuntu系统可能不是东八区

    查看当前时区  timedatectl
    
    root@xxx:~# timedatectl
                   Local time: Sun 2026-07-19 15:16:02 CST
               Universal time: Sun 2026-07-19 07:16:02 UTC
                     RTC time: Sun 2026-07-19 07:16:02
                    Time zone: Asia/Shanghai (CST, +0800)
    System clock synchronized: yes
                  NTP service: active
              RTC in local TZ: no
    
    首先将硬件时钟设为标准的 UTC 模式(消除报错警告)
    sudo timedatectl set-local-rtc 0
    
    然后设置本地时区为东八区
    sudo timedatectl set-timezone Asia/Shanghai
    
    然后查看  
    timedatectl

  • 快速释放mysql表空间

    方案一(推荐★★★★★):新建表 + 导入最近1个月数据(最快释放空间)

    这是互联网公司最常用的方法。

    例如:

    创建一个和 table1 结构完全相同的新表 table1_new,但不复制任何数据。
    
    CREATE TABLE table1_new LIKE table1;
    

    导入最近一个月:

    INSERT INTO table1_new
    SELECT *
    FROM table1
    WHERE create_at >= NOW() - INTERVAL 1 MONTH;

    确认数据:

    SELECT COUNT(*) FROM table1;
    SELECT COUNT(*) FROM table1_new;

    然后

    RENAME TABLE
    table1 TO table1_old,
    table1_new TO table1;

    观察几天没问题:

    DROP TABLE table1_old;

    立即释放50GB左右空间。

    优点

    ✅ 不会产生大量undo

    ✅ 不会锁很久(只有rename瞬间)

    ✅ DROP TABLE秒完成

    ✅ 空间立即释放

    这是MySQL官方都推荐的大表清理方式。

  • nano编辑器

    nano 的设计哲学就是简单直观。它的核心优势在于,所有常用操作都像菜单一样显示在屏幕底部,几乎不需要学习成本。

    1. 核心特点

    • 开箱即用:打开、编辑、保存、退出,所见即所得。
    • 快捷键提示:底部两行会显示最常用命令的快捷键,^ 代表 Ctrl 键,M- 代表 Meta 键(通常是 Alt 或 Esc)。
    • 轻量快速:占用资源极少,几乎在所有 Linux 系统中都预装。
    • 无模式编辑:没有 Vim 那种“插入/命令模式”的切换概念,敲下字母键就是输入。

    2. 常用操作速查

    这里的 ^ 代表 Ctrl 键。

    • 打开文件:nano 文件名 或 nano -l 文件名 (-l 显示行号)
    • 保存:Ctrl + O,然后按 Enter 确认。
    • 退出:Ctrl + X,若有未保存修改会提示。
    • 剪切一整行:Ctrl + K
    • 粘贴:Ctrl + U
    • 搜索:Ctrl + W,输入关键词后回车,重复操作ctrl+w 回车 (或者 Alt + W)会跳到下一处。
    • 撤销/重做:Alt + U 撤销, Alt + E 重做。
    • 跳转到指定行:Ctrl + _ 或 Ctrl + /,然后输入行号。
    • 显示帮助:Ctrl + G

    3. 进阶技巧

    • 只读模式查看文件:nano -v 文件名
    • 将光标定位到特定行/列:nano +行号,列号 文件名,比如 nano +10,5 test.txt
    • 平滑滚动:加上 -S 参数。
    • 设置选项永久生效:编辑 ~/.nanorc 文件,可配置语法高亮、自动缩进、鼠标支持等。例如加入 set mouse 就能启用鼠标点击定位。
    操作快捷键
    行首Ctrl + A
    行尾Ctrl + E
    文件开头Alt + \
    文件结尾Alt + /