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();
}

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

  • Call an interactive UNIX command from java

    Hi,
    I want to call a UNIX command from java. When issue the command 'htpasswd -c filename username' on UNIX terminal, it asks for the new password and the then confirmation password again (yeah, unfortunately the htpasswd installed on our system does not allow you proivde the password on the command line. So have to work interactively ). Now, I have written a simple java program RunCommand.java. I am hardcoding the password for the htpasswd command in the file (in the real situation, password will be generated dynamically). I want to issue 'java RunCommand' on the UNIX command line and get back the command prompt without being asked for the password twice. The code is below, but the Outputstream does not work as expected. It always asks for inputs. Any idea? Many thanks.
    import java.io.*;
    public class RunCommand {
    public static void main(String args[]) throws Exception {
    String s = null;
    try {
    String cmd = "htpasswd -c filename username ";
    // run a Unix command
    Process p = Runtime.getRuntime().exec(cmd);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    OutputStream stdOut = p.getOutputStream();
    String pswd = "mypassword";
    while ((s = stdInput.readLine()) != null) {
         s = stdInput.readLine();
         stdOut.write(pswd.getBytes());          
         stdOut.flush();
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
    System.out.println(s);
    stdOut.close();
    stdInput.close();
    stdError.close();
    System.exit(0);
    catch (IOException e) {
    System.out.println("exceptions caught: ");
    e.printStackTrace();
    System.exit(-1);

    There are only about 9 billion responses a day on how to do this. Use the search feature.

  • 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.

  • Excute unix script from java.

    Hi need to excute unix script from java application.
    My code is:
    public class Test
    public static void main(String args[])
         try{
         p = Runtime.getRuntime().exec("./qfe0"); //qfe0 is the name of the script.
    p.waitFor();
    catch(Exception e)
    e.printStackTrace();
    My problem is that using the waitFor() statement stuck the the script. if i don't use the waitFor() it works good but then i don't know when the script is finished.
    Any idea?

    The problem is likely to be that you script is either waiting for input or has filled the stdout buffer and you are not emptying it. Search this forum for this as its been answered many times before.

  • 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

  • Unable to execute Linux command from Java

    Hi,
    I am currently working on a code wherein i need to execute Linux command from Java. Below are some of the query i have.
    1) Is there any efficient method of running OS commands from Java, rather than using Runtime and Process method.
    2) Below is details of my code which fails in execution
    **-- Java Version**
    java version "1.6.0"
    OpenJDK Runtime Environment (build 1.6.0-b09)
    OpenJDK Server VM (build 1.6.0-b09, mixed mode)
    -- Program Code ----
    Where <path> = Path i put myself
    package test;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.*;
    public class GetInode{
         * @param args
         public static void main(String[] args) {
              GetInode test = new GetInode();
              test.getInode();
         public void getInode(){                    
              String command = "/usr/bin/stat -Lt <path>;
              System.out.println(command);
              Process process;
              Runtime rt;     
              try{
              rt = Runtime.getRuntime();               
              process = rt.exec(command);
              InputStreamReader isr = new InputStreamReader(process.getErrorStream());
              BufferedReader bre = new BufferedReader(isr);
              BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream());
              System.out.println(bre.readLine());
    System.out.println(br.readLine().split(" ")[7]);
              process.destroy();          
              }catch (Exception ex){
                   System.out.println("Error :- " + ex.getMessage());
    ------Output -------------
    /usr/bin/stat -Lt "<path>"
    /usr/bin/stat: cannot stat `"<path>"': No such file or directory
    Error :- null
    Can any one help me what is wrong and why i am unable to run the Linux command from Java.

    For clarity purpose............i m submitting actual code here
    --- Code ---
    package test;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.*;
    public class GetInode{
    * @param args
    public static void main(String[] args) {
    GetInode test = new GetInode();
    test.getInode();
    public void getInode(){               
    String command = "/usr/bin/stat -Lt \"/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt\"";
    System.out.println(command);
    Process process;
    Runtime rt;
    try{
    rt = Runtime.getRuntime();
    process = rt.exec(command);
    InputStreamReader isr = new InputStreamReader(process.getErrorStream());
    BufferedReader bre = new BufferedReader(isr);
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    System.out.println(bre.readLine());
    System.out.println(br.readLine().split(" ")[7]);
    process.destroy();
    }catch (Exception ex){
    System.out.println("Error :- " + ex.getMessage());
    --- Output ---
    [ratz]s0898671: java GetInode
    /usr/bin/stat -Lt "/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"
    /usr/bin/stat: cannot stat `"/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"': No such file or directory
    Error :- null
    -- Linux Terminal --
    If i copy the first line from the output and execute on Linux terminal her is the output that i get
    [ratz]s0898671: /usr/bin/stat -Lt "/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"
    /afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt 12003 24 81a4 453166 10000 1c 360466554 2 0 1 1246638450 1246638450 1246638450 4096
    Can you just assist me where am i really making mistake.......i was wondering if the command that i pass from Java....can be executed on Linux terminal why is it faling to run from java.........and when i print the Error Stream for process output........it show cannot Stat.......

  • Issueing unix command from java

    I am using FTPConnection.java by Bret Taylor, for uploading files to remote linux portal. But i cannot issue any unix command from it . please anyone help me in this case?

    Read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    It'll explain it all. - MOD

  • Problem while running dos command from java program

    Dear friends,
    I need to terminate a running jar file from my java program which is running in the windows os.
    For that i have an dos command to find process id of java program and kill by using tskill command.
    Command to find process id is,
    wmic /output:ProcessList.txt process where "name='java.exe'" get commandline,processid
    This command gives the ProcessList.txt file and it contains the processid. I have to read this file to find the processid.
    when i execute this command in dos prompt, it gives the processid in the ProcessList.txt file. But when i execute the same command in java program it keeps running mode only.
    Code to run this command is,
    public class KillProcess {
         public static void main(String args[]) {
              KillProcess kProcess = new KillProcess();
              kProcess.getRunningProcess();
              kProcess = new KillProcess();
              kProcess.readProcessFile();
         public void getRunningProcess() {
              String cmd = "wmic /output:ProcessList.txt process where \"name='java.exe'\" get commandline,processid";
              try {
                   Runtime run = Runtime.getRuntime();
                   Process process = run.exec(cmd);
                   int i = process.waitFor();
                   String s = null;
                   if(i==0) {
                        BufferedReader stdInput = new BufferedReader(new
                               InputStreamReader(process.getInputStream()));
                        while ((s = stdInput.readLine()) != null) {
                         System.out.println("--> "+s);
                   } else {
                        BufferedReader stdError = new BufferedReader(new
                               InputStreamReader(process.getErrorStream()));
                        while ((s = stdError.readLine()) != null) {
                         System.out.println("====> "+ s);
                   System.out.println("Running process End....");
              } catch(Exception e) {
                   e.printStackTrace();
         public String readProcessFile() {
              System.out.println("Read Process File...");
              File file = null;
              FileInputStream fis = null;
              BufferedReader br = null;
              String pixieLoc = "";
              try {
                   file = new File("ProcessList.txt");
                   if (file.exists() && file.length() > 0) {
                        fis = new FileInputStream(file);
                        br = new BufferedReader(new InputStreamReader(fis, "UTF-16"));
                        String line;
                        while((line = br.readLine()) != null)  {
                             System.out.println(line);
                   } else {
                        System.out.println("No such file");
              } catch (Exception e) {
                   e.printStackTrace();
              return pixieLoc;
    }     when i remove the process.waitFor(), then while reading the ProcessList.txt file, it says "No such file".
    if i give process.waitFor(), then it's in running mode and program is not completed.
    Colud anyone please tell me how to handle this situation?
    or Is there anyother way to kill the one running process in windows from java program?
    Thanks in advance,
    Sathish

    Hi masijade,
    The modified code is,
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        StreamGobbler(InputStream is, String type)
            this.is = is;
            this.type = type;
        public void run()
            try
                InputStreamReader isr = new InputStreamReader(is, "UTF-16");
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null)
                    System.out.println(type + ">" + line);
                } catch (IOException ioe)
                    ioe.printStackTrace(); 
    public class GoodWindowsExec
        public static void main(String args[])
            try
                String osName = System.getProperty("os.name" );
                String[] cmd = new String[3];
                 if( osName.equals( "Windows 95" ) )
                    cmd[0] = "command.com" ;
                    cmd[1] = "/C" ;
                    cmd[2] = "wmic process where \"name='java.exe'\" get commandline,processid";
                } else {
                    cmd[0] = "cmd.exe" ;
                    cmd[1] = "/C" ;
                    cmd[2] = "wmic process where \"name='java.exe'\" get commandline,processid";
                Runtime rt = Runtime.getRuntime();
                System.out.println("Execing " + cmd[0] + " " + cmd[1]
                                   + " " + cmd[2]);
                Process proc = rt.exec(cmd);
                System.out.println("Executing.......");
                // any error message?
                StreamGobbler errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERROR");           
                          // any output?
              StreamGobbler outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUTPUT");
                          // kick them off
                errorGobbler.start();
                outputGobbler.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
            } catch (Throwable t)
                t.printStackTrace();
    }when i execute the above code, i got output as,
    Execing cmd.exe /C wmic process where "name='java.exe'" get commandline,processid
    and keeps in running mode only.
    If i execute the same command in dos prompt,
    CommandLine
    ProcessId
    java -classpath ./../lib/StartApp.jar;./../lib; com.abc.middle.startapp.StartAPP  2468
    If i modify the command as,
    cmd.exe /C wmic process where "name='java.exe'" get commandline,processid  > 123.txt
    and keeps in running mode only.
    If i open the file when program in running mode, no contents in that file.
    If i terminte the program and if i open the file, then i find the processid in that file.
    Can you help me to solve this issue?

  • "at" UNIX Command in Java Program

    Friends,
    1. "at" command in UNIX execute Unix command at a scheduled time. 2. For each user there will be a table maintained internally which can be accessed by "at" with "-l" argument.
    3. A mail will be sent to the owner with the output of the commands as a message.
    I tried to run the "at" command of Unix in JSP, which gets succesfully executed in Oracle 10g App Server container (Installed in Solaris machine). I have tested the successful execution of command with the log file. But I haven't got any mail for the output. If anyone had any idea, please help me.
    The code I have wtitten is
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(new String[] {"sh","-c","at 2115 Dec 7 < /export/home/usr1/abc.sh"});
    InputStream stderr = proc.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    logger.info("<ERROR>");
    while ( (line = br.readLine()) != null)
    logger.info(line);
    logger.info("</ERROR>");
    int exitVal = proc.waitFor();
    logger.info("Process exitValue: " + exitVal);
    My doubts are:
    1. Who is the owner of the output of "at"command, which gets executed under Oracle 10g App Server container?
    2. If no one is the owner, then where will the output of "at" command will go?
    3. Is there any other way to execute "at" command of UNIX in java program? If so, then please help me.
    Thanks in advance.
    regards
    Nandha Kumar.M

    filestream I have to ask - what's a chav ?
    I have doubts abut what it is :-)
    Seriously though, what is that an abbreviation for?
    That's a new one to me.
    http://www.chavscum.co.uk
    chavs are roughly analogous to rednecksI wouldn't use that analogy. While both may lack certain social graces, rednecks typically don't receive ASBOs.
    Chavs favor small cars with lots of bling whereas rednecks are likely to drive a pickup or a large sedan.
    Chavs have pitbulls in their yards (gardens), rednecks an '84 Mustang LX on cinder blocks.
    etc, etc.
    Message was edited by:
    filestream
    Message was edited by:
    filestream

  • Calling a Unix Command from Java

    Hi all,
    I'm not a Java guy, I need a small help, I need a code which will call a Unix Command called from a Java code. For Example I need a Java code whereby I should be able to do a 'ls -lt' on my Unix box. Can anybody please help.
    Thanks,
    Shantanu

    See Runtime.exec()

  • Problems to execute "cd" DOS command from Java program

    Anyone try to exec command "cd.." or "cd directory", it doesn't have any action. No exceptions, just don't do anything.
    Runtime.getRuntime().exec("cd\\");
    Runtime.getRuntime().exec("cd hello");
    However, when I try the following, it is working fine. Any ideas???
    Runtime.getRuntime().exec("explorer");
    Runtime.getRuntime().exec("javac Test1.java");

    That's because cd is built into the command
    interpreter in Windows. Runtime.getRuntime().exec()
    can only be used to launch external programs. This
    article should get you going:And that's not the only reason why you can't do this.
    When you do
    Runtime.getRuntime().exec("cd c:\\");
    (or, heck, "cmd /c cd c:\\"): the new command that you spawn will cd to the destination specified, and then exit. The parent process (your java program, that is launching this command) won't go anywhere - the "cd" doesn't affect it.
    The only way to change your OS directory in Java is to invoke native code. And even then, the effects are undefined (in terms of how your CLASSPATH will be affected, etc.).

  • Using Unix commands from Java Application

    Hi,
    I need to write an Java application such that could run Unix commands in a Unix box.
    For example, my Java app needs to log in the Unix box, change directory (cd), create new folder (mkdir), list the current files in folder (ls), mount a new device (mount), etc.
    Thank you very much.
    Hung

    you can use java.lang.Runtime.exec to invoke OS commands, but if you're going to be completing a sequence that complicated and need to manage error handleing well, it might be best to just invoke a native method or write a shell script that does all of that stuff and then invoke that script via Runtime.exec . The Runtime class has limitations when you start invoking processes that require user input (like 'su'). Search the forums for more extensive examples on how to use Runtime.

  • 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.

  • Running UNIX command from Java

    import java.lang.* ;
    import java.io.*   ;
    public class TestRunTime
        public static void main(String args[])
            int rc = -1 ;
            String yard = "psnsy" ;
            String ifwList = "[email protected],[email protected]" ;
            String cmd = "/usr/bin/mailx -r oracle -s \"PMC - Missing Interface Files from " + yard +
                               "\" " + ifwList + " < /interface/nwps/missingfiles.txt" ;
            rc = RunThis(cmd) ;
            System.out.println(rc) ;
        private static int RunThis(String str)
             Runtime rt = Runtime.getRuntime();
             int        rc = -1;
             try
                Process p = rt.exec(str);
                p.waitFor() ;
                BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = "";
                while ((line = buf.readLine()) != null)
                   System.out.println(line) ;
                rc = 0 ;
                return rc ;
             catch ( Throwable t  )
                  t.printStackTrace();
                  rc = -1 ;
                  throw new RuntimeException() ;
    }When I run java TestRunTime
    all it does is hangs and never completes.
    I can run the string cmd from the UNIX shell and it runs as expected - I receive an email.

    jschell wrote:
    sabre150 wrote:
    Whether the detail is as you say or as I say does not remove the need to process the exec()ed processes stdout and stderr each in their own thread. Since the OP is not writing to stdin he can handle one of stdout or stderr in the Thread that invokes the exec() but the other needs a separate thread.If the streams are stripped from the process then...
    1. They should not be stripped until they are in their own thread.
    2. Each requires their own thread.
    But since the OP isn't stripping either, no other threads are needed. Nor does the OP need to strip them.I have to disagree. The following code is based on the traps article and sends output to stdout and to stderr from the 'sh' program. Run as is it deadlocks. Run by changing the 'false' to 'true' in the 'if' statement it does not deadlock.
    If one changes the code to process only stdout or stderr but not both then it deadlocks.
    Running the same code on Windows XP and Windows 2000 but using 'cmd.exe' instead of 'sh' and using 'dir' instead of 'ls' produces the same result.
    Running similar code that just runs a perl script without any stdin but that writes to both stdout and stderr it deadlocks if one does not process both stdout and stderr in separate threads.
    If one processes the Process stdout and stderr streams then one does not get a deadlock.
    This is entirely consistent with what the 'traps' article says and I hope consistent with what I have written in this thread.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    class StreamGobbler extends Thread
        private int count = 0;
        private final InputStream is;
        private final String type;
        StreamGobbler(InputStream is, String type)
            this.is = is;
            this.type = type;
        public void run()
            try
                final InputStreamReader isr = new InputStreamReader(is);
                final BufferedReader br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null)
                    System.out.println(++count + "\t " + type + "> " + line);
            } catch (IOException ioe)
                ioe.printStackTrace();
    public class Sabre20091015_2
        public static void main(String args[]) throws Exception
            final Process proc = Runtime.getRuntime().exec("sh");
            if (false)
                new StreamGobbler(proc.getErrorStream(), "ERROR").start();
                new StreamGobbler(proc.getInputStream(), "OUTPUT").start();
            final Writer writer = new OutputStreamWriter(proc.getOutputStream());
            for (int commandIndex = 0; commandIndex < 20000; commandIndex++)
                writer.write("echo Index " + commandIndex + "\n");
                writer.write("ls\n");
                writer.flush();
                writer.write("fnaskfdkdhflakjfljd\n");
                writer.flush();
            writer.close();
            final int exitValue = proc.waitFor();
            System.out.println("Exit value = " + exitValue);
    }

Maybe you are looking for

  • Camera Raw 6.3 update failed

    I have Photoshop CS 5 running Mac OS 10.10.2 I'm trying to install Camera Raw 6.3 update, but I get an error message: "Camera Raw 6.3 Update failed. How do I fix the problem? Thanks

  • Multiple related columns in JList

    Is it possible to have multiple columns in a JList? My problem is that I have a class called Volunteer who have a name, surname and id number. I would like these to be displayed in a JList like: name surname id name surname id and so on... I have cur

  • Itunes 11 releease date for windows 8?

    Hi does anyone know when the release date is after being delayed from october to november.... appreciate reply!

  • Error message trying to back up Library

    I followed all the steps to back up my library that are given on Apple's website. When I click the burn disc function, which is the final step, I am getting an error message that says "the disc burner is in use by another application other than itune

  • Parallel Approval in SUN IDM 7.1

    We are using SUN IDM 7.1. We want to send the approval notification to multiple approval at a time parallely. Every email/approval form have different email content to aprove and reject. We want to collect all approval and rejection at the end of the