Skip to content

Instantly share code, notes, and snippets.

@jbontech
Forked from chilicat/scp-ssh.gradle
Created December 30, 2021 20:05
Show Gist options
  • Save jbontech/1c431ee9a073aafc6d6d50215497c7a6 to your computer and use it in GitHub Desktop.
Save jbontech/1c431ee9a073aafc6d6d50215497c7a6 to your computer and use it in GitHub Desktop.
A simple gradle task to upload a file via SCP to a remote host and to execute a command via SSH on a remote host.
repositories { mavenCentral() }
configurations { sshAntTask }
dependencies { sshAntTask 'org.apache.ant:ant-jsch:1.9.2' }
ant.taskdef(
name: 'scp',
classname: 'org.apache.tools.ant.taskdefs.optional.ssh.Scp',
classpath: configurations.sshAntTask.asPath)
ant.taskdef(
name: 'ssh',
classname: 'org.apache.tools.ant.taskdefs.optional.ssh.SSHExec',
classpath: configurations.sshAntTask.asPath)
task scpAndScpTest() << {
// Create a new file for each execution to make
// sure that execution doesn't fails in case
// idententy of host has been changed.
def knownHosts = File.createTempFile("knownhosts", "txt")
def user = 'root'
def host = '10.129.184.44'
def privateKey = file('keys/myKey')
try {
// Example to copy files to a remote host.
ant.scp(
file: file("build.gradle"),
todir: "${user}@${host}:~",
keyfile: privateKey,
trust: true,
knownhosts: knownHosts
)
// Example to execute a command on the remote host.
ant.ssh(
host: host,
username: user,
keyfile: privateKey,
trust: true,
knownhosts: knownHosts,
command: "ls /"
)
} finally {
knownHosts.delete()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment