Executing Unix shell from Java Program

Hi,
I have written a java application using Maverick J2sshtools API which connects to a Unix box using SSH.The program authenticates with the remote box successfully,but It dosen't return the environment info or execute the test script.Have attached the complete code.
package shellInteraction;
import com.maverick.ssh.*;
import com.maverick.ssh2.Ssh2Client;
import com.maverick.ssh2.Ssh2Context;
import com.maverick.ssh2.Ssh2PasswordAuthentication;
import com.sshtools.net.*;
import java.io.*;
import java.util.Iterator;
import java.util.Vector;
public class JavaShell{
     public static void main(String[] args) {
          SshConnector con = null;
          SshClient ssh = null;
          ShellProcess process = null;
          Shell shell = null;     
          try{
               // Create a session to remote host
               con = SshConnector.getInstance();
               ssh = connectionSetup(con);
               System.out.println(ssh);
               // Start a session and do basic IO
               if (ssh.isAuthenticated()) {
                    shell = new Shell(ssh);
                    System.out.println("Authenticated");
                    if(shell.getEnvironment().hasEnvironmentVariable("hostname"))
                         System.out.println("We are connected to " + shell.getEnvironment().getEnvironmentVariable("hostname"));
                    //System.out.println("Remote operating system is " + shell.getEnvironment().getOperatingSystem());
               //     boolean isWindows = shell.getEnvironment().getOSType()==ShellEnvironment.OS_WINDOWS;
                    //if(shell.getEnvironment().hasEnvironmentVariable("USERPROFILE")) {
                         //System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("USERPROFILE"));
                    //} else if(shell.getEnvironment().hasEnvironmentVariable("HOME")) {
                         //System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("HOME"));
                    // Commands only executed for Unix OS
                    //if(!isWindows) {
                         // Execute a script
                         traverseDirectory(shell);
               shell.exit();
               ssh.disconnect();
               System.out.println("Shell has exited");
          } catch(Throwable t) {
               t.printStackTrace();
     private static void traverseDirectory(Shell shell) throws Exception{
          System.out.println("\n\nTraverse Directory");
          // Execute a simple script than prints a directory tree
          ShellProcess process = shell.execute("bash test.sh ");
          try{
               process.expect("Total directories", 1000, true);
               System.out.print(process.toString());
          } catch (ShellTimeoutException ex1) {
               System.out.println("TRAVERSE Expect operation timed out. Sending interrupt to kill the process");
               process.interrupt();
          }finally {
               process.close();
     static private Ssh2Client connectionSetup(SshConnector con)throws SshException{
          Ssh2Client ssh = null;
          final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
          try {
               System.out.print("Hostname: ");
               String hostname = reader.readLine();
               int idx = hostname.indexOf(':');
               int port = 22;
               if(idx > -1) {
                    port = Integer.parseInt(hostname.substring(idx+1));
                    hostname = hostname.substring(0, idx);
               System.out.print("Username [Enter for " + System.getProperty("user.name") + "]: ");
               String username = reader.readLine();
               if(username==null || username.trim().equals(""))
                    username = System.getProperty("user.name");
               System.out.println("Connecting to " + hostname);
               * Create an SshConnector instance
               con = SshConnector.getInstance();
               // Lets do some host key verification
               HostKeyVerification hkv = new PasswordHostKey();
               con.setSupportedVersions(SshConnector.SSH2);
               * Set our preferred public key type
               con.getContext(SshConnector.SSH2).setHostKeyVerification(hkv);
               ((Ssh2Context)con.getContext(SshConnector.SSH2)).setPreferredPublicKey(Ssh2Context.PUBLIC_KEY_SSHDSS);
               * Connect to the host
               ssh = (Ssh2Client)con.connect(new SocketTransport(hostname, port), username, true);
               * Authenticate the user using password authentication
               Ssh2PasswordAuthentication passwordAuthentication = new Ssh2PasswordAuthentication();
               System.out.print("Password: ");
               passwordAuthentication.setPassword(reader.readLine());
               if(ssh.authenticate(passwordAuthentication)!=SshAuthentication.COMPLETE) {
                    System.out.println("Authentication failed!");
                    System.exit(0);
          }catch(Exception ex1) {
               throw new SshException(ex1.getMessage(), ex1.getCause());
          return ssh;
When I execute the program
Hostname:****
Username [Enter for thaya]: **
Connecting to CATL
The connected host's key (ssh-dss) is
b6:85:91:6b:8b:ea:cb:40:b5:6f:01:2e:66:78:7f:62
Password: *****
SSH2 CATLMSXP62:22 [kex=diffie-hellman-group1-sha1 hostkey=ssh-dss client->server=aes128-cbc,hmac-sha1,none server->client=aes128-cbc,hmac-sha1,none]
Authenticated
Traverse Directory
com.maverick.ssh.ShellTimeoutException: The shell did not return to the prompt in the given timeout period 10000ms
     at com.maverick.ssh.Shell.A(Unknown Source)
     at com.maverick.ssh.Shell.execute(Unknown Source)
     at shellInteraction.ShellInteraction.traverseDirectory(ShellInteraction.java:108)
     at shellInteraction.ShellInteraction.main(ShellInteraction.java:68)
This is the error message what i get.

use code tags if you want a response,
ive done the same thing once using
ssh2.ethz.ch ie:
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ServerHostKeyVerifier;
import ch.ethz.ssh2.Session;
the code looked something like this:
try
               conn.connect(new ServerHostKeyVerifier() {
                    public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
                         return true;
              conn.authenticateWithPassword(username, password);
              try {
                   sess = conn.openSession();
               } catch (java.lang.IllegalStateException e) {
                    return;
//                    JOptionPane.showMessageDialog(null, "Could not autheticate.\nCheck username and password.\nTerminating.", "Authentication Failed", JOptionPane.ERROR_MESSAGE);
//                    System.exit(-1);
               sess.requestPTY("dumb", 50, 50, 0, 0, null);
               sess.startShell();
          }and after that sess has getStdIn() and getStdOut() that get the streams from which you read and write.

Similar Messages

  • Execute Unix command from Java program running on windows

    Hello,
    I need to write a java program that fetches file count in a particular unix machine directory. But java program will be running on windows machine.
    The program should execute unix list command and fetch the output of that command.
    Can anyone help me on this?
    Thanks.

    Hi there,
    I had a similiar problem, though years ago. It was to have a java program execute any other. Lately, I've had to have a java program running on a unix machine execute a shell script. Entirely two different scenarios. I'm not sure what you will need for your app, but look into this:
    Java Native Interface for executing C/C++ code.
    C/C++ Code for launching the program you need to run.
    java.lang.Runtime(?).exec(....)
    With a combination of that stuff, you can make a launcher for any os that has Java running on it, and with Runtime, you can exec() pretty near any sort of unix shell or app command you'd like.
    Good luck.
    Tim

  • How execute Unix script from java?

    Can I execute Unix script from java?

    Yes. Using ProcessBuilder. And read [When Runtime.exec() wont|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]. It's old, but pretty much all of it is still true.

  • Is it possible to execute SAPGUI scripts from java program?

    Hi everyone..
         I need to develop an java applications that executes the SAPGUI script or any technique that execute set of transaction as client.
         Is it possible to execute SAPGUI scripts from java program? if so, how it can be achieved? is there any other technique to achieve above mention scenario?.
         it will be more helpful, if docs related to that are shared..
         Thanks in advance

    Oh, bummer. Would be much more convenient if I could just use iTunes for everything. Can't stand WMP. I wonder if WinAmp might be a good compromise?
    Thanks for this answer . . .
    Sharon

  • Execute unix commands from Java

    Hi,
    I have a client application running on windows. This client should connect to a unix server and check for the existence of a file and display the result as "File found/File not found". In order to connect from windows to the unix server, I used the sockets and the connection is successfully established. The second part is to check for the presence of the file in unix server. I searched in google.com and the option I found to execute a unix command from java is the "Runtime.exec()". Runtime.exec is considered as the less effective (not a favorable) one.
    Is there any other option available (other than the Runtime) to execute the unix command from java? Can you please let me know.
    Thanks a lot
    Aishu

    So, please let me know how I can execute the above unix commands without Runtime.exec()You have a client and a server.
    You want something to run on the server, not the client.
    That means that something must in fact being running on the server before the client does anything at all.
    For example telnet. Or a J2EE server application.
    So is something like that running?
    If not then there absolutely no way to do what you want, even with Runtime.exec().
    If yes then what you do depends on what is running. So Runtime.exec() would be pointless if a J2EE server was running.

  • How to invoke dos shell from java program

    Hi,
    I'm not able to invoke dos shell from java.
    Can any one help me in this issue.
    I'm providing the source code below:
    try{
    Runtime.getRuntime().exec("cmd.exe")
    catch(IOException e) {
    System.out.println(e.getStackTrace());
    Thanks

    Does it throw a different exception?
    Or does it just do nothing at all?
    It does nothing at all[/b
    Is this a standalone Java app?
    Or a Java Applet running via a webbrowser? [b]It's a standalone application

  • Problem executing Unix script from Java...

    Hi there, I'm having trouble executing a unix script from a java program. The script receives multiple parameters and it seems that one of them ( or more ) is not well interpreted. When I run the script directly from a shell, the script executes without any errors. But, when I run the exact same script with the exact same parameters, it does not work.
    Here is the command to execute the script with all the parameters that is executed from the shell ( with success ) and also from the java program ( with errors ):
    /z/opus/dcap/intfu001.csh 'NODEBUG^NOTKPROF^NOSTACK' opus dcap JACQUES JACQUES '2625781' 'ORA$PIPE$001D00D70001' JOB^DEBUG^SINISIMU^STATPROD^DECTIDANC^81^503^4080^86^87^151^97^98^99 BUT^N^N^SPRI^0^13^24^3^J^05^N^19^19^19 >> /tmp/switcher8.999.null.pgm.test
    And here is my portion of code that executes the script:
    Runtime wShell = Runtime.getRuntime();
    Process wProc = wShell.exec(cmd_unix_final);
    wProc.waitFor();
    return wProc.exitValue();
    Please give me your thoughts on this!
    Thanks in advance!

    Ok.
    Let's proceed surgically, else we'll never solve or overcome anything.
    In the last your reply you wrote:
    the normal output is what I get when the script runs successfully, the script first prints a few things
    and then does stuff that takes at least 2 or 3 secondsWhat do you mean?
    -Finally have you got your script correctly executed?
    The stuffs you spoke of are really performed?
    If this is the case I can't see the prob.
    Is your concern only about exitValue() for it doesn't let you distinguish programmatically
    the success or failure of the script execution?
    Of course you surely already have a routine in your java code to handle
    exceptional situations of errors from the script.
    And the "normal output" is just what you must parse to detect those errors.
    Then who cares about exitValue() in this case?
    Don't invoke it, relay on the stdout and stderr of the script.
    -Or you get only a deceiving standard output
    that let you think the script execution went alright, while instead it didn't.
    In this case we have to investigate some other thing.
    I can't still exclude that the problem isn't related with the buffer size of the stdout
    allocated by the environment to the subprocess. You spoke of few things printed out.
    Be explicit. What's the size of the output you get?
    And is the "normal output" complete till the very last char
    or is it truncated from somewhere on?
    Also it's important that you hit a ps command after the java main process terminates
    (or simply when waitFor() returns) and see if the script subprocess hung up.
    As an alternative approach directly call your pro*C code from Java through JNI, instead of translating it.
    1. Exec.java
    public class Exec{
         static{
              System.loadLibrary("Exec");
         public static native void proCFunct();
         public static void main( String[] args){
              proCFunct();
    }2. javac Exec.java
    3. javah Exec
    4.Exec.c
    #include "Exec.h"
    JNIEXPORT void JNICALL Java_Exec_proCFunct(JNIEnv * a, jclass b){
         //here call the function that executes the script
    5. cc -G -I$JAVA_HOME/include -I$JAVA_HOME/include/solaris -I$YOUR_INCLUDES Exec.c -o libExec.so
    6. setenv LD_LIBRARY_PATH .
    7. java Exec

  • Executing unix scripts from java...

    Hi guys,
    I'm pretty new at this java stuff, but can someone tell me if it's possible to have a java object that connects to a specific unix box through a given IP and Port and execute a Unix shell command? The shell script creates a file that will be later ftp'ed from the UX box back to the PC I ran the java program from. Any ideas?
    Thanks in advance.

    Yes I thank it can be done. I have not done it but you prob can do it through tcp/ip useing ServerSocket and socket class.Make a server with the ServerSocket class on the linux box that is listening to the port and when it gets the right signal from your client on your pc/win the server will activate the sell script with the Runtime.getRuntime().exec(shellscript);
    Well just a thought GOOD LUCK

  • How to execute system command from java program

    Hi all,
    I want to change directory path and then execute bash and other unix commands from a java program. When I execute them separately, it's working. Even in different try-catch block it's working but when I try to incorporate both of them in same try-catch block, I am not able to execute the commands. The change directory command works but it won't show me the effects of the bash and other commands.
    Suggestions??

    The code I am using is....
    try
    String str="cd D:\\Test";
    Process p=Runtime.getRuntime().exec("cmd /c cd
    "+str);your str string is already having cd in it but again you ar giving cd as part of this command also please check this,i will suggest you to remove cd from str
    Process p1=Runtime.getRuntime().exec("cmd /c mkdir
    "+str+"\\test_folder");you should say mkdir once you change your path,but here you are saying mkdir first and then cd D:\Test(this is because of str)..please check this
    Process p2=Runtime.getRuntime().exec("cmd /c bash");
    Process p3=Runtime.getRuntime().exec("cmd /c echo
    himanshu>name.txt");
    catch(IOException e)
    System.err.println("Error on exec() method");
    e.printStackTrace();
    Message was edited by:
    ragas

  • Execute UNIX  script from java not working

    Hi
    I am having difficulty running my java program to execute UNIX script on a Windows box. Here is my code.
    public boolean executeScript() {
              try {
                   String testScript= "WEB-INF/scripts/test.sh";
                   File file = new File(copyToQaScript);
                   System.out.println(file.getAbsolutePath());
                   Process proc = Runtime.getRuntime().exec(file.getAbsolutePath());
              } catch (IOException ioe) {
                   ioe.printStackTrace();
                   logger.error(ioe);
              } catch (RuntimeException re) {
                   re.printStackTrace();
                   logger.error(re);
              } catch (Exception e) {
                   e.printStackTrace();
                   logger.error(e);
              return true;
         }When I execute this method, I am getting IOException as below.
    java.io.IOException: CreateProcess: C:\tomcat-5.0.28\webapps\myProject\WEB-INF\scripts\test.sh error=193
    Can anyone help me? Thanks.

    kminkeller wrote:
    Yes I have Cygwin installed. I am quite aware of that thanks Sabre.Then you need something like
          String[] command = {"bash","/home/sabre/bin/fred.sh"};
            Process p = Runtime.getRuntime().exec(command);
      if the executabe directory (/home/sabre/bin in my case) is not on the PATH or
          String[] command = {"bash","fred.sh"};
            Process p = Runtime.getRuntime().exec(command);
      if it is.

  • How to execute .msi files from java program

    Hi friends,
    i have written a java program which invokes and thereby execute any executable files like .exe and .bat.
    So its working fine with .exe and .bat files, but it is not working with .msi files.......can you please help me how can i execute .msi files as well??
    public class Executeexe {
         public static void main(String ar[])
              try
              Process p=null;
              Runtime rt=Runtime.getRuntime();
              p=rt.exec("D:\\mysql-essential-5.0.83-win32.msi");
              p.waitFor();
    catch(Exception e)
    }here is the program

    Make sure that the command that's being exec'd works from the cmd line.
    Then read this article and do what it says:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Then if you still are having problems explain what "...it is not working with .msi files..." really means, and provide a [SSCCE Example program|http://mindprod.com/jgloss/sscce.html]

  • Executing ANT task from java program

    hi i would like to execute an build.xml task from a java program, and i would like to catch potential errors, thanks for you help,
    i found Launcher class, but i have the following errors :
    Buildfile: build.xml does not exist!
    Build failed
    here is the code
    String argsLauncher[]= {"D:/temp/build.xml"};
    Launcher.main(argsLauncher);
    ....

    > i would like to execute an ant task from, a java program.
    http://ant.apache.org/manual/antexternal.html
    ~

  • How to execute unix script in java program that is on unix .

    hi ,
    I want to call "sendfax" script that is for sending fax to Hylafax server.
    This sendfax script is called in client java program.

    I want to call "sendfax" script that is for sending
    fax to Hylafax server.
    This sendfax script is called in client java program.And what is your problem?

  • Executing exe files from java program

    Hi,
    I need to execute exe files and pass arguments to them from my java code.
    Can you give me guidelines to do that as i haven't done that before.
    Thanks.

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html
    getRuntime() method.
    exec() method.

  • Unable to excute unix command from java program

    import java.io.File; // is java code
    public class RunSystemCommand {
    public static void main(String args[]) {
    String s = null;
    // system command to run
    String cmd = "ls ";
    // set the working directory for the OS command processor
    File workDir = new File("c:/cygwin/cygwin");
    Process p = Runtime.getRuntime().exec(cmd, null, workDir);
    p.waitFor();
    I am tryiing to excute above code to run unix command on cygwin but gave folllowing error...... but works well to open a note pad..
    Exception in thread "main" java.io.IOException: CreateProcess: C:/cygwin/bin err
    or=5
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at d.main(d.java:19)
    It seems using this functionone cannot excute unix commands..please help to do so..

    Are you sure you want cygwin/cygwin?
    the following works fine for me, you may need change the workDir to your bin folder
    import java.io.File; // is java code
    import java.io.InputStream;
    public class RunSystemCommand {
        public static void main(String args[]) throws Throwable {
         String s = null;
         // system command to run
         String cmd = "ls ";
         // set the working directory for the OS command processor
         File workDir = new File("c:/cygwin/bin");
         Process p = Runtime.getRuntime().exec(cmd, null, workDir);
         InputStream pis = p.getInputStream();
         while( pis.read() != -1 ); // added, as otherwise the ls hangs.
         p.waitFor();
    }

Maybe you are looking for

  • How to do Invoice Automation ( Converted PDF needs to be put in DMS)

    Hi All, i do have one requirement for Invoice Automation. i need to develop the report to do invoice Automation. the logic - first we need to run the tcode - VF31. after the Printing of invoice i need to convert into PDF, then converted PDF need to b

  • C2-03 software/maps update for Pakistan

    Dear Nokia Team We are anixiously waiting for new software update for c2-03 as number of complain suggest that device has most buggy software, as I noticed software update is available for some countries but for Pakistani variant we are still waiting

  • Specific page

    How do you open a pdf file and go to a specific page? I want to use a pdf file as a help system. In my application I want to open the direction manual which is pdf and go to a specific page. How do I do this? Tim

  • Arithmetic operations using Picklist field values

    Hi, I tried to multiply a picklist field value as below and wanted to store the result in a field (datatype = Integer or Number) using a workflow which triggers based on the Trigger Event "Before modified record saved". Criticality = [<plFrequency_of

  • Nokia X2-00 big problem with MMS receive

    I have 2 nokia X2-00 and is a very good phone but mms is a big big big problem. So. If I want to send mms from X2 to other phone all is good and the image can be view very good on other phone. BUT. If I receive MMS on my X2, the image is very poor, v