Runtime class (with scp command)

Hello
I wrote a working code , but I think there may be a simpler way to do it.
I would like to know if it's possible to use the Runtime class , to connect to a remote server and download a file to my computer, using scp command .
something like:
String command = "scp Username@server : fileWanted destinationPath";
            Runtime runtime = Runtime.getRuntime();
            Process child = runtime.exec(command);Something in this manner(obviously I will need to take care of the password issue).
(A code sample will be great)
thanks,Dave

You might be interested in jsch, Java Secure Channel (BSD license), a pure-Java implementation of SSH2:
http://www.jcraft.com/jsch/index.html
See "ScpFrom.java" in "examples" directory.

Similar Messages

  • Runtime.exec() with get command output

    hi,
    How can i get output of command which i run with runtime.exec().
    p.e.:
    Process p;
    Runtime r = Runtime.getRuntime();
    p = r.exec("net use \\pc\dir pswd /user:username");
    if command was done succesfully that in cmd is return this:
    "The command completed successfully." I can get this text, but i dont know how.
    Plese help
    thank you
    Palo

    Look at the API for Process

  • Executing a command using Runtime Class

    How to execute a command on a differnet machine with different ipaddress using Runtime Class
    My code is
    String[] cmd = new String[3];
    cmd[0] = "192.1...../c:/WINNT/system32/cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
    Runtime rt = Runtime.getRuntime();
    System.out.println("Execing " + cmd[0] + " " + cmd[1]
    + " " + cmd[2]);
    Process proc = rt.exec(cmd);
    // any error???
    int exitVal = proc.waitFor();
    System.out.println("ExitValue: " + exitVal);
    This is not Working

    I have same issue. Actually when I use cmd.exe /c set in java code and if I run the java code in DOS propmt, it retrieves all latest user Environment variable values. But if I run the code in windows batch file, it is not retrieveing the latest user environment values until I reboot my computer, Do you know how to get user environment value with out rebooting machine??????

  • Help with Runtime class and timeout of Process

    Hi,
    Question regarding using Runtime class, and yes I have looked at the javadocs, but I am still confused and frustrated.
    Here is part of my code.
    Process p;
    Runtime runtime = Runtime.getRuntime();
    p = runtime.exec("rsh localhost ls");
    if you are not familiar with rsh all it does is remote shell into the computer localhost and executes the command ls.
    Now, I dont have rsh running on my computer so it will hang at that line for about 40 sec and eventually time out on its own. Is there anyway I can specify a timeout argument like there is for the ping command? Like if there is no response from localhost after 3 sec, then just kill the process?
    I looked at the Runtime javadoc and Process javadoc and the closest thing I could come to with is something to do with envp (environment parameters), but I dont know what that is.
    Thanks guys.

    You can't timeout the "runtime.exec("rsh localhost ls");" call but if you execute the call in a seperate thread you can "timeout" and continue executing on the original thread (while letting the "runtime" thread to timeout on its own).
    Check the following class that I created for cases like this:
    abstract public class TimeoutHelper implements Runnable
        private Throwable error;
        private boolean running = true;
        private Object retValue;
        protected String name;
        private long waitTime;
        private Thread thread;
         * Creates a new helper. Use {@link #start} to run the code.
         * @param name A name that will be used in the helper thread name
         * @param waitTime The time (in msec) to wait before timeout.
        public TimeoutHelper(String name, long waitTime)
            this.name = name;
            this.waitTime = waitTime;
        public Object start() throws Throwable
            return asyncExecute();
        abstract protected Object execute() throws Throwable;
        private synchronized Object asyncExecute() throws Throwable
            createThread().start();
            if (running)
                try
                    wait(waitTime);
                    if (running)
                        // Timeout!!
                        abortThread();
                        throw new TimeOutException("Timeout for: " + name);
                catch (InterruptedException ie)
                    // Ignore
            if (error != null)
                throw error;
            return retValue;
        private void abortThread()
            if (thread != null)
                thread.interrupt();
        protected Thread createThread()
            thread = new Thread(this, name);
            return thread;
        public void run()
            try
                retValue = execute();
            catch (Throwable th)
                error = th;
            synchronized (this)
                running = false;
                notifyAll();
    }You use the class by extending it and implementing "execute". For example:
            TimeoutHelper helper = new TimeoutHelper("Runner", 5000)
                protected Object execute() throws Throwable
                    Runtime runtime = Runtime.getRuntime();
                    return runtime.exec("rsh localhost ls");
            try
                Process p = (Process)helper.start();
            catch (TimeOutException e)
                // Handle timeout here
            catch (Exception e)
                // Handle other errors here.
            }

  • Executing Multiple Commands (Runtime Class)

    granting that Runtime class could execute a command.
    Is it possible to execute a list of commands in
    just one process, for example "cd\javasdk" followed by "dir *.java".
    Any idea to do this?
    Thnx in advance.

    Execute either a script (a batch file) containing all commands or execute the command interpreter (sh, bash, cmd.exe) and feed it through its standard input.

  • Writing a compiler with Compiler and Runtime class

    I am writing a simple compiler that uses the Compiler class to compile a program and the Runtime class to execute the java file. However, I am having trouble located the .class file, and displaying the results when the file is executed. The following code is a segment of my program. Does anyone have any suggestions?
    try
                   saveFile();
                   //Process p = Runtime.getRuntime().exec("javac "+fileName.getName());
              Process p = null;
                   //JOptionPane.showMessageDialog(null,"Compile Message "+p.getErrorStream(), "Message:                
                   ",JOptionPane.ERROR_MESSAGE);
                   s = fileName.getName();
                   int truncStart = s.indexOf(".java");
                   compiled = java.lang.Compiler.compileClasses(s);
                   s = s.substring(0,truncStart);
                   JOptionPane.showMessageDialog(null,"Compile File "+s, "Compile File : ",JOptionPane.ERROR_MESSAGE);
                   p = Runtime.getRuntime().exec("java "+s);
              

    OK, I think I need a delay between my compile stmt and my exec stmt. If anybody has had a similiar problem please let me know how you resolved it. Here is my code so far.
    try
                   saveFile();
              Process p = null;
                   s = fileName.getName();
                   String[] command = {"javac","c:/"+s};
                   try
                   JOptionPane.showMessageDialog(null,"Compile File "+s, "Compile File : ",JOptionPane.ERROR_MESSAGE);
                   p = Runtime.getRuntime().exec(command);
                   catch (Exception q)
                   JOptionPane.showMessageDialog(null,"Compile Error:"                
    +q.toString(),"Error!",JOptionPane.ERROR_MESSAGE);
                   int truncStart = s.indexOf(".java");
                   s = s.substring(0,truncStart);
                   String[] command2 = {"java", "c:/"+s};
                   try
                   JOptionPane.showMessageDialog(null,"Exec. File "+s, "Exec. File : ",JOptionPane.ERROR_MESSAGE);
                   p = Runtime.getRuntime().exec(command2);
                   catch(Exception y)
                   JOptionPane.showMessageDialog(null,"Exec Error :"+y.toString(),"Error!",JOptionPane.ERROR_MESSAGE);
                   }

  • BCP data into a file using Runtime class

    Hi,
         I have a problem in using the Runtime class.
    I am trying to bcp a table's data into a file.I am working on a Unix environment.
    My bcp is not getting completed fully.The total records to be bcped is 1 million,but only one lakh records is getting bcped and then it hangs up..But if i issue the bcp command from my telnet session it is bcping it to the file without any problem.Can anyone help me out on how to overcome this..
    Is there anything specific with Runtime class..I am pasting the code that i tried out below.
    String l_s_bcpQuery="bcp mubstage.dbo.HousingUnitSampleMarket out /dun/d3nmb0/mariaps/subracheckprototype -c -t~ -Umariaps -Prykwz5ba -SD3NMB_MUB";
    try{
    Runtime time=Runtime.getRuntime();
    Process p=time.exec(l_s_bcpQuery);
    p.waitFor();
    System.out.println("The exit value is:"+p.exitValue());
    }catch(Exception ioe){
         ioe.printStackTrace();
         System.out.println("IOException"+ioe.getMessage());

    you might need to capture the stout & sterr from the process. see http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Process.html, or many other similar questions on this forum.
    try this:
    try{
    Runtime time=Runtime.getRuntime();
    Process p=time.exec(l_s_bcpQuery);
    BufferedReader stout = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader sterr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    String out = stout.readLine();
    String err = sterr.readLine();
    while((out != null)||(err != null))
    if(out != null)
    System.out.println(out);
    if(err != null)
    System.err.println(err);
    out = stout.readLine();
    err = sterr.readLine();
    int exit_value = p.waitFor();
    System.out.println("The exit value is:"+ exit_value);
    }catch(Exception ioe){
    ioe.printStackTrace();
    System.out.println("IOException"+ioe.getMessage());
    }

  • FTP using Runtime class ...Please Help ??

    Hi,
    I am trying to ftp a file programatically.
    I am trying to use Runtime class but facing problems
    in it.This is what I am trying to do :
    Runtime rr = Runtime.getRuntime();
    String[] cmds = new String[2];
    cmds[0]="username=rahmed";
    cmds[1]="password=prpas";
    try{
    Process p = rr.exec("ftp 192.168.1.18",cmds);     
    rr.exec("put vv.txt");
    This does not work ??
    Is there any way to make it work ? Or is there any
    other way to ftp a file programatically ??
    Thanks in adavance..
    Regards
    Rais

    Under Linux/Unix at least, it is good to use the switches -n and -i with the ftp client acually meant for intercative usage.
    -i Turns off interactive prompting during multiple file transfers.
    -n Restrains ftp from attempting ``auto-login'' upon initial connection.
    I do "user <myuser> <mypassword>" then from the script.
    I am happily using ftp this way from shell-scripts in my projects.
    scp is however better than ftp: it does not send plain text passwords over the net, it support key-based login, its encrypts the data.

  • Using Runtime class

    Hi,
    i would like to run a an external java program from within another java program,
    here is the structure of my called parogram
    c:/temp/jetty
    /lib/*.jar
    start.jar
    my caller program have to invoke the start.jar, but this jar uses the lib folder
    so my code construct a java command with the -cp options giving all the jar, and finally use th runtime class to call start.jar
    here is the code :
    String command = "java -cp D:/temp/jetty/lib/jetty-6.1.0.jar;D:/temp/jetty/lib/etc/another.jar -jar D:/temp/jetty/lib/jetty-6.1.0/start.jar"
    Runtime runtime = Runtime.getRuntime();     
    runtime.exec(command);
    it doesnt work, (classnot found error!!!) evenif i include in the cp option all the jar,
    my question is how to force the runtime to start the execution at c:/temp/jetty ??
    can anyone help

    Try this for ideas
    package testing;
    import java.io.IOException;
    public class Test
      public static void main(String[] args) throws IOException
        Runtime.getRuntime().exec("java -jar AnotherJar.jar");
    }and
    package testing;
    import javax.swing.JOptionPane;
    public class Another
      public static void main(String[] args)
         JOptionPane.showMessageDialog(null, "Another .jar running", "Blaa blaa", JOptionPane.INFORMATION_MESSAGE);
    }Then compile both, create manifests for both, create the jars (name the .jar corresponding to class Another as AnotherJar.jar), put the jars in the same directory and run the .jar that corrsponds to class Test.
    edit
    And obviously, in your case, you need to add the line
    Class-Path: lib/*.jar
    to the manifest of the program that needs the jar in directory lib.
    Message was edited by:
    duckbill

  • Problem to use SAPServer Class with load balancing

    Hello,
    We use the SAPServer Class from SAP .Net Connector 1.0.
    On our system, we want to start the RFC Server to use the logon group.
    I didn't find how to use ServerMessage and LogonGroup with one of constructors.
    When we start the SAPServer with the command line -aUSER -gBEAUSR201 -xsapgw10 from the DB server (BEAUSR201) it's Ok,
    but when we start from one of our application Server (for example -aUSER -gBEAUSR213 -xsapgw13 ) it's KO
    we have this message on the trc file.
    ERROR file opened at 20041125 084739 Paris, Madrid, SAP-REL 620,0,1622 RFC-VER 3 683864 MT-SL
    T:13188 ======> Connect to SAP gateway failed
    Connect_PM  TPNAME=USER, GWHOST=BEAUSR214, GWSERV=3314
    LOCATION    CPIC (TCP/IP) on local host
    ERROR       hostname 'BEAUSR214' unknown
    TIME        Thu Nov 25 08:47:39 2004
    RELEASE     620
    COMPONENT   NI (network interface)
    VERSION     36
    RC          -2
    MODULE      ninti.c
    LINE        385
    DETAIL      NiPHostToAddr
    SYSTEM CALL gethostbyname
    COUNTER     1
    What is the solution ?
    Thanks

    Hi,
    The message server and Logon group are there for balancing the load among application servers within a SAP system. You are using the SAPServer class to implement an external RFC server that usually serves the request from SAP servers. So using message server and logon group with an external server doesn't make sense.
    I understand that both your DB server and the application server in question are Windows machine with .NET runtime installed and you started the SAPServer programs directly from Windows command line. If so, the error message for the KO case says that the hostname BEAUSR214 could not be resolved from the application server. I also noticed that the hostname BEAUSR214 in error message doesn't match the hostname BEAUSR213 given in command line.
    Can you ping BEAUSR213 or BEAUSR214 from the application server in concern?
    Regards,
    Guangwei Li

  • Java programming - Runtime class

    hi
    I am not able to copy a file using Runtime class in java.lang
    i have used
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("copy c:/venk1/pmrpay.jar F:/");
    pr.waitFor();
    when running the program i am getting this error message:
    create process: copy c:/venk1/pmrpay.jar F:/ error = 2
    kindly help me
    venkat

    There is no copy.exe on your system. Copy is command interpreted with command.com. So you need to try something like
    Process pr = rt.exec("cmd /c copy c:/venk1/pmrpay.jar F:/");
    See
    cmd /?
    for details... Hope this will help you!

  • Using SCP command through Startand Java Library

    Hello,
    Is there any class or way available in Standard Java Library to use SCP command. Actually I want to copy file from one Linux system to another through Java code using SCP protocol .
    Zeeshan Hanif

    If we can't dissuade you from this course, I'll help you get started: go find RFC 4251, read it, understand it, love it. Then you'll have to do the same with 4252, 4253, 4254, 4255, and 4256. Also, don't forget 1321, 1950, 2104, 2144, 2409, 2440, 3447, and 3526. Then just brush up on java sockets, crypto and IO. Easy as pie! (assuming that pie has 15,641 ingredients, 63 layers, a nine-volume recipe, and must be baked in a perfect vacuum)
    :-)

  • Getiing error while genetrating jar file with xml beans with scomp command

    Hi ,
    I am using XmlBeans version 2.4.0-r670094 with jdk1.5 ,
    i am trying to generate java classes with given xsd's command is ----scomp -out emplo.jar any.xsd
    but getting below error
    Time to build schema type system: 1.953 seconds
    Time to generate code: 0.125 seconds
    java.io.IOException: Cannot run program "C:\\javac": CreateProcess error=2, The system cannot find the file specified
    java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    java.io.IOException: Cannot run program "C:\\javac": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at org.apache.xmlbeans.impl.tool.CodeGenUtil.externalCompile(CodeGenUtil.java:231)
    at org.apache.xmlbeans.impl.tool.SchemaCompiler.compile(SchemaCompiler.java:1154)
    at org.apache.xmlbeans.impl.tool.SchemaCompiler.main(SchemaCompiler.java:373)
    Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 6 more
    BUILD FAILED
    any solution for this

    Hi ,
    i have done all those things , please check below my environment variables path
    PATH=C:\oracle\product\10.2.0\db_3\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS
    \System32\Wbem;C:\Program Files\ActivIdentity\ActivClient;C:\Program Files\Java\
    jdk1.5.0_16\bin;C:\Program Files\Java\jdk1.5.0_16\lib;C:\xmlbeans-2.4.0\bin;C:\j
    devstudio10133\ant\bin;C:\xmlbeans-2.4.0\lib;
    i am using xml beans version - xmlbeans-2.4.0
    if i am running scomp.cmd -out CIDnotification2.jar CIDnotification2.xsd -compiler "C:\Program Files\Java\jdk1.5.0_16\bin"
    or
    scomp.cmd -out CIDnotification2.jar CIDnotification2.xsd
    i am getting below error
    Time to build schema type system: 0.797 seconds
    Time to generate code: 0.156 seconds
    java.io.IOException: CreateProcess: "C:\Program Files\Java\jdk1.5.0_16\bin" @C:\
    DOCUME~1\RAMAKR~1\LOCALS~1\Temp\javac9915 error=5
    null
    java.io.IOException: CreateProcess: "C:\Program Files\Java\jdk1.5.0_16\bin" @C:\
    DOCUME~1\RAMAKR~1\LOCALS~1\Temp\javac9915 error=5
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at org.apache.xmlbeans.impl.tool.CodeGenUtil.externalCompile(CodeGenUtil
    .java:231)
    at org.apache.xmlbeans.impl.tool.SchemaCompiler.compile(SchemaCompiler.j
    ava:1154)
    at org.apache.xmlbeans.impl.tool.SchemaCompiler.main(SchemaCompiler.java
    :373)
    BUILD FAILED
    Please let me know if something else required

  • Unable to start Tomcat using runtime class in windows 98

    hi,
    I am using a runtime class which calls a batch file, that calls statup.bat for starting tomcat.
    This works perfectly in windows NT,2k. But on win 98, the tomcat window opens and closes within no sometime.
    In my class i call the first batch file starter.bat using
    Runtime.getRuntime().exec("%COMSPEC% /c start e:/starter.bat");
    (I tried with command.com also...)
    Starter.bat has the line
    call E:\jakarta-tomcat4.1\bin\startup.bat.
    Is there anyother way to start the tomcat process and keep it running on windows 98. Anyone with anyclues pls help.
    Thanks in advance.

    This is the Runtime class i am using... Sometimes tomcat gets closed and sometimes just hangs... (putting it in for better understanding..)
    public class Starter {
         public static void main(String[] args) {
              String com = "%COMSPEC% /c start
    C:\\PACS\\SFAApp\\tomcat\\startup.bat";
                   try     {               
                        Runtime rt = Runtime.getRuntime();
                        Process pr = rt.exec (com);//Starting tomcat
                        try
                             pr.waitFor();     
                        catch (Exception e)
                             e.printStackTrace();
                   catch (IOException ie) {
                        System.out.println("IOException caught" + ie);
                        ie.printStackTrace();

  • Runtime class exec statement

    I would like to know why while using a Runtime class object with exec method it is able to execute certain commands where as it is not able to do certain other. Like Procees p, Runtime r and p=r.exec("notepad abc.dat" works and p=r.exec("java abc") doesnot work.the path has been set also. How can one call other java programs to be executed from one program? are there other ways. tried jexepack with a very limited success.

    Here's one way of doing it albeit not via the Runtime path - here you just need to provide the class which needs to be invoked as value of variable 'className'. This by default runs the class with no arguements to main - if you wish to provide some args then do so in variable 'argListForInvokedMain'
    String className = "a";
    try {
    Class[] cls = new Class[1];
    cls[0] = String[].class;
    Method mainMethod = Class.forName(className).getDeclaredMethod("main",cls);
    Object[] argListForInvokedMain = new Object[1];
    argListForInvokedMain[0] = new String[0];
    //put arguements in here
    mainMethod.invoke(null,
    argListForInvokedMain);
    catch (ClassNotFoundException ex) {
    System.out.println("Class "+ className +" not found in classpath.");
    catch (NoSuchMethodException ex) {
    System.out.println("Class "+ className +" does not define public static void main(String[])");
    catch (InvocationTargetException ex) {
    System.out.println("Exception while executing "+ className +":"+ex.getTargetException());
    catch (IllegalAccessException ex) {
    System.out.println("main(String[]) in class "+ className +" is not public");
    Hope this helps
    John Morrison

Maybe you are looking for