Capturing Unix command output in WLST

I am trying to write a WLST/Python script that connects to a particular domain based on the machine the script is run on. My thought was to issue the 'hostname' Unix O/S command get the name of the machine, test against it, and connect based on the output. My initial thought was to do something like
import os
hr = os.system('hostname')
if hr == 'name':
ConnectToAS()
This doesn't work of coarse because the os.system() command returns the boolean exit code of the statement and not the output. I then tried looking into using the 'subprocess' mod but that returns the following:
Problem invoking WLST - Traceback (innermost last):
File "/home/beaadmin/bin/scripts/wlst/wip/checkMachine.py", line 1, in ?
ImportError: no module named subprocess
Does anyone know of another way to run a WLST/Python script that get's the name of the machine it's running on and make that name available to the rest of the calling script?
Any help would be greatly appreciated.

Thanks for the reply but I was hoping to stay away from external dependencies. Since you have to set the environment to run WLST we use shell scripts as wrappers to launch WLST. I think I will look at getting the hostname from the shell script:
hn=`hostname` and then pass that to WLST:
java weblogic.WLST script-name.py $hn
I am hoping to be able to test against it with Python:
import sys
HOSTNAME = sys.argv[1]
if HOSTNAME == 'some-machine-name':
connect to something
of coarse with this I would need to hard code all the machine names in the Python script to test against and then modify the script if we ever add machines. sigh I guess if it was easy I wouldn't appreciate it.
Edited by: user8004556 on Sep 1, 2011 11:21 AM

Similar Messages

  • Capturing a command output from unix

    Hi All
    I am using enchanter to connect to unix and running a command but how do i capture the output of the command. Follwoing is the code i used.
    import java.io.IOException;
    import org.twdata.enchanter.SSH;
    import org.twdata.enchanter.impl.DefaultSSH;
    public class connect {
              public static void main(String[] args) throws IOException {
                   SSH ssh = new DefaultSSH();
                   ssh.connect("ip address", 22, "username", "pwd");
                   ssh.sendLine("ls -lrt");          
                   System.out.println(ssh.getLine());               
                   ssh.disconnect();
    }Thanks
    Diana

    [http://code.google.com/p/enchanter/]

  • Capturing print command output from procedures

    Is it possible to capture the output from print statements in stored procedures such as the "print" command in Sybase stored procedures? This information doesn't seem to come through the result set.
    Thanks,
    KP

    This will be database specific. Please consult your database documentation.

  • Unix command output to a TextArea

    Hi,
    I would like to use the contents of the variable >>line<< to be displayed in a JTextArea in another class within the same package.
    Code:
    public class HostAction implements ActionListener {
    static String line;
    public void actionPerformed(ActionEvent e) {
    //monitor the next block of code
    try {
    Process process = Runtime.getRuntime().exec("hostname");
    BufferedReader output = new BufferedReader( new InputStreamReader( process.getInputStream() ) );
    while ( (HostAction.line = output.readLine()) != null )
    {  // start while
    System.out.println(HostAction.line);
    } //end while
    //catch IOException (no input data)
    }catch (IOException x) {
    //if IOException caught, display this
    System.out.println("No Input Data");
    Does anyone have a suggestion on how this can be accomplished?
    Thanks!
    Rusmir.

    // in some other class...
    JTextArea ta = new JTextArea(HostAction.line);The JTextArea should already exist, but if you have a reference to it, just append using the methods provided by JTextArea.
    The above code would create a new JTextArea for every line, which is not likely what you are after.

  • Having trouble in running a unix command and getting the output

    Hi,
    I am trying to run a unix command from within the java code. I am not able to make it work. I am enclosing the code and the error message that I am getting. Any help is highly appreciated.
    import java.io.*;
    public class RunCommand {
        public static void main(String args[]) {
            String s = null;
            try {
                Process p = Runtime.getRuntime().exec("cat UNIX_ASCII_TEXT_FILE | A_UNIX_PROGRAM -d");
                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);
                System.exit(0);
            catch (IOException e) {
                System.out.println("exception happened - here's what I know: ");
                e.printStackTrace();
                System.exit(-1);
    }The error message that I am getting is
    Here is the standard output of the command:
    SLu|%%$$=
    Here is the standard error of the command (if any):
    cat: cannot open |
    cat: cannot open A_UNIX_PROGRAM
    cat: cannot open -dLooks like the cat command is working and not the pipe command and the command after the pipe. But when I run the UNIX command from the command prompt I get the expected result.

    You might read this article and see if its approach works.
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Output from Send Unix command stalled

    after send a unix command to a client the output from
    the command stalls. It seems that the output is buffered
    and that the final buffers are not flushed. This behaviour
    is new since 10.5.5 --
    Anyone know of a way to control the buffer size, when
    they are flushed or to how to run unbuffered ??
    ARD 3.2.2 all around and 10.5.6 all around ARD on a Quad Xenon
    and clients iMac Alum

    well this seems to have been a red herring --
    I had not set the "linebuffering" option on the
    command
    the command was lapply from the radmind suite
    needed to set "-i"
    thanks

  • Run Unix command from windows

    I would like to run a unix command and capture the output by running a java program on a windows 98 machine, this will be ran on a secure intranet. What is the best way to do that. If anyone knows of an example source code that would be great.
    thanks,
    Dean

    Try this. It always works for me.
    import java.io.*;
    public class Exec {
        private BufferedReader out;
        private Process p;
        public Exec(String cmd) throws IOException {
            p = Runtime.getRuntime().exec(cmd);
            out = new BufferedReader(new InputStreamReader(p.getInputStream()));
        public BufferedReader getBufferedReader() {
            return out;
        public void waitFor() throws InterruptedException {
            p.waitFor();
        public static void main(String [] args) throws IOException,
                InterruptedException {
            final Exec p = new Exec("your command goes here.");
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String s = null;
                        while((s = p.getBufferedReader().readLine()) != null) {
                            System.out.println(s);
                    catch(IOException io){}
            }).start();
            p.waitFor();
    }

  • Capturing multiline process output ?

    Hello all. I am writting a few methods that can execute a UNIX command
    or script and then grab standard output. However, when I try to capture
    the output I am only able to get the first line ? Here is a code snippet
    private java.lang.Process shellProcess = null;
    public void RunShellCommand( String command ) throws IOException
      try
        if( command != null )
          String[] kshCommand = { "/bin/ksh", "-c", command };
          /* Use the runtime exec() method to start the command. */
          shellProcess = java.lang.Runtime.getRuntime().exec(kshCommand);
      catch( IOException ioe )
        throw( ioe );
    public String getShellCommandOutput() throws IOException
       String readStr = null;
       if( shellProcess != null )
         try
           /* Create a buffered reader. */
           BufferedReader stdInput = new BufferedReader( new InutStreamReader( shellProcess.getInputStream() ));
           readStr = stdInput.readLine();
         catch( IOException ioe )
           throw( ioe );
       return( readStr );
    }These methods are called from a GUI like this:
    myClass.RunShellCommad( "ls -l" );
    String out;
    while( (out = myClass.getShellCommandOutput()) != null)
      /* Stuff ouput into a JTextArea */
    }Does anyone know why I can only get one line of output. Thanks.

    you r reading the output using this command
    readStr = stdInput.readLine();
    well you r calling stdInput.readline() only once
    do something like this
    while (readStr != null)
    readStr = stdInput.readLine();
    }

  • How to generate a empty file in AL11 using ABAP and unix command

    Hi Experts,
    when load infopackage triggers it will search file from AL11 if file is available it will get loaded successfully.  When there is no file in AL11 error while opening file (orgin A) and the load will fail.  At this level i have to write a abap code using unix command to generate a empty file.
    Is there any way to achieve the above requirement.
    Thanks
    Vara

    Hi,
    If i get your requirement properly then you want to create a blank file if there is no file on the application server so that your infopackage does not fail, am i correct.
    If this is your requirement then this can be easily done if you use process chain to load the file via infopackage. Follow the following steps:
    1. Add a ABAP program before the infopackage and check if the file is present on the server or not. Use a simple ABAP statement OPEN DATASET <FNAME>. Check the SY-SUBRC after this statement if it is not 0 then it means that the file does not exist on the application server.
    2. Once you have established that the file is not present create a flat file using a code similar to the below one
    OPEN DATASET FILENAME FOR OUTPUT IN TEXT MODE
                          MESSAGE D_MSG_TEXT.
    IF SY-SUBRC NE 0.
      WRITE: 'File cannot be opened. Reason:', D_MSG_TEXT.
      EXIT.
    ENDIF.
    * Transferring Data
    LOOP AT INT_table.
      TRANSFER INT_table-field1 TO FILENAME.
    ENDLOOP.
    * Closing the File
    CLOSE DATASET FILENAME.
    3. Add your infopackage step after this ABAP program in your process chain.
    I hope this helps.
    Best Regards,
    Kush Kashyap

  • Calling unix command in Apex Window

    I am working on a small project where in; it would be handy to run an external plsql in oracle database which calls for unix command such as tail -f alert.log or tail -1000 alert.log when a button is pressed in the application.
    I know the client and server aspect and very difficult to forward the server output to Application specially web based but still thought of trying my luck to get some insights from this forum .
    Is this possible in Apex ?
    UK

    Don't see why not. All the building blocks are there (assuming a recent version of the database, and that 1000 is a realistic metric of the data volume):
    1. A script to run the required UN*X commands.
    2. An initial log extract file created manually using the script.
    3. An external table on the log extract file.
    4. An external scheduler job to rerun the log extract script to refresh the log extract.
    5. An APEX page with a report based on the external table, and a button that calls the external job.
    Note that providing relevant information when asking a question is helpful in determining a solution:
    - APEX version
    - DB version and edition
    - Web server architecture (EPG, OHS or APEX listener)
    - Browser(s) used
    - Theme used
    - Templates used

  • "at" UNIX Command in Java Program

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

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

  • Call unix command in sqlplus script

    Hello, I wanna to know how to call a unix command in the sqlplus script.
    For exemple,
    I've a sqlplus script to lauch a oracle report, after the report is generated, I wanne to replace the output file in an other directory.
    So that, I have to call the unix command mv here in the sqlplus script
    How can I do it?**
    I completed my situation:
    I don't have dbms_scheduler untility in my database.
    Thanks a lot for your help
    Edited by: user11930885 on 17 janv. 2010 14:53

    Yes, at the begining, I'll tried the unix shell by calling SQL.
    I've the problem of passing the parameters through.
    It seems to me
    we can use
    Host in the SQLPLUS to run the unix command.
    but I've written it in my sqlplus script, it doesn't work. so I wanna to find an exemple how to use HOST in sqlplus script?
    I would have loved to give you an example..but its not unix on my laptop.
    But what i can tell you is...u should be doing otherway round.
    Not calling Unix commands from SQL but calling SQL's form unix.
    You got shell scripts for that.
    Write a shell script. Login to SQL execute your code.
    exit from sql and then move your file with MV. That's it.
    Do post how far you get after trying this.

  • Unix command in Report Builder

    Is it possible to use UNIX command in Report builder because I am trying to move one file in UNIX directory to some other directory in UNIX also.
    Thanks
    Shishu Paul
    Chandigarh

    Hye, Basically , I have attached this report in Oracle Apps 11.5.10 and wants to output of this, always having specific output id for each report which have been completed in Apps to be move to some specified folder.
    Please provide some guidance.
    Thanks
    Shishu Paul

  • How do run unix command in java

    hi
    All unix command working fine in our java program.
    but i want change user in linux by using java. it's not working.
    "su root" This command onely not working.
    anybody know help me
    This is my ID [email protected]
    This my code
    <% String s = null;
    try{
    Process p = Runtime.getRuntime().exec("su root");
    BufferedReader stdInput = new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new
    InputStreamReader(p.getErrorStream()));
    out.println("Here is the standard output of the command:\n");
    while ((s = stdInput.readLine()) != null)
    out.println(s);
    catch(Exception e) {}
    %>

    I don't have further info to add to your first post, but think your guess seems quite reasonable. I thought of starting a new thread on the same topic, but think this (question) fits in here, too.
    I have Java code (freeware, not opensoure), intended for Unix, which basically provides the graphical interface and relies on an I/O layer (C + shell scripts) to do most of the work. I have access to the C+shell scripts which are opensource. I ported it to Cygwin and want to use it under Windows (there is no Cygwin native Java VM).
    My problem now boils down to " how to run commands under Unix and what differences are there with Windows". What are the variants?
    I have to guess what the program is doing when I get an IOException at some point. E.g.: a call to shell script may be made in a different way as to a compiled exe in Unix?. I found a way to bypass path problems because forward slashes are also accepted and /cygdrive/c construct can be replace by c:/; shell scripts can be compiled into exes using shc and they work; if symbolic links are replaced by duplication of exe files, they work. What will happen in an instance whereby a process runs a shell script dynamically, through a pipe (the shell script is compiled in the Cygwin/win version and receives parameters) in a construct like:
    pipefp = epopen(cmdbuf,"w"); /* (cmbuf is "makehdr par1 par2 ... ") (makehdr was a shell script and is now compiled exe for Cygwin/Windows) */?.
    Thanks.
    LT

  • Problem With UNIX command in ODI Environment.

    A procedure is used in our package which involves moving a file from a folder to another in a UNIX server.
    The procedure uses an OS command - 'os.system' to execute unix command.
    The unix command is a grep command which seems to work fine when executed alone.
    But when this procedure is executed ,it fails.
    The following code raises an error and the procedure fails.:
    if os.system(cmd) <> 0:
    raise "command fails","see agent output for details";
    Whenever we are trying to reverse,we get "file not Found " error.
    We tried to execute the jython code by placing the files in local directories. The same error appears both when the file is in local and when it is in a remote directory.
    This is the error we get:
    org.apache.bsf.BSFException: exception from Jython:
    Traceback (innermost last):
    File "<string>", line 20, in ?
    HeaderCmd failed:: See agent output for details      at org.apache.bsf.engines.jython.JythonEngine.exec(JythonEngine.java:146)
         at com.sunopsis.dwg.codeinterpretor.k.a(k.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.scripting(SnpSessTaskSql.java)      at com.sunopsis.dwg.dbobj.SnpSessTaskSql.execSrcScriptingOrders(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTaskTrt(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSqlS.treatTaskTrt(SnpSessTaskSqlS.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTask(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessStep.treatSessStep(SnpSessStep.java)
         at com.sunopsis.dwg.dbobj.SnpSession.treatSession(SnpSession.java)
         at com.sunopsis.dwg.cmd.DwgCommandSession.treatCommand(DwgCommandSession.java)      at com.sunopsis.dwg.cmd.DwgCommandBase.execute(DwgCommandBase.java)
         at com.sunopsis.dwg.cmd.e.i(e.java)
         at com.sunopsis.dwg.cmd.g.y(g.java)
         at com.sunopsis.dwg.cmd.e.run(e.java)
         at java.lang.Thread.run(Unknown Source)

    Hi,
    The unix command is a grep command which seems to work fine when executed alone. :-
    I guess you executed this from your Unix server , so it work fines.
    And when you are trying to execute outside from this (using ODI) , its failing , right ?
    Can you please check the permission settings for that script file (sh).
    Please try by giveing the full permission (specifically execution permission) for all users connecting from other machines.
    This can be one of the reason for the failure .
    please let me know if this is not working
    Regards,
    Rathish

Maybe you are looking for

  • Month Sorting at Universe Level

    Hi All, We have created a Universe on BEx query to develope an BO Explorer. We are having Sorting problem with Fiscal Period values, which is in Character type. So need some clarification on below queries.. Q: Can we change the Fiscal Period datatype

  • WLC-2106 and multiple interfaces on the same network

    Hi there, I recently created a TAC request to the Cisco support regarding our WLC-2106, but they could not help me. Basically I just learned that you can create new interfaces for the wireless LAN controller and then dedicate them to a given wireless

  • Custom Error Message for Validation.....

    Here is my Validation: I want the error which is grown from what is wrong on the page to display after the validation. the GUI for validation will not let me leave the Validation ERROR box empty...just not sure how to get around this. DECLARE isValid

  • Cannot update Extension Manager 6.0.4

    Update Failed Updates cold not be applied Extension Manager 6.0.4 Update Installation failed. Error Code: U44M1P7 David Pelkey [email address removed by host]

  • Creating SOLMAN suppport message from EP 7.0

    Hi all, We are in the support phase of a project.The support is handled by the solution manager.The suport messages are raised in SOLMAN.From ECC users are able to create a solman message(standard functionality ).Client wants such type of functionali