2025年12月15日 星期一

SSH 連線時自訂 PS1 提示符 (Ubuntu為例)

SSH 連線時自訂 PS1 提示符 (Ubuntu為例)

以 Ubuntu 預設彩色提示符為例



方式一:臨時一次性使用(連線後手動執行)

連線進去後,直接在終端機貼上執行:

export PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

說明:

  • 只對當前 session 有效,登出後就消失
  • 不需要任何設定檔修改
  • 適合臨時想換個提示符樣式試試看



方式二:修改遠端伺服器設定

在遠端伺服器的 ~/.bashrc 加入:

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

優點:

  • 不影響 scp/rsync 等檔案傳輸功能
  • 所有連線方式都自動套用
  • 不用記複雜的命令
  • 最簡單、最推薦的做法



方式三:連線時指定命令(命令列參數)

每次連線時加上參數:

ssh myserver -t 'export PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "; exec bash'

說明:

  • -t — 等同於 RequestTTY yes,強制分配 TTY
  • 單引號包住整個命令,避免本地 shell 先展開變數
  • 適合偶爾需要或寫成別名使用



方式四:寫在 SSH Config 中(本地端設定)

在本地的 ~/.ssh/config 中設定:

Host myserver
    HostName example.com
    User ubuntu
    RequestTTY yes
    RemoteCommand bash -c 'export PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "; exec bash'

說明:

  • RequestTTY yes — 強制分配終端,否則 RemoteCommand 無法正常互動
  • RemoteCommand — 連線後自動執行的命令,用 exec bash 確保留在互動式 shell
  • 連線方式:直接 ssh myserver

注意事項:

  • 使用 RemoteCommand 後,scprsync 等檔案傳輸會失效(因為它會執行指定命令而非預設 shell)
  • 如果需要傳檔案,要另外建一個不帶 RemoteCommand 的 Host 設定




補充:PS1 提示符格式說明

對照格式

\[\033[01;32m\]  → 亮綠色開始
\u              → 使用者名稱
@               → @ 符號
\h              → 主機名稱
\[\033[00m\]    → 重設顏色
:               → : 符號
\[\033[01;34m\] → 亮藍色開始
\w              → 當前完整路徑
\[\033[00m\]    → 重設顏色
\$              → 一般用戶顯示 $,root 顯示 #



2025年12月4日 星期四

自動初始化 Git 倉庫一個空 README.md 當作起點的腳本

自動初始化 Git 倉庫一個空 README.md 當作起點的腳本

這不是必要的,只是我通常習慣第一點用空 README.md 來當作起始,寫個腳本之後要複製比較容易

# 自動初始化Git倉庫腳本
function Initialize-GitRepository {
    [CmdletBinding()]
    [Alias("igr")]
    param(
        [Parameter(Position = 0)]
        [string]$Path = ".",

        [Parameter()]
        [string]$ReadmeFileName = "README.md",

        [Parameter()]
        [string]$CommitMessage = "Init"
    )

    # 啟用嚴格模式
    Set-StrictMode -Version Latest
    $ErrorActionPreference = 'Stop'

    # 切換到指定目錄
    $originalLocation = Get-Location
    Set-Location $Path

    # Git 包裝函式 - 自動檢查錯誤並拋出例外
    function git {
        & (Get-Command git.exe -CommandType Application) @args
        if ($LASTEXITCODE -ne 0) {
            Write-Error "Git command failed: git $($args -join ' ') (exit code: $LASTEXITCODE)"
        }
    }

    try {
        # ==================== 預檢查階段 ====================
        # 檢查 README 檔案是否已存在
        if (Test-Path $ReadmeFileName) {
            Write-Error "Error: $ReadmeFileName file already exists!"
        }
        # 檢查 Git 倉庫是否已存在
        if (Test-Path ".git") {
            Write-Error "Error: Git repository already exists!"
        }
        # 檢查 Git 命令是否可用
        try {
            git --version | Out-Null
        } catch {
            Write-Error "Error: Git is not installed or not in PATH!"
        }

        # ==================== 執行階段 ====================
        # 創建 README 檔案
        New-Item -Name $ReadmeFileName -ItemType File | Out-Null
        # 初始化Git倉庫
        git init
        # 添加檔案並提交
        git add $ReadmeFileName
        # 提交
        git commit -m $CommitMessage

    } catch {
        throw
    } finally {
        Set-Location $originalLocation
    }
}





PowerShell 產生隨機密碼

經常用到每次都要查有點煩了,乾脆弄個函式寫到系統中,呼叫的時候比較方便

在 PowerShell 中輸入 $PROFILE 會顯示出每次 PowerShell 載入時讀取的腳本,可以把以下函式寫到裡面去,這樣打開 PowerShell 只要輸入 nrp 就可以產出密碼了

(第一次創建的時候需要設定權限不然會錯,那個複製錯誤信息Google或問AI就可以解了)

以下是產密碼的函式

# Generate a random password
function New-RandomPassword {
    [Alias('nrp')]
    param (
        [Parameter(Position = 0)]
        [ValidateRange(1, 512)]
        [int]$Length = 15,
        [switch]$Symbols,
        [switch]$Ambiguous,
        [string]$IncludeCharacters,
        [string]$ExcludeCharacters
    ) $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    if (-not $Ambiguous) { $chars = $chars -replace '[lIO01]', '' }
    if ($Symbols) { $chars += '!@#$%^&*()-_=+' }
    if ($IncludeCharacters) { $chars += $IncludeCharacters }
    if ($ExcludeCharacters) { $chars = -join $chars.ToCharArray().Where{ $ExcludeCharacters.IndexOf($_) -lt 0 } }
    if ($chars.Length -eq 0) { Write-Error "Character set is empty after exclusions"; return }
    $rng = [Security.Cryptography.RandomNumberGenerator]::Create()
    try {
        $rng.GetBytes(($bytes = [byte[]]::new($Length * 8)))
        -join (0..($Length - 1)).ForEach({ $chars[[BitConverter]::ToUInt64($bytes, $_ * 8) % $chars.Length] })
    } finally { $rng.Dispose() }
} # New-RandomPassword

預設使用 New-RandomPassword 或是 ‘nrp’ 會產出 15 碼的隨機密碼 (預設不包含易造成混亂的 lIO01 字元)

如果需要複雜包含符號,可以使用 -Symbols 與 -Ambiguous 參數
要定義字元可以使用 -IncludeCharacters -ExcludeCharacters 參數
顯式指定與 Symbols / Ambiguous 有衝突時顯式優先級更高