Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use ant <exec> to execute commands on linux?

Tags:

java

linux

ant

I would like to use ant to exectue a command like below:

<exec executable="echo ptc@123 | sudo -S /app/Windchill_10.0/Apache/bin/apachectl -k stop">
</exec>

But it replies an error say

The ' characters around the executable and arguments are not part of the command.

The background is: I want to use ant to stop the apache server but it doesn't installed by the same user I run the command.

Anyone could help or give me some clues?

Thanks in advance

like image 393
user3153661 Avatar asked Jan 02 '14 12:01

user3153661


1 Answers

Ant's <exec> task uses Java's Process mechanism to run commands, and this does not understand shell-specific syntax like pipes and redirections. If you need to use pipes then you have to run a shell explicitly by saying something like

<exec executable="/bin/sh">
  <arg value="-c" />
  <arg value="echo ptc@123 | sudo -S /app/Windchill_10.0/Apache/bin/apachectl -k stop" />
</exec>

but in this case it's not necessary, as you can run just the sudo command and use inputstring to provide its input rather than using a piped echo:

<exec executable="sudo" inputstring="ptc@123&#10;">
  <arg line="-S /app/Windchill_10.0/Apache/bin/apachectl -k stop" />
</exec>

Since sudo -S requires a newline character to terminate the password, I've added &#10; on the end of the inputstring (this is the simplest way to encode a newline character in an attribute value in XML).

Note that <arg line="..." /> is pretty simple minded when it comes to word splitting - if any of the command line arguments could contain spaces (for example if you need to refer to a file under a directory such as ${user.home}/Library/Application Support or if the value is read from an external .properties file that you don't control) then you must split the arguments up yourself using separate arg elements with value or file attributes, e.g.:

<exec executable="sudo" inputstring="ptc@123&#10;">
  <arg value="-S" />
  <arg file="${windchill.install.path}/Apache/bin/apachectl" />
  <arg value="-k" />
  <arg value="stop" />
</exec>
like image 165
Ian Roberts Avatar answered Oct 21 '22 13:10

Ian Roberts