Jenkins 使用ssh 传输文件的插件很多,比如SSH plugin, SCP publisher,Publish Over SSH,pipeline脚本可以用 SSH Pipeline Steps,如果你不想用插件,也可以直接通过命令进行复制
Jenkins 使用Publish Over SSH插件传输文件如图所示,文件路径为相对路径
可以使用pipeline 脚本为
sshPublisher(
publishers: [
sshPublisherDesc(
configName: '30.208',
transfers: [
sshTransfer(
cleanRemote: false,
excludes: '',
execCommand: '',
execTimeout: 120000,
flatten: false,
makeEmptyDirs: false,
noDefaultExcludes: false,
patternSeparator: '[, ]+',
remoteDirectory: '/home/software/microservice-docker-jars',
remoteDirectorySDF: false,
removePrefix: 'target',
sourceFiles: 'target/*.jar'
)
],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: true
)
]
)
使用 SSH Pipeline Steps 插件并结合withCredentials 如下:
def remote = [:]
remote.name = "node-1"
remote.host = "10.000.000.153"
remote.allowAnyHosts = true
node {
withCredentials([sshUserPrivateKey(credentialsId: 'sshUser', keyFileVariable: 'identity', passphraseVariable: '', usernameVariable: 'userName')]) {
remote.user = userName
remote.identityFile = identity
stage("SSH Steps Rocks!") {
writeFile file: 'abc.sh', text: 'ls' #写入脚本
sshCommand remote: remote, command: 'for i in {1..5}; do echo -n \"Loop \$i \"; date ; sleep 1; done'
sshPut remote: remote, from: 'abc.sh', into: '.'
sshGet remote: remote, from: 'abc.sh', into: 'bac.sh', override: true
sshScript remote: remote, script: 'abc.sh'
sshRemove remote: remote, path: 'abc.sh'
}
}
}
sshPut 正则匹配写法如下:
sshPut remote: remote, from: './target/', filterRegex: /\.jar$/, into: '/data/software/jars'
但是sshPut 在实际使用过程中,当我们利用正则匹配匹配target下的jar包,无法仅复制文件夹中的文件。总是将整个文件夹复制过去,该插件没有给出很好的解决方案 (或许可以使用filterBy,filterRegex参数进行过滤,感兴趣的可以试试)。
比较好的解决方案如下:
findFiles(glob: 'Build/rpms/*.rpm').each { rpmFile ->
sshPut remote: remote, from: rpmFile.path, into: '/data/mirror/rpm-repo'
}
findFiles依赖插件:Pipeline Utility Steps,否则会报错:java.lang.NoSuchMethodError: No such DSL method ‘findFiles’ found among steps
遇到的问题
Also: hudson.remoting.Channel$CallSiteStackTrace: Remote call to linux-centos-slave2
at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1797)
at hudson.remoting.UserRequest$ExceptionResponse.retrieve(UserRequest.java:356)
at hudson.remoting.Channel.call(Channel.java:1001)
at org.jenkinsci.plugins.sshsteps.steps.PutStep$Execution.run(PutStep.java:98)
at org.jenkinsci.plugins.sshsteps.util.SSHStepExecution.lambda$start$0(SSHStepExecution.java:84)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
com.jcraft.jsch.JSchException: channel is not opened.
at com.jcraft.jsch.Channel.sendChannelOpen(Channel.java:765)
at com.jcraft.jsch.Channel.connect(Channel.java:151)
at com.jcraft.jsch.Channel$connect.call(Unknown Source)
at org.hidetake.groovy.ssh.operation.DefaultOperations.sftp(DefaultOperations.groovy:66)
at org.hidetake.groovy.ssh.operation.Operations$sftp$0.call(Unknown Source)
原因:sshPut执行超时
解决方法:修改pipeline脚本中SSH Pipeline Steps 相关的remote配置,参考
增加: remote.timeoutSec = 60