Execute command on remote linux and return output?

Guys,
I'm new to Java and still working hard on my way thru.
I used a client software "putty" to logon to a linux machine. as the window is exactly like what it is in linux. in "/proc" I typed in "grep cpu stat" which returned 2 lines result of the cpu status on the screen.
now, I have to do the same thing in Java. To execute a line of command "grep cpu stat" on the remote linux. then return the 2 lines result to my code and store them in string variebles. Can anyone please help me with this and show me some sample code of doing this Please.
Thanks, and thanks big time
, Jimbo

Hi,
look at this code, maybe it will help you...
//this is only method
public int exec(String[] command, OutputStream outStream) {
     Process p;
     int exitValue = -1;
     ByteArrayOutputStream tmpErr = new ByteArrayOutputStream(OUTPUT_BUFFER_SIZE);
     try {
          p = Runtime.getRuntime().exec(command);
          BufferedInputStream out = new BufferedInputStream(p.getOutputStream());
          ThreadStreamPumper pumper = new ThreadStreamPumper(out, tmp);               pumper.start();
          p.waitFor();
          exitValue = p.exitValue();
          pumper.join();
          out.close();
          p.destroy();
          tmp.close();
          tmp.writeTo(outStream);
     } catch (IOException ioe) {
          return -3;
     } catch (InterruptedException ie) {
          return -4;
     boolean isOkay = exitValue == 0;
     if (tmp.size() > 0) {
          return -5;
     return exitValue;
//this is class
*  class for continually pumping the input stream during Process's
*  runtime.
class ThreadStreamPumper extends Thread {
     private BufferedInputStream stream;
     private boolean endOfStream = false;
     private boolean stopSignal = false;
     private int SLEEP_TIME = 5;
     private OutputStream out;
      *  Creates new <code>ThreadStreamPumper</code>
      *@param  is   From where to pump datas
      *@param  out  Where to send datas
     public ThreadStreamPumper(BufferedInputStream is, OutputStream out) {
          this.stream = is;
          this.out = out;
      *  Gets datas from <code>in</code> and sends them to <code>out</code>.
      *@exception  IOException  When some IO error occurs
     public void pumpStream()
           throws IOException {
          byte[] buf = new byte[BUFFER_SIZE];
          if (!endOfStream) {
               int bytesRead = stream.read(buf, 0, BUFFER_SIZE);
               if (bytesRead > 0) {
                    out.write(buf, 0, bytesRead);
               } else if (bytesRead == -1) {
                    endOfStream = true;
      *  Main processing method for the <code>ThreadStreamPumper</code>
     public void run() {
          try {
               //while (!endOfStream || !stopSignal) {
               while (!endOfStream) {
                    pumpStream();
                    sleep(SLEEP_TIME);
          } catch (InterruptedException ie) {
          } catch (IOException ioe) {

Similar Messages

  • Execute webdynpro from abap program and return to the caller program

    Guys,
    I have a question here.
    I know there is a way to call an abap webdynpro application from normal abap program by either using a class method, or use a function module WDY_EXECUTE_IN_PLACE by providing
    the webdynpro application or using CALL TRANSACTION statement.
    But, is there anyways that we can call the webdynpro application from abap program by supplying data to the webdynpro and display to the user from the portal, and then
    once the user do some manipulation on the data, can we transfer back the data to the caller abap program?

    hey ,
    you can pack any web-dynpro program in tranasaction code and run it from R/3 and not via portal  :
    search in " SAPTECHNICAL" how to do so  - for some reason i cant post a link here
    than you can use call transaction .
    regards
    ASA

  • Execute db function from adf and return collection

    Hi All
    jdev version : 11.1.1.3
    db : oracle
    Can anyone suggest how do I get a collection(cursor or array) from a db function in a db package?
    I want to call it from the adf side using a preparecall and executeupdate

    Use Oracle's JDBC extentions of the standard Java JDBC API. Have a look here:
    http://docs.oracle.com/cd/B28359_01/java.111/b31224/oraint.htm#BABBGDFA
    http://docs.oracle.com/cd/B28359_01/java.111/b31224/oraarr.htm
    Dimitar

  • Problem of executing a process under Linux using Runtime.exec

    Hi, All
    I am having a problem of executing a process under Linux and looking for help.
    I have a simple C program, which just opens a listening port, accept connection request and receive data. What I did is:
    1. I create a script to start this C program
    2. I write a simple java application using Runtime.exec to execute this script
    I can see this C program is started, and it is doing what it supposed to do, opening a listening port, accepting connection request from client and receiving data from client. But if I stop the Java application, then this C program will die when any incoming data or connection request happens. There is nothing wrong with the C program and the script, because if I manually execute this script, everying works fine.
    I am using jre1.4.2_07 and running under Linux fedora 3.0.
    Then I tried similar thing under Windows XP with service pack2, evrything works OK, the C program doesn't die at all.

    Mind reading is not an exact science but I bet that you are not processing either the process stdout or the stderr stream properly. Have you read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html ?

  • What is happening about: The GNU Bourne Again Shell (Bash) is a command line utility widely used in many Unix-based operating systems including Linux and OS X.  Researchers have discovered a critical flaw in Bash which could allow remote code executi

    Authoritative advice today:
    The GNU Bourne Again Shell (Bash) is a command line utility widely used in many Unix-based operating systems including Linux and OS X.
    Researchers have discovered a critical flaw in Bash which could allow remote code execution by an unauthenticated user
    APPLE response?

    Also see:
    http://www.macrumors.com/2014/09/26/apple-os-x-users-safe-bash-flaw-update-soon/
    If you are not running a web server
    If you have not enabled CUPS web interface
    If you do not allow anonymous users to ssh into your Mac.
    If all are no, they you are not at risk.
    This IS a very serious bug for web servers, but the typical consumer Mac user is not at risk.

  • Execute command and save output in a HTML File

    Hello Guys,
    I have a requirement and for that i have to do following. a) read a file in an array and then execute a command for each value in that array. after that i want to store the output of command and value of array in another array.
    i am doing something like below.
    set objtextfile = objfso.opentextfile _
    ("c:\temp\aaaa.txt", forreading)
    j=0
    Do until objtextfile.atendofstream
    redim preserve arr123(j)
    arr123(j) = objtextfile.readline
    j = j+1
    Loop
    for each server in arr123
    chk_status = "command" &" "& server
    set objexecobject = objshell.exec(chk_status)
    'Here i am not sure how to proceed further to achieve what i described above.
    Next
    Can someone help me with this?
    -KAKA-

    Thank you for your response.
    So here is what i want to do.
    Query a database using odbc from my management server (odbc is configured and connection is tested) and based on the query it will result out few list of servers. then from the same management server i want to execute a command against all the resulted server
    (management server has a binary which can execute remote action). this remote action will get output back.
    then i would like to store the name of server and resulte output in a html file which should look like below.
    which i will later host on apache.
    YOu do not need to move things in and out of arrays and files.
    >>>> You are right but as i stated, i am not a core programmer and due to nature of my job i have to work on perl, shell and VB Script, apart from my actual technology so it becomes difficult to write it with perfection.
    I hope you understand.
    -KAKA-
    -KAKA-

  • Remoting and localized output from executables

    Hello all, I am in need of a bit of assistance.
    We have client computers which have non-English Windows 7, and thus any executable that produce output produce non-English output. This is not a problem when using PowerShell locally, all localized output is displayed properly.
    Problems arise when using PowerShell remoting, where output does not display non-English characters correctly. Examples of native executables which produce incorrect output: ipconfig, ping, wingmmt.
    Host's output encoding:
    IsSingleByte      : True
    BodyName          : ibm850
    EncodingName      : Western European (DOS)
    HeaderName        : ibm850
    WebName           : ibm850
    WindowsCodePage   : 1252
    IsBrowserDisplay  : False
    IsBrowserSave     : False
    IsMailNewsDisplay : False
    IsMailNewsSave    : False
    EncoderFallback   : System.Text.InternalEncoderBestFitFallback
    DecoderFallback   : System.Text.InternalDecoderBestFitFallback
    IsReadOnly        : True
    CodePage          : 850
    Remoting output encoding:
    IsSingleByte      : True
    BodyName          : iso-8859-1
    EncodingName      : Western European (Windows)
    HeaderName        : Windows-1252
    WebName           : Windows-1252
    WindowsCodePage   : 1252
    IsBrowserDisplay  : True
    IsBrowserSave     : True
    IsMailNewsDisplay : True
    IsMailNewsSave    : True
    EncoderFallback   : System.Text.InternalEncoderBestFitFallback
    DecoderFallback   : System.Text.InternalDecoderBestFitFallback
    IsReadOnly        : True
    CodePage          : 1252
    Following command can be run to change console output encoding to UTF8:
    [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
    However, running this on remote session will result in "Exception setting "OutputEncoding": "The handle is invalid." Running this on host works, but has no effect on remote session.
    Apparently $OutputEncoding only works for input, not output. But I tried to set it to UTF8 anyway, with no effect.
    This problem does not affect PowerShell cmdlets, as Write-Host and Write-Output produce correct output even in remote session.
    Previously host had PowerShell 3 and client had PowerShell 2, now both have PowerShell 4 and problem still persists.
    Anyone know how I can receive correct output from localized native executables? Thanks in advance.

    Actually I am using PS remoting from server to client workstations.
    I have provided several examples of commands that produce incorrect characters in place of non-English characters in the first post. Likewise I have provided encoding info in the first post.
    As for culture info, info below.
    Get-Culture on host:
    LCID             Name             DisplayName
    1035             fi-FI            Finnish (Finland)
    Get-Culture in remote session:
    LCID             Name             DisplayName
    1035             fi-FI            Finnish (Finland)
    Get-Culture locally on client:
    LCID             Name             DisplayName
    1035             fi-FI            Finnish (Finland)

  • Execute command of Linux

    Dear All,
    I want to execute command below but I don't know the step. Could anyone help me on this. I try to enter using root password & type this command but no output appeared. Please advice;
    1. File permission of 1) /etc/passwd and 2) /etc/shadow file by executing either one of the command below:
    /usr/bin/cat/ls -l /etc/passwd
    or cat ls -l /etc/passwd
    /usr/bin/cat/ls -l /etc/shadow
    or cat ls -l /etc/shadow
    2. Password configuration setting of Linux by excuting the all 3 commands
    below:
    a) /usr/bin/ls -l /var/log/ >var_log.txt
    /bin/cat/etc/pam.d/login > etc_pamd_login.txt
    b) /bin/cat/etc/login.defs > etc_logindefs.txt
    /bin/cat/etc/pam.d/system-auth > etc_pamd_systemauth.txt
    c) /bin/cat/etc/pam.d/system-auth > etc_pamd_systemauth.txt
    /bin/ls-l/etc/security/opasswd > etc_security_opasswd.txt

    The no ip rcmd rsh-enable command does not prohibit a local user of the router from executing a command on other routers and UNIX hosts on the network using rsh. The no form of this command only disables remote access to rsh on the router.
    For more information on rsh please click following link:
    http://www.cisco.com/en/US/products/sw/iosswrel/ps1831/products_command_reference_chapter09186a00800d9833.html#1018286

  • Execute commands remote with PSSession

    Hi,
    I am trying to write a script that is executed on Server A but connects to Server B and executes the commands with remote Powershell.
    I am currently just trying some simple commands since it's the first time I have tried the remote Powershell function. I connect to a server which is working fine, but if I do a simple command like:
    $FoundFiles = Get-ChildItem - Path "C:\Temp"
    it returns an error telling me that it cannot find the path. If I do the same and use "C:\Windows" it works.
    If I enter the commands manually in a console everything also works as expected.
    Lasse
    /Lasse

    If you do this:
    Enter-PSSession -Name TestConnection
    $tmpFiles = get-childitem -path "C:\temp"
    you will be running  from the remote system and c:\temp will have to be on the remote system.  Either copy the file there or use invoke.
    Spend some time testing the commands until you sort out how remoting works.   When you enter a sessin your prompt changes to tell you you are now running on the remote system and all references are to the remote system.
    This works the same but references are local and execution is remote:
    $session=New-PSSession  -ComputerName Servername
    invoke-command -file c:\temp\script.ps1 -Session $session -ArgumentList '-param1 xxxx','-param2 vvvvv'
    I can also alter the session:
    PS C:\scripts> invoke-command -command {$newvar='hello remote'} -Session $session
    PS C:\scripts> invoke-command -command {$newvar} -Session $session
    hello remote
    Notice the session is retained. I can load modules in one command or file and use them in another:
    We can also use -AsJob for very long running scripts and invoke against a list of computers.
    it is not just a telnet like session but a full remote targetable session.
    ¯\_(ツ)_/¯

  • Output to command line in Linux with built exe

    Hi Folks,
    Here's an interesting challenge...
    I've got a VI that a customer wants to use as a command line utility in
    Linux.  I've gotten command line arguments in without any
    problem.  However, I can't seem to figure out how to get strings
    back out to the prompt.  The first thing I tried was the system
    exec VI that's in the communication palette.  Is there something
    silly I've overlooked?
    I've also seen some very limited discussion on how to output to the
    command line using Windows API calls.  However, please remember
    that I'm trying to output to the command line in Linux.
    Thanks very much as always.
    Jim

    Hi Jim,
    You can accomplish this using the pipe commands. Just don't open the
    handle, stdout (0), stdin (1), and stderr (2) are always open. See the
    attatched VI.
    For the record, I haven't tried this as an executable, but it works
    running in LabVIEW and I have no reason to expect that it wouldn't work
    as an exe.
    Jason
    Attachments:
    stdout.vi ‏17 KB

  • Execute commands on a remote server

    hello,
    1. how can i execute commands on a remote server using java (how to connect and how to execute) without having java on the remote server
    (i cannot connect with Socket object)
    2. how can i execute commands on the local computer
    please help me

    Well, for #1, if you can possibly know what commands you'd have to call you could set a perl script up on the remote machine to perform that command and return to you the results. problem is, you'll have to have a web server of some sort to do this (as far as i know).
    I know it's not a very good solution, but it's helped me plenty of times where i couldnt install Jakarta or the likes on a server and couldnt connect to it using sockets.
    Justin

  • Ways to run dir command in Process and get Output

    Hello,
    In one of the control in our web application, User can select any directory from his work area and can get list of directories and content of directories i.e. list of files. As working on file object is really slow so the performance is extremely poor. I am thinking of using Process object and run dir command for any directory selected by user and show the directory listing to user.
    Do you guys think it would be possible

    Its always good to work with IO buffer than low level file api. That should be irrelevant to the question as asked (if not then there might be other problems.)This is no way irrelevant but its a fact. Working with Java File api to traverse the content of the directory is really painful. Because we currently use file api to help user to traverse thru her work area.
    BTW, there are two servers. One running the app and the other have all users work areas. User can traverse the workareas content by using something \\server1\workarea1\user1\folder1 etc... in the app to see the content of any folder.A "server" in this context would be an "application" such as something like tomcat. Your client would then ask the "server" for information.
    In your case you are dealing with another file system via the windows remote file system access. So per my question it is not another "server".A server is what providing service to a client and in our case its a app server with a web app in it. The users use the web app to manage their work area(which is another file server).
    The app server and file server and physically two separate machines.
    So again, I am back to my first question, how can run dir command using Process object and get the buffer.
    Till now, I have done this
    ProcessBuilder pb = new ProcessBuilder("cmd", "dir", "c:/");
            pb.directory( new File("C:/temp")); // Or whatever directory you want for cwd
            Map<String,String> env = pb.environment();
            env.put("PATH", "C:/temp");
            try {
                 Process process = pb.start();
                   InputStream inStream = process.getInputStream();
                   new AsyncPipe(process.getErrorStream(), System.out).start();
                 new AsyncPipe(process.getInputStream(), System.out).start();
                 final int returnCode = process.waitFor();
                 System.out.println("Return code is " + returnCode);
                   System.out.println("\nExit value = " + inStream + "\n");
              } catch (Exception e) {
                   e.printStackTrace();
              }However it simply opens command prompt

  • Telneting to a remote host and executing unix shell script

    I am using VPN.I want to telnet to a remote server and execute some script there and show it the output in my front end..is it easily possible thru java..i know it can be easily done thru Python...can anyone let me knw if this can ve achieved properly thru java..thnx plz let me knw ASAP.

    Yes surely I have wriiten the code..
    I have first used a Socket to connect to teh host at port 23.
    Then i am using outstream to give the user and passwd .. but in my Inputstream i am getting some vague outputs (some symbols..$,%,etc..) This is the code for ur reference....
    import java.net.*;
    import java.io.*;
    class Telclient {
    public static void main(String args[]) {
    int c;
    try{
    Socket s=new Socket("abc.net",23);
    InputStream in=s.getInputStream();
    OutputStream out=out.getoutputStream();
    String str="user" + "\n" + "password" + "\n";
    byte buf[]=str.getBytes();
    out.write(buf);
    while((c=in.read()) != -1) {
    System.out.println((char)c);
    s.close();
    Please help with teh code , bcoz its not really working..Need urgent helpI also used TelnetClient from jakarta , but failing to understand
    how to use those classes to use..can anyone show me an example...

  • Whats the difference between producing output and returning a value?

    I've just started learning Java. I am having difficulty understanding what it means to "return a value".
    If a method has an argument, then whenever this method is called the variable named will be used for output.
    If you create a method to return a new value rather than display it, you would exchange the 'void' for 'double' e.g. public static double predictRaise(double moneyAmount). My book states that a return statement causes a value to be sent from a called method back to the calling method. Their example is not clear to me. Here is what they show for when only 'output' is produced:
    <code>
    Public static void predictRaiseUsingRate (double money, double rate)// 2 arguments
              double newAmount;
              newAmount = money * (1 + rate);
              System.out.println (?With raise, new salary is ? + newAmount);
    </code>
    And their example of a returned value:
    <code>
    public static double predictRaise(double moneyAmount)
              double newAmount;     
              newAmount = moneyAmount * 1.10;
              return newAmount;
    </code>
    Their explanation: "This return statement causes a value to be sent from a called method back to the calling method. The value stored in newAmount is      sent back to any method that calls predictRaise() method."
    For some reason this is just not sinking in. Does anyone have a better example/explanation? I could not find anything with a better explanation in archives.
    Are they tring to tell me: "if the original method declares an argument that is declared as 257 in the method call, that when that same method is called again, it will always be 257? But if you do a return statement, any changes in the return statement will now always be used in all methods calling that method?
    Thanks for your help.
    Gizelle

    To use an older and possibly more easily understood terminology. Methods can either be "functions" almost in the mathematical sense or they can be "procedures" in the sense of a process.
    A function is a mapping between a "domain", its arguments, and a "range", its result. An example of a function in mathematics is cosine, which takes an argument in degrees or radians and returns a result between -1 and 1. In java functions are just methods that declare a result type. eg. public int foo(int arg).
    A procedure is a program that doesn't return any result, it's not something that fits well into mathematics, but it occurs all the time in real life. For example, walking the dog does not map something from a domain to a range, but it may have some side effects, which is why I always carry a plastic bag with me. Procedures in java are methods that are declared as "void". eg. public void foo(int arg).
    All the well known arithmetic operations are functions, they take one or two arguments in the domain of numbers and return a result in the same set. Eg, x = a + b, the operator + is a function that takes two numbers, calculates the arithmetic sum of them and returns a result. Functions are very handy since you can string them together, eg. z = a+foo(b)*max(c+d). This doesn't work with procedures.
    Procedures are often used for much longer and more involved operations, there is no immediate result, but a lot of things may occur while they run. Data may be printed on a screen or paper, a database or file may get updated and email messages might get send. But no other expession is waiting for a resulting value so it can carry on. Procedures may also happen asynchonously, ie. outside the timeframe of their caller, see threads. Functions cannot do this, or if they do, they turn into procedures by throwing away their result. For example, you can schedule a procedure to send an email to your friends every Friday inviting them to go out for drinks, but you don't wait around for the result.
    In a way functions are a bit like phone calls, you wait for a response, procedures are more like snail mail, you send it off and check on what happened later.
    I hope this helps.

  • How to output executable Bin file under linux from java

    Hi
    im beginner in java under linux and i want to out put my java programs to be bin files that can run
    if this not possilble
    how to run the output jar files with just double click ?
    does i have to run sh file that do the hob how?
    thanks in advance.

    say your main method (application's entry point) is located in a class com.my.Class,
    then first you create a text file (say, manifest.txt) that contains this line:
    Main-Class: com.my.Class
    [/code}
    and then you append this to the jar's manifest as such:
    jar cfm yourjarfile.jar manifest.txt [additional files you might want to add]
    for more info,
    http://java.sun.com/docs/books/tutorial/deployment/jar/manifestindex.html                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Maybe you are looking for

  • No sound through HDMI cable

    I have an HP Phenom DV7-4178NR.  Audio works fine on the PC.  Audio also works fine with the HDMI cable through other devices.  I know it's a problem with the laptop and not the cable.  Under device manager, display adaptors it says: AMD M880G with A

  • Western Digital external hard drive not working properly

    I have this external hard drive from western digital, 2 TB space, in wich i stored data from a windows machine. Now i moved to an arch machine (the one i have at home) and it doesn't mount the hard drive. I tried as normal user and as root, i tried j

  • Remove Bogus Font from PDF?

    I create the quarterly PDF of Hinduism Today magazine, on Macs, in InDesign, individual articles are exported to PDF as spreads and assembled in Acrobat to produce a single PDF of the entire magazine: nothing new there... Now, my final PDF is showing

  • Read data on click of a button

    Dear Experts, i have a critical requirement where in i need to default some text in the form on clicking a button on the form. I have created an ISR button on the form and created a new backend generic service to default the text on the form. The gen

  • ITunes 11 update gone wrong

    Ok....so I have been using iTunes 10.7 (or whatever the latest one before iTunes 11 is) on my Windows laptop and it has been working fine ever since i bought my iPhone 5. When my Apple Update told me to update to iTunes 11, I tried to update it and i