Jay Kandy
Posts: 77
Nickname: jay
Registered: Mar, 2002
|
|
Re: executing a unix shell command using jsp
|
Posted: Mar 29, 2002 12:50 PM
|
|
Patrick,
Firstly, this is not a universal solution. I mean you can not run any *NIX command with this class. In a perfect world, you might want to check for ErrorStream, wait appropriately for a command to finish, etc...For simplicity's sake I ignored all those cases. This class runs commands that dont expect an input from command line during the process of execution. (For example 'passwd')
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class RunCommand
{
public static String execute(String[] cmd)
{
String output = null;
try
{
String line;
StringBuffer buffer = new StringBuffer();
Runtime rt = Runtime.getRuntime();
Process process = rt.exec(cmd);
InputStreamReader isr = new InputStreamReader( process.getInputStream() );
BufferedReader br = new BufferedReader( isr );
while( ( line = br.readLine() ) != null )
{
buffer.append( line );
}
int exitValue = process.waitFor();
System.out.println( "ExitValue: " + exitValue );
output = buffer.toString();
}
catch (Throwable t)
{
t.printStackTrace();
}
return output;
}
/**
* Usage:
*
* public static void main(String s[])
* {
* String cmd[] = new String[1];
* cmd[0] = s[0];
*
* System.out.println( RunCommand.execute( cmd ) );
* }
*/
}
Deploy the class in WEB-INF/classes directory and within the JSP, use <jsp:useBean id="rc" scope="session" class="RunCommand"/>
<% String cmd[] = String[1]; cmd[0] = "dir" %> <% RunCommand.execute( cmd ); %>
Also note: I did not test with whois command. (My *NIX machine is not on LAN )
Sincerely, Jay
|
|