Apache Ant – Using scp and sshexec tasks in build.xml

Unlike the Ant Contrib library which could be included thru the <taskdef>, the <scp> and <sshexec> tasks could not be included in this way or it will throw the following errors.

  • A class needed by class org.apache.tools.ant.taskdefs.optional.ssh.Scp
    cannot be found: com/jcraft/jsch/…

 

If you want to make use of the SCP protocol to do file transfer in Apache Ant, first, visit JCraft and download the jsch-0.1.50.jar.

There are 2 ways to enable the <scp> and <sshexec> tasks in the Ant build.xml.

1. Copy the jsch-0.1.50.jar to the $ANT_HOME/lib folder. This is the most straight forward approach but in return you project would have a dependency on the Apache Ant installation of the build environment.

2. The second approach is copy the jsch-0.1.50.jar to somewhere inside your project. For instance, ./ant-lib/jsch-0.1.50.jar. Then when you invoke the Ant, pass the -lib parameter as follow.

  • ant -lib ./ant-lib

 

For Approach 1, you can also remove the ant-jsch.jar in $ANT_HOME/lib and move it to your project ./ant-lib together with jsch-0.1.50.jar. Then in your build.xml, define the <scp> and <sshexec> tasks as follow.

...

<!-- Load the jsch lib -->
<available property="ant-jsch.present" file="${ant.home}/lib/ant-jsch.jar"/>
<fail if="ant-jsch.present" message="Please remove ant-jsch.jar from ANT_HOME/lib see [http://ant.apache.org/faq.html#delegating-classloader]"/>
<path id="jsch.class.path">
  <pathelement location="./ant-lib/ant-jsch.jar" />
  <pathelement location="./ant-lib/jsch-0.1.50.jar" />
</path>
<taskdef name="scp" classname="org.apache.tools.ant.taskdefs.optional.ssh.Scp" classpathref="jsch.class.path" />
<taskdef name="sshexec" classname="org.apache.tools.ant.taskdefs.optional.ssh.SSHExec" classpathref="jsch.class.path" />

...

 

It will fail if the ant-jsch.jar exists in $ANT_HOME/lib and ask the user to remove it first. And both ant-jsch.jar and jsch-0.1.50.jar will be included during runtime.

There is another dependency-free approach suggested by Marcond but i haven’t tried. You can refer to it @ StackOverflow – Is there a way to specify the location of a local jsch.jar from within build.xml?.

Done =)

Reference:

Advertisements

One thought on “Apache Ant – Using scp and sshexec tasks in build.xml”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s