上一篇文章
> Jenkins集成SonarQube代码质量检测
一、实验环境
jenkins环境
jenkins入门与安装
容器为docker
主机 | IP | 系统版本 |
---|---|---|
jenkins | 10.10.10.10 | rhel7.5 |
二、OpenSSH安装
1、下载
官网地址:https://learn.microsoft.com/zh-cn/windows-server/administration/openssh/openssh_install_firstuse
Win32-OpenSSH下载地址:https://github.com/PowerShell/Win32-OpenSSH/releases
下载版本:v9.2.2.0p1-Beta
Windows Server 2019、Windows 10、Windows Server 2022可以直接使用Windows设置安装来安装OpenSSH,可直接参考微软官网中OpenSSH管理Windows进行安装,但是由于本机是winserver2016,所以使用Win32-OpenSSH来进行安装
2、安装
(1)打开PowerShell
在对应目录打开PowerShell
(2)进行安装
powershell.exe -ExecutionPolicy Bypass -File install-sshd.ps1
3、配置OpenSSH服务
如果想方便调用可以设置环境变量
(1)打开防火墙22端口
netsh advfirewall firewall add rule name=sshd dir=in action=allow protocol=TCP localport=22
(2)设置开机自启
Set-Service -Name sshd -StartupType 'Automatic'
(3)启动
Start-Service sshd
三、jenkins配置
1、配置连接用户
系统管理 -->系统配置–>Publish over SSH
2、创建pipeline
注
:Publish over SSH中execCommand后面传入参数,末尾要有个空格
mvn编译通过-pl指定编译模块,如果不需要/usr/local/maven/bin/mvn clean install package -Dmaven.test.skip=true即可
pipeline {
agent any
environment {
PROJECT_NAME="test-monitor"
UPDATE_BAT="D:\\project\\update\\update.bat"
DEST_JAR_PATH="D:\\project\\mission\\${PROJECT_NAME}.jar"
SOURCE_JAR_PATH="C:\\${JOB_NAME}\\${PROJECT_NAME}.jar"
PORT="8709"
}
stages {
stage('git拉取代码') {
steps {
checkout scmGit(branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[credentialsId: 'e87fcb1b-fb2b-xxxx-xxxx-16d1ca8bf5fb', url: 'https://gitee.com/xxxx.git']])
}
}
stage('maven编译代码') {
steps {
sh '''JAVA_HOME=/usr/local/jdk
PATH=$PATH:$JAVA_HOME/bin
/usr/local/maven/bin/mvn clean install package -Dmaven.test.skip=true -pl ${PROJECT_NAME}
'''
}
}
stage('发送到服务器') {
steps {
script() {
deploy()
}
}
}
}
}
def deploy() {
sshPublisher(
publishers: [
sshPublisherDesc(
configName: 'xxxx-winserver-test',
transfers: [
sshTransfer(
cleanRemote: false,
excludes: '',
execCommand: "cmd /c call ${UPDATE_BAT} ${DEST_JAR_PATH} ${SOURCE_JAR_PATH} ${PORT} ",
execTimeout: 120000,
flatten: false,
makeEmptyDirs: false,
noDefaultExcludes: false,
patternSeparator: '[, ]+',
remoteDirectory: "${JOB_NAME}",
remoteDirectorySDF: false,
removePrefix: "${PROJECT_NAME}/target",
sourceFiles: "${PROJECT_NAME}/target/*.jar")],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: false)
])
}
update.bat:
根据业务进行自我修改
@echo off
set "JAR_PATH_NAME_DEST=%1"
set "JAR_PATH_NAME_SOURCE=%2"
set "JAR_PORT=%3"
set CURRENT_TIME=%date:~0,4%%date:~5,2%%date:~8,2%
rem 查找占用指定端口的进程ID
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :%JAR_PORT%') do set "pid=%%a"
if "%pid%"=="" (
echo 没有找到占用端口 %port% 的进程。
) else (
taskkill /pid %pid% /f
)
REM 备份
move %JAR_PATH_NAME_DEST% %JAR_PATH_NAME_DEST%-%CURRENT_TIME%
move %JAR_PATH_NAME_SOURCE% %JAR_PATH_NAME_DEST%
exit 0