Skip to content

Instantly share code, notes, and snippets.

@chilicat
Last active July 10, 2023 02:53
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save chilicat/6486392 to your computer and use it in GitHub Desktop.
Save chilicat/6486392 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()
}
}
@madmas
Copy link

madmas commented Oct 14, 2015

An interesting alternative on using the ant task might be the gradle SSH plugin: https://gradle-ssh-plugin.github.io/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment