通过詹金斯管道的 ssh 和 scp

时间:2021-03-02 13:56:47

标签: jenkins ssh

我是 jenkins 的新手,我试图使用凭证和管道建立 ssh 连接。 当我使用 ssh 等插件时, easy2 SSH, 我能够连接到远程主机并执行任何 shell 命令。 但要求是使用管道脚本,不幸的是出现错误。

代码:

    pipeline {
       agent any
  stages {
    stage('deploy app and reports') {
      steps {
        script {
          withCredentials ([sshUserPrivateKey(credentialsId: 'oracle', keyFileVariable: 'identity', passphraseVariable: '', usernameVariable: 'oracle')]) {
            def remote = [:]
            remote.name = "friendly name"
            remote.host = "ip address"
            remote.allowAnyHosts = true
            remote.user = 'prasad'
            remote.identityFile = identity

           
            sshCommand remote:remote, command: "ls -l"
            sshCommand remote:remote, command: 'ls -l'
            sshCommand remote:remote, command: 'pwd'
          }
        }
      }
    }
  }
}

错误:

**java.lang.NoSuchMethodError: No such DSL method 'sshCommand'** found among steps [ArtifactoryGradleBuild, MavenDescriptorStep, addInteractivePromotion, archive, artifactoryBuildTrigger, artifactoryDistributeBuild, artifactoryDownload, artifactoryEditProps, artifactoryGoPublish, artifactoryGoRun, artifactoryMavenBuild, artifactoryNpmCi, artifactoryNpmInstall, artifactoryNpmPublish, artifactoryNugetRun, artifactoryPipRun, artifactoryPromoteBuild, artifactoryUpload, bat, build, buildAppend, catchError, checkout, collectEnv, collectIssues, conanAddRemote, conanAddUser, deleteDir, deployArtifacts, dir, dockerPullStep, dockerPushStep, echo, emailext, emailextrecipients, envVarsForTool, error, fileExists, findBuildScans, getArtifactoryServer, getContext, git, initConanClient, input, isUnix, jfPipelines, junit, library, libraryResource, load, lock, mail, milestone, newArtifactoryServer, newBuildInfo, newGoBuild, newGradleBuild, newMavenBuild, newNpmBuild, newNugetBuild, newPipBuild, node, parallel, powershell, properties, publishBuildInfo, publishChecks, publishHTML, pwd, pwsh, readFile, readTrusted, resolveScm, retry, rtAddInteractivePromotion, rtBuildAppend, rtBuildInfo, rtBuildTrigger, rtCollectIssues, rtConanClient, rtConanRemote, rtConanRun, rtDeleteProps, rtDockerPull, rtDockerPush, rtDotnetResolver, rtDotnetRun, rtDownload, rtGoDeployer, rtGoPublish, rtGoResolver, rtGoRun, rtGradleDeployer, rtGradleResolver, rtGradleRun, rtMavenDeployer, rtMavenResolver, rtMavenRun, rtNpmCi, rtNpmDeployer, rtNpmInstall, rtNpmPublish, rtNpmResolver, rtNugetResolver, rtNugetRun, rtPipInstall, rtPipResolver, rtPromote, rtPublishBuildInfo, rtServer, rtSetProps, rtUpload, runConanCommand, script, setGitHubPullRequestStatus, sh, sleep, sshagent, stage, stash, step, timeout, timestamps, tm, tool, unarchive, unstable, unstash, validateDeclarativePipeline, waitUntil, warnError, withChecks, withContext, withCredentials, withEnv, withGradle, withMaven, wrap, writeFile, ws, xrayScan, xrayScanBuild] or symbols [Number, Open, all, allBranchesSame, allOf, allowRunOnStatus, always, ant, antFromApache, antOutcome, antTarget, any, anyOf, apiToken, architecture, archiveArtifacts, artifactManager, artifactsPublisher, asIsGITScm, authorizationMatrix, batchFile, booleanParam, branch, branchCreated, branches, brokenBuildSuspects, brokenTestsSuspects, buildButton, buildDiscarder, buildDiscarders, buildRetention, buildUser, buildingTag, caseInsensitive, caseSensitive, certificate, changeRequest, changelog, changeset, checkoutToSubdirectory, choice, choiceParam, cleanWs, clock, close, command, commentPattern, commit, commitChanged, commitMessagePattern, concordionPublisher, configFile, configFileProvider, created, credentials, cron, crumb, cucumber, culprits, defaultFolderConfiguration, defaultView, deleted, demand, dependenciesFingerprintPublisher, description, developers, disableConcurrentBuilds, disableResume, downstream, dumb, durabilityHint, email-ext, envVars, envVarsFilter, environment, equals, exportIpa, expression, file, fileParam, filePath, findbugsPublisher, fingerprint, fingerprints, frameOptions, freeStyle, freeStyleJob, fromScm, fromSource, git, gitBranchDiscovery, gitHub, gitHubBranchDiscovery, gitHubBranchHeadAuthority, gitHubEvents, gitHubExcludeArchivedRepositories, gitHubExcludePublicRepositories, gitHubForkDiscovery, gitHubPRStatus, gitHubPlugin, gitHubPullRequestDiscovery, gitHubSshCheckout, gitHubTagDiscovery, gitHubTopicsFilter, gitHubTrustContributors, gitHubTrustEveryone, gitHubTrustNobody, gitHubTrustPermissions, gitTagDiscovery, github, githubBranches, githubPRAddLabels, githubPRClosePublisher, githubPRComment, githubPRMessage, githubPRRemoveLabels, githubPRStatusPublisher, githubPlugin, githubPullRequests, githubPush, globalConfigFiles, gradle, hashChanged, headRegexFilter, headWildcardFilter, hyperlink, hyperlinkToModels, importDeveloperProfile, inheriting, inheritingGlobal, installSource, invokerPublisher, isRestartedRun, jacocoPublisher, javadoc, jdk, jdkInstaller, jgit, jgitapache, jgivenPublisher, jnlp, jobBuildDiscarder, jobName, junitPublisher, junitTestResultStorage, label, labels, labelsAdded, labelsExist, labelsNotExist, labelsPatternExists, labelsRemoved, lastDuration, lastFailure, lastGrantedAuthorities, lastStable, lastSuccess, legacy, legacySCM, list, local, location, logParser, logRotator, loggedInUsersCanDoAnything, mailer, masterBuild, maven, maven3Mojos, mavenErrors, mavenLinkerPublisher, mavenMojos, mavenWarnings, message, modernSCM, myView, namedBranchesDifferent, noGITScm, node, nodeProperties, nonInheriting, nonMergeable, none, not, openTasksPublisher, overrideIndexTriggers, paneStatus, parallelsAlwaysFailFast, parameters, password, pattern, permanent, pipelineGraphPublisher, pipelineMaven, pipelineTriggers, plainText, plugin, pollSCM, preserveStashes, projectNamingStrategy, proxy, pruneTags, pullRequest, pullRequests, queueItemAuthenticator, quietPeriod, rateLimit, rateLimitBuilds, recipients, requestor, resourceRoot, restriction, restrictions, retainOnlyVariables, rule, run, runParam, sSHLauncher, schedule, scmRetryCount, scriptApproval, scriptApprovalLink, search, security, shell, simpleBuildDiscarder, skipDefaultCheckout, skipStagesAfterUnstable, slave, snapshotDependencies, sourceRegexFilter, sourceWildcardFilter, spotbugsPublisher, ssh, sshPublicKey, sshPublisher, sshPublisherDesc, sshTransfer, sshUserPrivateKey, standard, status, statusOnPublisherError, string, stringParam, suppressAutomaticTriggering, swapSpace, tag, tags, teamSlugFilter, text, textParam, timestamper, timestamperConfig, timezone, tmpSpace, toolLocation, triggeredBy, unlockMacOSKeychain, unsecured, untrusted, upstream, upstreamDevelopers, userSeed, usernameColonPassword, usernamePassword, viewsTabBar, weather, withAnt, xcode, xcodeBuild, zfs, zip] or globals [Artifactory, currentBuild, env, params, pipeline, scm]
    at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:216)
    at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
    at jdk.internal.reflect.GeneratedMethodAccessor983.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1213)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:163)
    at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:157)
    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:161)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:165)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
    at WorkflowScript.run(WorkflowScript:20)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:86)

1 个答案:

答案 0 :(得分:0)

明白了,通过安装 ssh steps 插件解决了这个问题。