分享程式代碼相關筆記
目前文章總數:190 篇
最後更新:2025年 07月 26日
如果我們用 sshpass 的語法在 Jenkins 的 Pipeline 中訪問遠端,雖然可正常訪問,但密碼會透漏在 Console Log 中
這是必須避免的
首先要於 Jenkins 主機內產生一對新的 SSH 金鑰,目的是為了可以 SSH 訪問用
登入 Jenkins Server -> 然後輸入以下指令
ssh-keygen -t rsa -b 4096 -C "louistest@sshconnect" -f ~/.ssh/jenkins_key
以下是參數與說明
ssh-keygen | 用來產生 SSH 金鑰對的指令。 |
-t rsa | 金鑰類型(type)為 RSA。現在建議使用 ed25519,但 RSA 在一些舊系統仍廣泛支援。 |
-b 4096 | 指定 RSA 金鑰長度為 4096 bits(比預設的 2048 更安全) |
-C “louistest@sshconnect” | 加一段註解,通常是 email 或用途說明。這段會附在公開金鑰裡,方便辨識。 |
-f ~/.ssh/jenkins_key | 指定金鑰檔案的儲存路徑與檔名:~/.ssh/jenkins_key是私鑰 ; ~/.ssh/jenkins_key.pub 是公開金鑰 |
並且會要求輸入 passphrase ,可以選擇不輸入,便於 Jenkins 有關係的主機訪問用。
接著可進入 Jenkins Server 的 root/.ssh/ 目錄下,確認是否有產生私鑰、公鑰
假設我們現在要訪問的機器是 192.168.51.93 ,我們可以從 Jenkins Server 下輸入:
ssh-copy-id -i ~/.ssh/jenkins_key.pub root@192.168.51.93
如果成功將公開金鑰複製到遠端機器,可以看到關鍵字:Number of key(s) added: 1,表示複製成功
更安全的確認方式是直接訪問該目錄 ~/.ssh/jenkins_key ,可輸入以下:
ssh -i ~/.ssh/jenkins_key root@192.168.51.93 "hostname -I && whoami"
如果正確可以看到類似如下的訊息
接著要在 Jenkins 設定 Credentials ,將剛剛產生的金鑰匯入
登入 Jenkins Web-UI -> System -> Global credentials (unrestricted) -> 選擇 Add Credentials
依序將 ID , UserName , Passphrase , Private Key
※如果再 Step 1. 沒有輸入 Passphrase 這裡可以空白
※範例這邊的 ID 用 ssh-remote
至於 Private Key 的來源可看 Step 7.
私鑰就是 Jenkins Server 我們 Step 1. 產生的,檔案位置在 root/.ssh/jenkins.key
開啟後,將所有的內容複製,並且貼上於 Step 6. Private Key 的位置
我們新建一個 Pipeline Job ,並且貼上以下範例代碼
關鍵在於使用憑證 withCredentials ,模式為 sshUserPrivateKey,並且用剛剛設定的 ID : ssh-remote
此 Pipeline 的目的有 2 點:
1. 可透過 SSH 訪問連線 192.168.51.93 |
2. 連線後訪問 192.168.51.93 的目錄 /var/log |
pipeline {
agent any
stages {
stage('SSH to remote host') {
steps {
withCredentials([
sshUserPrivateKey(
credentialsId: 'ssh-remote',
keyFileVariable: 'SSH_KEY',
usernameVariable: 'SSH_USER'
)
]) {
sh """
ssh -i "\$SSH_KEY" -o StrictHostKeyChecking=no "\$SSH_USER@192.168.51.93" hostname && \
ls -al /var/log
"""
}
}
}
}
}
接著進行建置,可以從 Console Log 確認,密碼資訊都變為星號 ,成功避免外洩密碼的問題,並達到成功訪問遠端主機的效果
建置成功 :
隱藏密碼:
另一種訪問 SSH 的方法是安裝 Jenkins Plugings 的 SSH Agent,使用此插件可以讓 Pipeline 腳本更精簡
登入 Jenkins Web-UI -> 管理 Jenkins -> Plugings -> 安裝 SSH Agent 這個插件
訪問此插件可以知道用途為 SSH 訪問
並且提供如何設定的教學,此教學與上述我們設定 Jenkins 憑證是相同的
我們新建 Pipeline Job ,並且貼上以下範例代碼,增加了第 2 個 Stage
關鍵在於 sshagent(credentials: [‘ssh-remote’]),完成了大部分憑證的設定,更精簡了我們的代碼
pipeline {
agent any
stages {
stage('SSH to remote host') {
steps {
withCredentials([
sshUserPrivateKey(
credentialsId: 'ssh-remote',
keyFileVariable: 'SSH_KEY',
usernameVariable: 'SSH_USER'
)
]) {
sh """
ssh -i "\$SSH_KEY" -o StrictHostKeyChecking=no "\$SSH_USER@192.168.51.93" hostname && \
ls -al /var/log
"""
}
}
}
stage("SSH Agent to remote host") {
steps {
sshagent(credentials: ['ssh-remote']) {
sh '''
ssh -o StrictHostKeyChecking=no 192.168.51.93 hostname && \
ls -al /var/log
'''
}
}
}
}
}
接著進行建置,可以從 Console Log 確認,密碼資訊直接消失,也避免外洩密碼的問題,並達到成功訪問遠端主機的效果
建置成功 :
Console Log 密碼資訊不存在: