Running ssh command in a java application

Hi there!
I am trying to run a ssh command from a java application cause I need to store the result.
Actually I can run this command in the cygwin shell so I need to open the shell and run the command, all trough java.
so, what my process needs to do is:
1) open the cmd
2) run C:\cygwin\cygwin.bat
3) execute the ssh command
ssh -l fip-user ipdb fip 42704) print the result of the ssh command.
Note that the cygwin opens in the same command line window and so will print it's result to the same process inputstream
Message was edited by:
RBervini

Use "Runtime.getRuntime().exec()" to execute the SSH program,
and you can then get the output of the SSH program
via the getInputStream() method on the returned Process object.
Note: there are many pitfalls with this. In particular, most people don't know
they should create separate threads to drain the input/output pipes.
See this excellent classic article http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
on how to do it right.

Similar Messages

  • Running ssh command from java and then answering password prompt

    Hi,
    I have a situation that has not solved yet. I am running ssh command from unix terminal without any problem, and then i enter password.
    For example :
    [oracle@fuata]:/export/home/oracle> ssh -N [email protected] -L 9901:127.0.0.1:9999
    Password:
    It is working. I have question that how can i perform this in java? I am thinking that i can run ssh command by using Runtime Class, it is ok. But how can i answer the password? I am a bit confused. Is there any example looks like this?
    Thanks for responses.

    futi wrote:
    Thanx. Firstly i insisted to do this without jsch but actually this is harder than jsch. I edit some of code pieces PortForwardingL.java and could run it. It works problem-free. Could you say why you "insisted" on this approach. It can't be for speed+ since jsch is very fast. It can't be for portability+ since jsch is portable but the use of Runtime.exec() requires the installation of ssh software. It can't be because of limitations+ since jsch is a fully featured library. It can't be for security+ since jsch is secure. It can't be for ease of use+ since jsch is much easier to use than ssh with Runtime.exec(). Unless it's a licensing issue, it can't be for commercial+ reasons since jsch is free. The only reason I can think of why one would "insisted" on this approach is if it is for some college project.

  • Total nube to jws, need to run ssh command via web or jws?

    Ok So we had a developer that created this application that can basically run ssh commands via jws I believe. Unfortunately he is no longer here. I am wondering how you do this? I know tha commands that are already set up, but I have no idea how to implement it into my project.
    I am using Struts 2, Java 5, Weblogic 9.2, Spring
    Thanks
    orozcom

    Have a look at:
    http://www.jcraft.com/jsch/
    basically you'd need a small webstart client to wrap something like the above library. Best thing is to try with a standalone java client first. Once that is working have a look at turning it into a webstart app.

  • How to run a jar file using Java application.

    Hi all,
    I know that jar file can run using the following command, using the command prompt.
    java -jar jar-fileBut I don't know how to run that command through a Java code. Hope it's clear to you.
    So can you please explain how can I do it.
    Thanks,
    itsjava

    rayon.m wrote:
    The solution given by ropp appears to have nothing to do with what you asked about.Ok sir, I got the point.
    I've try a test as follows. But it doesn't give any output. Even not an exception.
            try {
                String[] temp = new String[]{"java", " -jar", " MainApp.jar"};
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(temp);
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);
                System.out.println("Temp_Values");
            catch(InterruptedException ex) {
                System.out.println(ex.getMessage());
            catch (IOException ex) {
                System.out.println(ex.getMessage());
            }I've debug and see, but the exitValue is even not exist at run time. Can you tell me where I'm going wrong.

  • Can we execute DOS Commands from a Java Application

    I just want to know whether we can execute DOS Commands from a Java Application.
    Thanks.

    hi,
    try this:
    Runtime.getRuntime().exec("cmd /c start abc.bat");
    andi

  • Running a dos command from a java application

    hello,
    I'm trying to execute a batch file from a java application. I tried with:
    try
    Process proc=Runtime.getRuntime().exec("fop -fo "+iXmlFoFile+" -
    svg "+SvgFileName);
    }catch (IOException e){System.err.println("Error in conversion of
                               the Xml FO file into Svg file: "+e);}
    and with:
    try
    Process proc=Runtime.getRuntime().exec("cmd ./c fop
    -fo "+iXmlFoFile+" -svg "+SvgFileName);
    }catch (IOException e){System.err.println("Error in conversion of
                the Xml FO file into Svg file: "+e);}
    but i have a IOException: CreateProcess: .... error=2
    When I try these line to launch a .exe file it works but not with a .bat file.
    I also tried:
    String execstr = "fop -fo "+iXmlFoFile+" -svg "+SvgFileName;
    String [] commandArray = { execstr };
    try {
    Runtime.getRuntime().exec(commandArray);
    } // end try
    catch ( Exception e ) {
    System.out.println( e.getMessage() );
    e.printStackTrace();
    }// end catch
    but i got the same exception in java.lang.Win32Process.create
    What did i do wrong?

    Your execution string is a bit more that I want to figure out, but here are a couple ideas:
    Is the working directory of any importance? If so you'll need to set that when you do your exec()
    I think I remember reading something about batch files that couldn't be kicked off via this method. Perhaps you need to execute the string "start mybatchfile.bat". Seems like you need to do something like that to get a command interpreter to run your batch file.

  • Run ssh command in labview

    does anyone knows how to run an ssh command in labview?
    I know how to run some linux commands in labview but my problem is when I try to run an ssh command ...
    thks
    JP

    Unfortunetly, I don't know how to script in a password for ssh. SSH closes the stdin and re-opens the tty that you are logged in at. This is actually a security feature. As well as a way to send stdin to remote programs (otherwise your password would get in the way.)
    If you don't need to ssh to a remote host, and you want to chmod something on the localhost, you could use sudo instead. With sudo you can specify certain users (or all users) to run certain commands. (so you could make a shell script to chmod for you).
    I don't know your exact needs, but I think that a public/private keypair could still work. In your authorized keys file on your "root" account, you can even specify that "this public key does not get shell access, and can only execu
    te this one command." This would probably be the most secure method. But it requires the user to have the correct private key as well.
    If you know that won't work for some reason, then maybe you could setup a inetd process that will execute a command whenever someone connects to a certain port (then you could use LabVIEW's TCP VIs).
    Or, if you are not connecting remotely, you could setuid your LabVIEW executable (A VERY BAD IDEA!).
    Also, it is possible to script "telnet." It would of course transmit your root password as plaintext, but trying to script your ssh session would also embed your password in your LabVIEW VI. Out internet toolkit for LabVIEW has some helpful telnet VIs.
    May I ask why you want to chmod something on a remote system that requires root? Sounds like maybe you should create a LabVIEW application on the remote side that acts as a daemon (running as root) and accepts connections and commands and does the chmodding for you.
    -Duffey

  • Running curl command from a java program using Runtime.getRuntime.exec

    for some reason my curl command does not run when I run it from within my java program and errors out with "https protocol not supported". This same curl command however runs fine from any directory on my red hat linux system.
    To debug the problem, I printed my curl command from the java program before calling Runtime.getRuntime.exec command and then used this o/p to run from the command line and it runs fine.
    I am not using libcurl or anything else, I am running a simple curl command as a command line utility from inside a Java program.
    Any ideas on why this might be happening?

    thanks a lot for your response. The reason why I am using curl is because I need to use certificates and keys to gain access to the internal server. So I use curl "<url> --cert <path to the certificate>" --key "<path to the key>". If you don't mid could you please tell me which version of curl you are using.
    I am using 7.15 in my system.
    Below is the code which errors out.
    public int execCurlCmd(String command)
              String s = null;
              try {
                  // run the Unix "ps -ef" command
                     Process p = Runtime.getRuntime().exec(command);
                     BufferedReader stdInput = new BufferedReader(new
                          InputStreamReader(p.getInputStream()));
                     BufferedReader stdError = new BufferedReader(new
                          InputStreamReader(p.getErrorStream()));
                     // read the output from the command
                     System.out.println("Here is the standard output of the command:\n");
                     while ((s = stdInput.readLine()) != null) {
                         System.out.println(s);
                     // read any errors from the attempted command
                     System.out.println("Here is the standard error of the command (if any):\n");
                     while ((s = stdError.readLine()) != null) {
                         System.out.println(s);
                     return(0);
                 catch (IOException e) {
                     System.out.println("exception happened - here's what I know: ");
                     e.printStackTrace();
                     return(-1);
         }

  • Running a command line in Java

    Dear all,
    I have a question, I need to run a command line in a Java program. The commands line is the next:
    cas.exe -i file1
    I have been seeing in internet and I have tried:
    Process ls_proc = Runtime.getRuntime().exec("cmd /c start D:\\cas>cas.exe -i file1");
    it start the window where the cas folder is... but it dont run the commands line : cass.exe -i file1 :(
    Somebody can help me, please??
    Andrea

    try running it like this.
    Process ls_proc = Runtime.getRuntime().exec("cmd /c start D:\\cas>cas.exe -i file1" +"\n");
    if that does not work put this underneath the original.
    ls_proc.newLine();
    or look into the ProcessBuilder class in java.lang.

  • Is it possible to run dos-command's in java?

    I have a small security problem. I have a dos-based java prog. with login at the start og the program, but I have problems hiding the password. I have managed to hide the password when it is typed, but when you press enter and get to the next menu, it is only to press the up-key, and dos recover the last typed sentence. (The password...) I have been able to fine the dos-command "doskey /reinstall", which will clear the memory, but I haven't been able to implemet this in my java-prog.
    Any tips/trics are appreciated.

    I have a small security problem. I have a dos-based
    java prog. with login at the start og the program, but
    I have problems hiding the password. I have managed to
    hide the password when it is typed, but when you press
    enter and get to the next menu, it is only to press
    the up-key, and dos recover the last typed sentence.
    (The password...) I have been able to fine the
    dos-command "doskey /reinstall", which will clear the
    memory, but I haven't been able to implemet this in my
    java-prog.
    I doubt that calling that in your program would help.
    doskey is specific to the process. Running it by any means in java means that a new process will exist. You can verify this by open two console windows and running doskey in both. Nothing that you do in one will be reflected in the other.
    I don't think your problem is a program problem. That means that it should not be solved by software but rather by management. For example you certainly wouldn't expect your program to make sure that someone wasn't standing behind the user when they typed their password right? And what if someone installs a key grabber on the computer? In that case any program, yours included, would have all the key presses logged to a file.
    Alternatively if you might be able to solve it with one of the following...
    - Recode the application to use a GUI. If there is no console the doskey isn't going to get anything.
    - Write some JNI that bypasses the java input handling. If you handle the input directly then you can turn off echo
    - Inspect the java source code for the VM. There might be a hidden method to turn echo off. Alternatively you can find the code responsible for this, modify them, and use them with the bootclass option to replace the ones in the VM. This solution is not distributable. And it might not be possible solely using java.

  • Running single instace of the java application

    Hi,
    I developed a swing based application in java. I am running it through the executable jar. Each time clicking on the jar file it opens the new instance of the appliction.
    But I want to open the single instance of the application i.e. If the application is running , then user tries to open another instance it should be display the error or running application only like yahoomessenger,notepad,etc.
    Please tell me how it is done in java. send aly sample code or resources regarding this.
    Thanks
    in advance

    use jni and access java PID... etc etc it is long way to do that... i think easiest way locking a file and whenever jar runs has to check file whether it is locked or not... if the file is locked, application quits.

  • Executing jar command from the java application

    Hi All,
    In my application i want to create a jar file with the existing class @ Runtime and want to download . But i tried to execute the jar command via Process.getRuntime, it throws IOException. Please guide me or give the solution

    PavithraKarthikeyan wrote:
    Please guide me or give the solutionQuestion your need for this. Why do you think you need to create the jar file.
    P.S. The jar command is only available if the user has the JDK installed so if he has only the JRE installed then you have a problem using Runtime.exec(). There are classes (java.util.jar.JarFile et al) that will allow you to jar files using Java code.

  • Sorry if i sound foolish how to run an applet through a java application

    I am into java from last one month ank keep on exploring it in the want to
    recently i created a application cum applet in the same class like
    applet is doing its own task and there is a main method in the code
    that does entirly different task lets assume displaying *'s on the dos prompt the program is getting complied and belive it its running as desired
    but the only problem that i m facing if i use appletviewer Myclass.java
    only the appletprog is displayed
    and if i run java Myclass than only dos task is done
    may be it is sounding foolish for most of you but if i can get a way
    which will help me in excecuting only one of it and both of them run succesfully
    it tryied different ways to do it but was not succesful
    please do not get irreated if its bizzered but if you really have a solution for it .i will appreciate it
    thanking you

    Yes you can run an Applet from an application. The magic bit is providing an AppletContext and AppletStub!
    Here's how you start it:
            wpa = new WayPointsApplet(this);
            new AppletWrapper(wpa, 380, 320);Here's the class definition: (includes code for my application that can be ignored.
    // Define a wrapper class for the applet
    class AppletWrapper extends Frame implements AppletStub, AppletContext {
        Applet applet;
        // Constructor
        AppletWrapper(Applet a, int x, int y) { 
              applet = a; 
              setTitle(a.getClass().getName());
              setSize(x, y);
              Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
              setLocation((ss.width-x)/2, (ss.height-y)/2);
              add(a, "Center");
              a.setStub(this);
              // Trap window closing
              addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent we) {
                    // Test if Write left undone before exiting???
                    if(WayPoints.wpa != null) {
                      if(!WayPoints.wpa.okToExit())
                         return;           // Ignore
                    applet.stop();
                    applet.destroy();
                    if(WayPoints.debug || WayPointDefs.plot_debug) {
                      SaveStdOutput.stop();
                    System.exit(0);         // EXIT Program
              });  // end WindowListener
              a.init();
              show();
              a.start();
       } // end constructor
        // AppletStub methods
        public boolean   isActive() { return true; }
        public URL       getDocumentBase() { return null; }
        public URL       getCodeBase() {
            return WayPoints.currDir;
        public String    getParameter(String name) {
            if (name.equalsIgnoreCase("DEBUG")) {
                if (WayPoints.debug)
                    return "YES";
                else
                    return "NO";
            if(name.equals("PLOTDEBUG"))
                return (WayPointDefs.plot_debug ? "YES" : "NO");
            if (name.equalsIgnoreCase("SERVER"))
                return "NO";
            return "";
        public AppletContext getAppletContext() { return this; }
        public void      appletResize(int width, int height) {}
        // AppletContext methods
        public AudioClip getAudioClip(URL url) { return null; }
        public Image     getImage(URL url) { return null; }
        public Applet    getApplet(String name) { return null; }
        public Enumeration getApplets() { return null; }
        public void      showDocument(URL url) {}
        public void      showDocument(URL url, String target) {}
        public void      showStatus(String status) {}
    } // end class AppletWrapper

  • Running SSH command after auth

    To save some time, I know about sshrc...
    What I am trying to do is run a script (or file or whatever) after a user is authenticated... This is extremely simple with the use of sshrc, but my users are going to be connecting with the -N argument:
    -N     Do not execute a remote command.  This is useful for just forwarding ports (protocol version 2 only).
    When users are connecting with that, my script does not run...
    Is there an alternate way to run a script?
    By the way... The reason I'm doing this is because I am running a SOCKS server and the users are set to /bin/false.

    Well I am trying to run a script after ssh authentication when the client is connecting with the -N flag....
    I am hosting a socks proxy server, and I want to prevent simultaneous logins with the same user. The proxy users all have the shell set to /bin/false and their default group set to 'proxy '.
    Basically, what I want to do is to disconnect both connections when I detect simultaneous logins...

  • Running an ouside exe from java application

    Hi
    My application should display an help button that will open a pdf file in a browser or in acrobat reader.
    I would like to know how to start an outside applicatioon from my application.
    thanks,
    Liat

    My os is win 2000 professional
    the code:
    public static void main(String[] args) throws Exception {
    Process p = Runtime.getRuntime().exec("c:\\temp\\1.pdf");
    p.waitFor();
    System.out.println("Done.");
    and this is the exception:
    com.bitband.maestro.gui.temp.Demo1
    java.io.IOException: CreateProcess: c:\temp\1.pdf error=193
         at java.lang.Win32Process.create(Native Method)
         at java.lang.Win32Process.<init>(Win32Process.java:66)
         at java.lang.Runtime.execInternal(Native Method)
         at java.lang.Runtime.exec(Runtime.java:566)
         at java.lang.Runtime.exec(Runtime.java:428)
         at java.lang.Runtime.exec(Runtime.java:364)
         at java.lang.Runtime.exec(Runtime.java:326)
         at com.bitband.maestro.gui.temp.Demo1.main(Demo1.java:100)
    Exception in thread "main" Process terminated with exit code 1

Maybe you are looking for

  • Error Trapping for reports

    I inserted a formula column and written an SQL statement which sometimes returns a value. But sometimes there is no data matches the criteria so no row is selected. In this case reports gives fatal error warning and stops. To get around this i wrote

  • Bean Managed Transactions and rollback

    Hi Everybody, I am using Bean Managed Transactions in a Message Bean which is called every some time by an EJB3 timer. This Message Bean subsequently calls a Session Bean which uses Container Managed Transactions and uses the default transaction attr

  • Samsung GX-10 and Pentax K10D RAW support?

    I recently bought a Samsung GX-10 thinking it was essentially the same camera as the Pentax K10D (which is it in hardware). However, it appears that the RAW images cannot be read in Aperture or iPhoto, even thought the K10D is listed as supported. Th

  • Multiple selection of  e_ucomm in ALV Grid toolbar

    Dear SAP friends, I have created HR report. On the selection screen the User enters some initial data  and ALV Grid get displayed. In event Handle_toolbar the program adds a custom button to standard ALV grid toolbar named "ABSENCE/ATTENDANCE". In ev

  • Use of item number in maintenance order

    Hi Experts, Plz tell me what is the use of item number in maintenance order?