Friday, December 14, 2007

How to Execute Linux Machine Command using Java from Windows Operating System?

Here, In this example, we are execute Linux machine command using Java from windows operating machine.

In Java, This can be achieved using Command Prompt. To access any runtime (say DOS) we need an access to that Runtime. We can access runtime using Runtime class.

Runtime class has a static method called getRuntime() which returns Runtime object.
Then with exec() method we can have access to that runtime command.

To access Linux machine, we need plink - ( a command-line interface to the PuTTY back ends ) which can be downloaded from the following URL,

http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

Here, Is the code snippet that will do the work.


class RuntimeTest
{
public static void main(String[] args)
{
try
{
Runtime runtime= Runtime.getRuntime ();

// Here , we have to access command line to run plink utility as well provide username , password and comman to execute on linux machine.

Process pro = runtime.exec("cmd /c plink.exe root@192.168.0.247 -pw nki.6300 mkdir test13456");

// Wait for the result of process.

int i = pro.waitFor();

if(i==0)
{
System.out.println("Exceuted");
}

}
catch(Exception ex)
{
System.out.println(ex);
}
}
}