I want to execute [b]some shell [/b]commands in a java program

Hello,
I would like to know if it's possible to execute some unix commands in the same "environment"... I mean, if I use the exec() function to execute the "cd /tmp" command, and after that, if I want to do "ls" , I'm not in the "/tmp" directory, know what I mean ??
In fact, I want to have in my GUI a textarea or something like that, in which one can enter several unix command like in a xterm window...
I don't know how to do that and if it's possible ??
Thank you very much for your answers !

OK !! It works with this code but I don't understand why I have to do "return" twice before the command execute ??
(I'm a newbie)
Here's the sample code:
import java.io.*;
public class Tonta {
private String dada="";
private BufferedReader in;
private InputStream instr;
private InputStream errstr;
private PrintStream outstr;
private Process transyt;
private Tonta t;
public Tonta() {
//Executem el programa
try {
transyt=Runtime.getRuntime().exec("ksh");
System.out.print("toto");
} catch (IOException e)
{System.out.println("EXCEPCION:exec"+ e.getMessage());}
instr= transyt.getInputStream();
errstr= transyt.getErrorStream();
outstr= new PrintStream(transyt.getOutputStream());
in = new BufferedReader( new InputStreamReader(System.in));
}//end of constructor
  public void run() {
    int exit=0;
    boolean processEnded= false;
    try {
      while (!processEnded) {
        try {
          exit = transyt.exitValue();
          processEnded = true;
        catch (IllegalThreadStateException e) {}
        System.out.print("\nREMOT:");
        System.out.flush();
        int n= instr.available();
        if (n>0) {
          byte[] pbytes= new byte[n];
          instr.read(pbytes);
          System.out.print(new String(pbytes));
          System.out.flush();
        n= errstr.available();
        if (n>0) {
          byte[] pbytes= new
          byte[n];
          errstr.read(pbytes);
          System.err.print(new
          String(pbytes));
          System.err.flush();
        System.out.println();
        System.out.print("LOCAL> ");
        System.out.flush();
        dada= in.readLine();
        if (dada.equals("exit")) {
          System.out.println();
          System.out.println("Programa finalizado");
          System.out.flush();
          transyt.destroy();
          instr.close();
          errstr.close();
          outstr.close();
          System.exit(0);
        outstr.println(dada);
        outstr.flush();
        try {
          Thread.sleep(10);
        catch (InterruptedException e) {}
      System.out.println();
      System.out.println("Process exited with:"+ exit);
      System.out.flush();
    } catch (IOException e) {
        System.err.println("EXCEPCION "+ e.getMessage());
public static void main (String [] args) {
Tonta t= new Tonta();
t.run();
}Thanks

Similar Messages

  • Running a perl shell command through a java program on linux platform

    i'm trying to execute the following command in a java program "perl xxx.pl" using the runtime.getruntime method
    here is the piece of code
    String[] cmd={"perl","-c","AraMorph.pl",""};
    Process p = Runtime.getRuntime().exec(cmd,null,new File("/home/ahmed/buckwalter_morphan_1/data"));
    p.waitFor();
    BufferedReader in=new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line=in.readLine())!=null)
    System.out.println(line);
    but it doesn't output anything even if i tried to print the output to a file
    i'm trying to execute this program on linux platform but its working properly on a windows platform
    thx
    raar

    String[] cmd={"perl","AraMorph.pl"," </home/ahmed/in.txt"," >/home/ahmed/ast.txt"};
    Process p = Runtime.getRuntime().exec(cmd,null,new File("/home/ahmed/buckwalter_morphan_1/data"));
    BufferedReader in=new BufferedReader(new InputStreamReader(p.getErrorStream()));
    String line;
    while ((line=in.readLine())!=null)
    System.out.println(line);
    p.waitFor();
    String str2=p.getInputStream().toString();
    System.out.println("==================================="+str2);
    and it still outputs nothing but goes in something like infinite loop or as assumed in the article u suggested a deadlock but even all solutions to all pitfalls didn't succeed

  • How:Execute OS commands from a Java program

    hi,
    is it possible to execute an OS command from a java program, as in C/C++? if yes, plz give the details.
    thanx

    In the future try searching the forum before posting. Using keywords like "execute os commands" would lead you to several postings on this topic.
    Note the keywords where taken directly from you subject line. With practice you learn which keywords to use to yield the best search results.

  • How to execute unix command from the Java program running on Windows

    Hello,
    I need to
    1. Execute a unix shell script from a Java program running on the Windows.
    2. I also need to capture the output of this shell script in my program.
    Please suggest me how to achieve this.
    Thanks in Advance.

    Hi...
    Something is missing here
    If you want to execute a shell script in windows that not posible unless you find or develop a unix shell script parser for windows.
    But if you are trying the execute a unix shell script on a remote unix computer from your java program running on a windows platform you can do that by logging on to the UNIX terminal which is running on port 23 I think.
    You can test this using telnet tool on windows
    just type on command prompt
    telnet <ip of the unix pc> <port number this case 23>
    you should get the unix terminal. If that works you can do the same through java or you can directly conect to port 23 of that pc using sockets that way your program will be platform independant

  • Using a UNIX shell script to run a Java program (packaged in a JAR)

    Hi,
    I have an application (very small) that connects to our database. It needs to run in our UNIX environment so I've been working on a shell script to set the class path and call the JAR file. I'm not making a lot of progress on my own. I've attached the KSH (korn shell script) file code.
    Thanks in advance to anyone who knows how to set the class path and / or call the JAR file.
    loggedinuser="$(whoami)"
    CFG_DIR="`dirname $0`"
    EXIT_STATUS=${SUCCESS}
    export PATH=/opt/java1.3/bin:$PATH
    OLDDIR="`pwd`"
    cd $PLCS_ROOT_DIR
    java -classpath $
    EXIT_STATUS=$?
    cd $OLDDIR
    echo $EXIT_STATUS
    exit $EXIT_STATUS

    Hi,
    I have an application (very small) that connects to
    our database. It needs to run in our UNIX environment
    so I've been working on a shell script to set the
    class path and call the JAR file.
    #!/bin/sh
    exec /your/path/to/java -cp your:class:paths:here -MoreJvmOptionsHere your.package.and.YourClass "$@"Store this is a file of any name, e.g. yuckiduck, and then change the persmissions to executechmod a+x yuckiduckThe exec makes sure the shell used to run the script does not hang around until that java program finishes. While this is only a minor thing, it is nevertheless infinite waste, because it does use some resources but the return on that investment is 0.
    CFG_DIR="`dirname $0`"You would like to fetch the directory of the installation out of $0. This breaks as soon as someone makes a (soft) link in some other directory to this script and calls it by its soft linked name. Your best bet if you don't know a lot of script programming is to hardcode CFG_DIR.
    OLDDIR="`pwd`"
    cd $PLCS_ROOT_DIRVery bad technique in UNIX. UNIX supports the notion of a "current directory". If your user calls this program in a certain directory, you should assume that (s)he does this on purpose. Making your application dependent on a start in a certain directory ignores the very helpful concept of 'current directory' and is therefore a bug.
    cd $OLDDIRThis has no effect at all because it only affects the next two lines of code and nothing else. These two lines, however, don't depend on the current directory. In particular this (as the cd above) does not change the current directory for the interactive shell your user is working in.
    echo $EXIT_STATUS
    exit $EXIT_STATUSEchoing the exit status is an interesting idea, but if you don't do this for a very specific purpose, I recommend not to do this for the simple reason that no other UNIX program does it.
    Harald.

  • How to call up an executable file (eg. MSPaint) from within my java program

    How to call up an executable file (eg. MSPaint) from within my java program

    Ummm... why would you want to get MSPaint anyway? Even in the absense of real software, Java's own graphics tools are way more sophisticated - with a little time and effort, you could write a simple paint package that beat MSPaint hands down.

  • Need some help on a medium size Java program..

    I was given a medium size Java program which contains servlets that run on a web server..
    There are some documentations, but not very detailed.
    I'm just trying to following through the codes right now and are having some trouble..
    I'm trying to find out how the program actually begin and how all the other classes related to each other..
    Is there any tools or suggestions on what I should do/use??

    That is incredibly vague question but I will try to get you thinking about some things...
    The best thing to do first and foremost is in my opinion understand the application as a user first. If you have it packaged then deploy it to a web server, and try to simply install it. Look in the documentation to see if there is any other necessary software to run correctly on the server side, JRE version? Specific web server? Database server? Before you go any further make sure that you can figure out how to not only deploy it but establish it on a local test environment and then use it to some extent.
    If you did this then look for specific technologies, is it utilizing EJB's? Spring? Hibernate?, JSP, JSF, Servlets? Then go into more details, if servlets, servlet handler controller architecture? MVC design patterns? DAO objects?
    Try to conceptualize it from the top down.
    If you have done all this then post back.

  • Execute several UNIX OS commands from inside Java program

    Greetings,
    I would like to be able to execute from a Java program several of the following UNIX commands
    script filename
    cd
    date
    grep
    diff
    I have been able to get a single command to work with
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec("dir");
    My goal here is to accomplish a Java program which will use JDBC to access an Oracle database with SQL and then compare the resultant flat file with a diff command in Unix to another delimited file from an Excel spreadsheet. Your input is appreciated.
    Thank you

    I would suggeat to use JDBC to get the data from database and then read your file and then use existing java diff program from following link to find the differences between the files
    http://www.bmsi.com/java/
    I hope this helps
    VAN

  • 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

  • How to execute MS DOS command through Java program???

    Dear Sir,
    I want to run a MS-DOS command through my Java program. I have tried "Dir" command but no other command which takes command line args doesn't work at all. Please help.
    import java.io.*;
    class CommandPrompt
         public static void main(String[] args)
              try
                   File file = new File("C:/Temp/Java");
                   String[] cmd = {"command.com","/c","md folder"};
                   String[] envp = {""};
                   Process m;
                   String s = "";
                   m = Runtime.getRuntime().exec(cmd,null,file);
                   BufferedReader buf = new BufferedReader(new InputStreamReader(m.getInputStream()));
                   while ((s = buf.readLine())!=null)
                        System.out.println(s);
              catch (Exception ex)
                   System.out.println("Exception is "+ex);
                   ex.printStackTrace();

    1. This forum is for Swing-related issues only. This question should be posted to the "Java Programming" forum.
    2. Please enclose your sample code in code blocks; it's much easier to read that way. See here for how it's done: http://forum.java.sun.com/faq.jsp#messageformat
    3. Please provide more information, like what error messages you got and what OS you're running. For instance, if you're running WinXP, Win2k or NT4, your command processor should be "cmd.exe", not "command.com". When I made that change, your program worked for me.

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

  • Shell script to execute java program

    Hi there,
    In my script to execute my Java program, I have assigned a variable as follows:
    PROGRAM_ROOT = "C:/program"
    A jar file that my program needs is located in C:/program/build. ie. it is located in "PROGRAM_ROOT/build".
    In my script I have a property set as follows:
    -Dprogram.build="$PROGRAM_ROOT/build"
    When I execute the script using cygwin, the above line gets converted to the following:
    -Dprogram.build="$PROGRAM_ROOT
    /build"
    i.e. the concatenation of "PROGRAM_ROOT" and "build" results in PROGRAM_ROOT<carriage_return>\build.
    Is there a way to use PROGRAM_ROOT and concatenate "/build" to it?

    You'd have to build your own client/server implementation or use a remote messaging framework (like RMI) to help you with this if you wanted to do it in pure Java.
    It would be easier to just kick off some other installed process to send the message, e.g. install cygwin and pipe the command to start the shell and run the script through ssh. If you wrote a Java program to kick this off, it would only be a couple lines of code, and not really necessary.
    It's not ideal to try to do remote command administration just using Java.

  • I want to execute UNIX COMMAND in ABAP

    Hi All,
    I want to execute a UNIX XOMMAND sh <scriptname> <filename> to replace divsion codes.in ABAP.
    But, I came to know that we can't (2) or try the following program but unfortunately the command CALL SYSTEM is not supported by SAP. If you are on R/3 2.1 - 2.2x you can get some idea's from the program SAPMSOS0.
    REPORT ZUNIXCOM .
    DATA: U_COMMAND(200).
    Table for system messages
    DATA: BEGIN OF RT OCCURS 100 ,
    LINE(100) ,
    END OF RT .
    START-OF-SELECTION .
    MOVE 'unix command' to U_COMMAND .
    REFRESH RT.
    CALL 'SYSTEM' ID 'COMMAND' FIELD U_COMMAND
    ID 'TAB' FIELD RT-SYS .
    LOOP AT RT.
    WRITE : / RT-LINE .
    ENDLOOP. 
    So please can u help me how to call a unix command from ABAP. it is very urgent. I want complete details and all possible solutions
    <removed_by_moderator>
    Thanks,
    gyanaraj
    Edited by: Julius Bussche on Aug 26, 2008 11:29 AM

    Selvaraj Gyanaraj wrote:>
    > So please can u help me how to call a unix command from ABAP.
    I was about to help you.
    >it is very urgent.
    I changed my mind.
    >I want complete details and all possible solutions
    I'm glad I changed my mind.
    >Points are surely rewarded.
    Too late.

  • Error While Executing Sqlplus from shell

    I am trying to execute the below shell script with out back ticks(`${ORACLE_HOME}/bin/sqlplus) while calling sqlplus in the below code. When i do that all the next lines after that are changing to red color in vi and when i execute the script i am getting an error as "syntax error: unexpected end of file". may i know i please know what could be the issue? i suspect it could be because of EOF, when i have the backticks on it is executing fine.
    #!/bin/bash
    logit "Updating the Validation Status Field in ${DBSTGUSER}.FEED_PROCESS_LOG Table as RUNNING With Matching Parameters"
            logit "UNINUM :: ${UNINUM} PROVIDER :: ${PROVIDER} EXTRACT_DT :: ${EXTRACT_DT} VER_NUM :: ${VER_NUM}"
            `${ORACLE_HOME}/bin/sqlplus ${DBSTGUSER}/${DBSTGPASS}@${DBSRC} <<EOF > ${UPD_FEED_PROC_LOG}
            spool ${UPD_SQL1}
            UPDATE ${DBSTGUSER}.FEED_PROCESS_LOG SET VALIDATION_STATUS='RUNNING'
            WHERE UNINUM='${UNINUM}' and PROVIDER='${PROVIDER}' and EXTRACT_DT='${EXTRACT_DT}'
            and VER_NUM=${VER_NUM} and ACT_END_DT IS NULL  AND (VALIDATION_STATUS IS NULL OR VALIDATION_STATUS='RUNNING');
            spool off;
            COMMIT;
            EXIT;
            EOF`
            if grep -q "ERROR" ${UPD_FEED_PROC_LOG}
            then
                    logit "Error While Updating the ${DBSTGUSER}.FEED_PROCESS_LOG Table"
                    logit "Please Check ${UPD_FEED_PROC_LOG} Log File For Detailed Information"
                    exit 3
            else
                    logit "Updation Of ${DBSTGUSER}.FEED_PROCESS_LOG Table Completed Successfully"
                    logit "Please Check ${UPD_FEED_PROC_LOG} Log File For Detailed Information"
            fi

    Ariean wrote:
    I thought forum will have people with mixed skills (sql/scripting) they would be able to quickly point me to right direction. There is no problem is with RDBMS!
    I know EOF stands for End of file and i am piping the data into the program (sqlplus).You could just as well use "FUBAR" in place of EOF; which just happens to be some arbitrary string.
    piping ("|") is NOT involved , as in env | sort
    you don't know, what you don't know.

  • Through Java code I want to execute a exe file which is in aJar file

    I am having some classes and an exe file in a directory. I have made them in to a Jar file. In a class file which is in that jar file i want to execute a Exe file which is also resides in that jar file. Is it possible to exexute that EXE file?
    For Example....
    1. Im having a directory named CLIENT.
    2. In that directory I have 10 clss files and an EXE file.
    3. These class files and EXE files are ziped in to a Jar file.
    4. I have to give the Jar file to my client.
    5. He can put that Jar file where ever he installed my product may be C driver or D drive like that
    Now the problem is...
    I want to execute the Exe File from one of the class where both the exe file and class file resides in the Jar file
    This is my requirment
    Can anyone Help to me to solve this problem?
    Thanks in Advancd
    Ibram Shah.A.M
    ([email protected])

    The answer is to extract the EXE into a temp directory, execute it, and delete it when you're done. For example:
    //This is the path *inside* the JAR file!
    InputStream in = getClass().getResourceAsStream("/resources/myprog.exe");
    OutputStream out = new FileOutputStream("myprog.exe");
    File file = new File("myprog.exe");
    int data;
    while((data = in.read()) >= 0) out.write(data);
    in.close();
    out.close();
    //Execute the EXE here using java.lang.Runtime.exec()
    if(file.exists()) file.delete();
    ...

Maybe you are looking for