Ant: Using Secure Copy (scp) to Copy Files to Servers

During my Java class, we have 2 different deployment machines: one for the MySQL server and another for the web server.

Since the remote server is not configured to accept any ftp connections, I am forced to use scp. It’s a pain to manually scp my file manually to the web server, so I did a bit of research and found a good way to securely copy my file (to the web server).


I looked at the ant optional tasks in the manual and it does include the scp. The manual mentions:
Note: This task depends on external libraries not included in the Ant distribution. See Library Dependencies for more information. This task has been tested with jsch-0.1.2 to jsch-0.1.14.

Doing a Google search on “scp jsch” yields the following web site: http://www.jcraft.com/jsch/. I downloaded the jsch-0.3.0.jar, but you can download the jsch-0.3.1.jar now.

Once the jar has been downloaded, I put the file in my $ANT_HOME/lib.

What I want is to shut the web server down and to put the new war file. Here is a portion of my build.xml:
<target name=”deploy_server” depends=”compile,build_general”>
<echo message=”Shutting down remote tomcat…” />
<sshexec host=”my.web.server” username=”${username}” password=”${password}” command=”~/tomcat/bin/shutdown.sh” />
<scp file=”${dist}/${war.name}” todir=”${username}:${password}@my.web.server:~/tomcat/webapps” />
<sshexec host=”my.web.server” username=”${username}” password=”${password}” command=”~/tomcat/bin/startup.sh” />
</target>

Notice how I use ${username} and ${password} from hard-coding my username and password in the build.xml.

I run the new ant target using the following command:
ant -Dusername=handy -Dpassword=mypassword

Leave a Reply