Need Help on Executing Shell Scripts through PL-SLQ

Hi All,
I am trying to execute a shell script from PL-SQL but I am not getting it right .
the code i used is as follows
----JAVA CLASS ---
CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "Host" AS
import java.io.*;
public class Host {
public static void executeCommand(String command) {
try {
String[] finalCommand;
if (isWindows()) {
finalCommand = new String[4];
// Use the appropriate path for your windows version.
finalCommand[0] = "C:\\windows\\system32\\cmd.exe"; // Windows XP/2003
//finalCommand[0] = "C:\\winnt\\system32\\cmd.exe"; // Windows NT/2000
finalCommand[1] = "/y";
finalCommand[2] = "/c";
finalCommand[3] = command;
else {
finalCommand = new String[3];
finalCommand[0] = "/bin/sh";
finalCommand[1] = "-c";
finalCommand[2] = command;
final Process pr = Runtime.getRuntime().exec(finalCommand);
pr.waitFor();
new Thread(new Runnable(){
public void run() {
BufferedReader br_in = null;
try {
br_in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String buff = null;
while ((buff = br_in.readLine()) != null) {
System.out.println("Process out :" + buff);
try {Thread.sleep(100); } catch(Exception e) {}
br_in.close();
catch (IOException ioe) {
System.out.println("Exception caught printing process output.");
ioe.printStackTrace();
finally {
try {
br_in.close();
} catch (Exception ex) {}
}).start();
new Thread(new Runnable(){
public void run() {
BufferedReader br_err = null;
try {
br_err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String buff = null;
while ((buff = br_err.readLine()) != null) {
System.out.println("Process err :" + buff);
try {Thread.sleep(100); } catch(Exception e) {}
br_err.close();
catch (IOException ioe) {
System.out.println("Exception caught printing process error.");
ioe.printStackTrace();
finally {
try {
br_err.close();
} catch (Exception ex) {}
}).start();
catch (Exception ex) {
System.out.println(ex.getLocalizedMessage());
public static boolean isWindows() {
if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1)
return true;
else
return false;
---PROCEDURE TO BE EXECUTED WHICH USES THE ABOVE JAVA CLASS IS ----
CREATE OR REPLACE PROCEDURE Host_Command (p_command IN VARCHAR2)
AS LANGUAGE JAVA
NAME 'Host.executeCommand (java.lang.String)';
--- THE PERMISSIONS ---
call dbms_java.grant_permission('SYSTEM', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'read ,write, execute, delete');
call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
--- THE SHELL SCRIPT IS -----
#!/bin/sh
# This script removes the carriage returns from the Files having .DAT1 extensions in the /test/ Directory
# and the sends the single line stream to the new file with the use of 'gawk' command
# so finaly the files with same primary name but different secondary name are created
# e.g. file 'test.DAT1' is onverted to 'test.DAT'
# LOOP on /test/ DIRECTORY FOR SEARCHING FILES HAVING EXTENSION *.DAT1
for file_name in `ls /test/*.DAT1`
do
new_file_name=`echo $file_name | sed 's/DAT1/DAT/'`
# SEND THE CONTAINTS OF SELECTED FILE IN LOOP AS A CONTINUOUS STREAM TO NEW FILE NAME USING 'gawk' COMMAND
gawk 'BEGIN { ORS = "''" } { print $0 }' $file_name >> $new_file_name
# ABOVE LINE WILL CREATE A NEW FILE WITH SAME PRIMARY NAME BUT .DAT AS SECONDARY NAME(EXTENSION)
# REMOVE THE PRIOR FILE(s) AFTER SUCCESSFUL CALL TO 'gawk'
# $? returns 0 if the call to gawk command is succesfull
if test 0 = "$?"
     then
     rm -f $file_name
fi
done
# END LOOP ON /test/ DIRECTORY
---THE CALL TO THE PROCEDURE --
SQL>CALL DBMS_JAVA.SET_OUTPUT(1000000);
SQL>SET SERVEROUTPUT ON SIZE 1000000
SQL>exec host('/root/sh ecs_script.sh'); -----------------------------------------------1
now, the statement 1 is the path of the Shell Script ecs_script.sh
which uses gawk command and does some operations on some file..
but when i give the call in Statement 1 its giving error like
/bin/sh is not a directory
so i am not getting wHat should I do so that my script "ecs_script.sh" gets executed..
Please Help.

@ Bhagat & Michaels
Dear Friends,
I changed my shell name as per ur suggestions
and recompiled the Java class source with
finalCommand[0] = "/bin/bash"; instead of finalCommand[0] = "/bin/sh";
and then recompiled the host procedure
executed the host procedure as per ur suggestion as follows (with out put)
SQL> exec host('/bin/bash ecs_script.sh')
PL/SQL procedure successfully completed.
bt, bt, bt, it still did not do any operations defined in the "ecs_script.sh"
in fact the script did nt executed.......
pls help , I am loosing my time..
regards.

Similar Messages

  • Executing shell script through PL/SQL

    Hi,
    I need some help regarding execution of shell script through Oracle PL/SQL.
    I have a shell script present in /abc/xyz folder with name search.sh , Through a PL/SQL procedure I am creating a file to store the report data.
    I want to execute /abc/xyz/search.sh from the PL/SQL procedure to delete all files created before 3 mins .
    1.     At first I took Java route and got following permissions granted for RECON user.
    GRANT USER SYS java.io.FilePermission <<ALL FILES>> execute ENABLED 351
    GRANT USER SYS java.lang.RuntimePermission readFileDescriptor * ENABLED 350
    GRANT USER SYS java.lang.RuntimePermission writeFileDescriptor * ENABLED 349
    2.     Then I created a simple java class for execution of OS command as below
    CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "OSCommand" AS
    import java.io.*;
    import java.util.*;
    public class OSCommand{
    public static String Run(String Command){
    try{
    Process proc = Runtime.getRuntime().exec(Command);
    int ext=proc.waitFor();
    return ("0");
    catch (Exception e){
    System.out.println("Error running command: " + Command +
    "\n" + e.getMessage());
    return(e.getMessage());
    3.     And a wrapper function as below to use this class
    create or replace
    FUNCTION OSCommand_Run(Command IN STRING)
    RETURN VARCHAR2 IS
    LANGUAGE JAVA
    NAME 'OSCommand.Run(java.lang.String) return int';
    4.     In my PL/SQL proceedure I am using following code to execute the command
    v_Return := OSCommand_Run('/abc/xyz/search.sh');
    to execute the shell script.
    Proceedure executes without any error and generates a new csv file with report data , however shell script does not get executed and hence all csv files created earlier remain as it is in the folder.
    Please help.

    Sven W. wrote:
    What happens if you remove the catch exception block from your java command?
    I asume you still might have a permission issue. But it could be hidden from you, because of the exception is catched and printed into nirvana.Executed the wrapper function OSCOMMAND_RUN as below
    DECLARE
    v_Return VARCHAR2(2000);
    BEGIN
    v_Return := OSCOMMAND_RUN('/recon/html/invoice/search.sh' );
    DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
    END;
    And following is the result
    v_Return = 0
    Process exited.
    In case of exception it would had printed the exception.
    One more thing I noticed, even though I have taken following permissions
    GRANT     RECON     SYS     java.io.FilePermission     /abc/*     execute     ENABLED     347
    GRANT     RECON     SYS     java.io.FilePermission     /abc/xyz/*     execute     ENABLED     351
    GRANT     RECON     SYS     java.io.FilePermission     <<ALL FILES>>      execute     ENABLED     352
    GRANT     RECON     SYS     java.lang.RuntimePermission     readFileDescriptor     *     ENABLED     350
    GRANT     RECON     SYS     java.lang.RuntimePermission     writeFileDescriptor     *     ENABLED     349
    When I create a new search.sh in /abc dir I get following error
    v_Return = the Permission (java.io.FilePermission /abc/search.sh execute) has not been granted to RECON. The PL/SQL to grant this is dbms_java.grant_permission( 'RECON', 'SYS:java.io.FilePermission', '/abc/search.sh', 'execute' )
    Edited by: 960702 on Sep 25, 2012 10:34 AM

  • Execute Shell Script through Demantra Workflow

    Hi All ,
    Can we execute shell script from Demantra Workflow ?
    If yes where should we place the shell script file and wat should be the commandline command in the step .
    We have the Demantra installed on a windows server and the workflow manager is on a linux server .
    the batch file on the windows server can be executed through the secure shell from the linux server .
    I am trying to achieve the same through thr demantra workflow
    Appreciate any input on the same .
    Thanks and regards
    Suzy

    Hi,
    Shell script is not supported till Demantra 7.2.0.2 WF.
    I have checked with Oracle team also and reply I got below for your reference:
    QUESTION
    *=========*
    As per your details, shall we conclude like this:
    *"only *.bat and *.exe files can be used in workflow. Demantra standard functionality doe*
    *s not support shell script in workflow"*
    ANSWER
    *=======*
    Hi ,
    The Demantra standard functionality 7.2.0.2 does support shell script in workflow.
    Thanks,
    Asya
    Please review the note#468071.1-Unable to Run EBS Workflows that Call EngineManager.exe in
    You will find this note is referring to the Enhancement Request Bug 6644455-- ANALYTICAL ENGINE
    NOT AVAILABLE ON UNIX/LINUX
    But the enhancement bug exist and I hope it is fixed in Demantra 7.3.
    Tks
    MJ

  • Executing Shell Scripts through PL-SQL

    Hi All,
    I am trying to execute a shell script from PL-SQL but I am not getting it right .
    the code i used is as follows
    ----JAVA CLASS ---
    CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "Host" AS
    import java.io.*;
    public class Host {
    public static void executeCommand(String command) {
    try {
    String[] finalCommand;
    if (isWindows()) {
    finalCommand = new String[4];
    // Use the appropriate path for your windows version.
    finalCommand[0] = "C:\\windows\\system32\\cmd.exe"; // Windows XP/2003
    //finalCommand[0] = "C:\\winnt\\system32\\cmd.exe"; // Windows NT/2000
    finalCommand[1] = "/y";
    finalCommand[2] = "/c";
    finalCommand[3] = command;
    else {
    finalCommand = new String[3];
    finalCommand[0] = "/bin/sh";
    finalCommand[1] = "-c";
    finalCommand[2] = command;
    final Process pr = Runtime.getRuntime().exec(finalCommand);
    pr.waitFor();
    new Thread(new Runnable(){
    public void run() {
    BufferedReader br_in = null;
    try {
    br_in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String buff = null;
    while ((buff = br_in.readLine()) != null) {
    System.out.println("Process out :" + buff);
    try {Thread.sleep(100); } catch(Exception e) {}
    br_in.close();
    catch (IOException ioe) {
    System.out.println("Exception caught printing process output.");
    ioe.printStackTrace();
    finally {
    try {
    br_in.close();
    } catch (Exception ex) {}
    }).start();
    new Thread(new Runnable(){
    public void run() {
    BufferedReader br_err = null;
    try {
    br_err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
    String buff = null;
    while ((buff = br_err.readLine()) != null) {
    System.out.println("Process err :" + buff);
    try {Thread.sleep(100); } catch(Exception e) {}
    br_err.close();
    catch (IOException ioe) {
    System.out.println("Exception caught printing process error.");
    ioe.printStackTrace();
    finally {
    try {
    br_err.close();
    } catch (Exception ex) {}
    }).start();
    catch (Exception ex) {
    System.out.println(ex.getLocalizedMessage());
    public static boolean isWindows() {
    if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1)
    return true;
    else
    return false;
    ---PROCEDURE TO BE EXECUTED WHICH USES THE ABOVE JAVA CLASS IS ----
    CREATE OR REPLACE PROCEDURE Host_Command (p_command IN VARCHAR2)
    AS LANGUAGE JAVA
    NAME 'Host.executeCommand (java.lang.String)';
    --- THE PERMISSIONS ---
    call dbms_java.grant_permission('SYSTEM', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'read ,write, execute, delete');
    call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
    call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
    --- THE SHELL SCRIPT IS -----
    #!/bin/sh
    # This script removes the carriage returns from the Files having .DAT1 extensions in the /test/ Directory
    # and the sends the single line stream to the new file with the use of 'gawk' command
    # so finaly the files with same primary name but different secondary name are created
    # e.g. file 'test.DAT1' is onverted to 'test.DAT'
    # LOOP on /test/ DIRECTORY FOR SEARCHING FILES HAVING EXTENSION *.DAT1
    for file_name in `ls /test/*.DAT1`
    do
    new_file_name=`echo $file_name | sed 's/DAT1/DAT/'`
    # SEND THE CONTAINTS OF SELECTED FILE IN LOOP AS A CONTINUOUS STREAM TO NEW FILE NAME USING 'gawk' COMMAND
    gawk 'BEGIN { ORS = "''" } { print $0 }' $file_name >> $new_file_name
    # ABOVE LINE WILL CREATE A NEW FILE WITH SAME PRIMARY NAME BUT .DAT AS SECONDARY NAME(EXTENSION)
    # REMOVE THE PRIOR FILE(s) AFTER SUCCESSFUL CALL TO 'gawk'
    # $? returns 0 if the call to gawk command is succesfull
    if test 0 = "$?"
         then
         rm -f $file_name
    fi
    done
    # END LOOP ON /test/ DIRECTORY
    ---THE CALL TO THE PROCEDURE --
    SQL>CALL DBMS_JAVA.SET_OUTPUT(1000000);
    SQL>SET SERVEROUTPUT ON SIZE 1000000
    SQL>exec host('/root/sh ecs_script.sh'); -----------------------------------------------1
    now, the statement 1 is the path of the Shell Script ecs_script.sh
    which uses gawk command and does some operations on some file..
    but when i give the call in Statement 1 its giving error like
    /bin/sh is not a directory
    so i am not getting wHat should I do so that my script "ecs_script.sh" gets executed..
    Please Help.

    The Java proc says:
    > finalCommand[0] = "/bin/sh";
    finalCommand[1] = "-c";
    finalCommand[2] = command;
    You call it as follows:
    SQL>exec host('/root/sh ecs_script.sh');
    The final command will be:
    /bin/sh -c /root/sh ecs_script.sh
    Is this what you intended?

  • Need Help Writing a Shell Script

    Basically I'm writing a script that opens TextEdit so I can open it from the Terminal. I also want it to run in the background so I can continue using the Terminal without having to quit TextEdit first. So far I've figured out two ways of doing this, and neither one does exactly what I want it to do. Here's the first one I tried:
    /Applications/TextEdit.app/Contents/MacOS/TextEdit $@ &
    The problem with this is that if TextEdit is already running, it opens a new instance of it to open the files, and it doesn't bring the app into focus when I run it. So I decided to try this:
    open -a "TextEdit" $@ &
    This way all files open in the same instance of TextEdit and it brings the app to the front, but it won't let me save anything I don't have write privileges for, even if I run it with sudo. I Googled it and apparently what happens is it runs "open" as root but runs the actual application that I'm opening as the current user.
    So basically what I need to know is if there's a way of doing this that will congregate all files into the same instance of TextEdit and bring the app to the front when I launch it, but still let me run it as root with sudo. If not, is there at least a way to check if TextEdit is running and throw an error if it is?

    #!/usr/bin/env bash
    if ps ax | grep '[T]extEdit'; then
    echo "TextEdit is already running!"
    else
    /Applications/TextEdit.app/Contents/MacOS/TextEdit &
    fi
    open -a TextEdit "$@"
    osascript -e 'tell application "TextEdit" to activate'
    Example:
    your.script "text file.txt"
    NOTE 1: When posting code to this forum, enclose your code in
    ...your code goes here...
    This will make sure that all your indentation and other meta-characters that might get interpreted by the forum code will be left alone.
    NOTE 2: The $@ will ONLY preserve quoted strings as a single argument if it is specified as "$@". That is to say it MUST be inside a pair fo double-quotes. Otherwise it is the same as $* The missing ".." are what messed up your ability to treat a file with space as a single argument. ALSO NOTE, I specified the file on the command line inside quotes (could be single or double), or you could use  if you desire.
    NOTE 2 and a half:
    If you DO NOT want to put quotes around the space filled filename when invoking your script, you could change your "$@" to "$*"
    open -a TextEdit "$*"
    The difference is that using "$@" will allow specifying several filenames on the command line and TextEdit will open all of them at once. The use of "$*" means you can only open 1 file per use of your script. Not a big deal, but I figured you should know the options available to you.
    NOTE 3: I've simplified your script.
    I do not know why you decided that if you are root you wanted to use sudo, since sudo gives normal users root privileges, and root already has root privileges.
    Actually based on earlier exchanges, I would have thought that you wanted to start TextEdit using sudo, unless it was already running:
    sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit &
    so that you had root privileges allowing you to write files in places you were normally not allowed. Then again, maybe I was reading the earlier posting wrong (won't be the first time ).
    NOTE 4: The use of
    if [ "$textedit" > /dev/null ]; then
    is just plain wierd This translates to the command:
    test "$textedit" >/dev/null
    which redirects standard output into /dev/null, so the actually command looks like
    test "$textedit"
    which will essentially return TRUE if $textedit has a string in it, and FALSE if $textedit is empty.
    I decided to just use the completion status of the grep command as a way to decide if TextEdit was running on not.
    NOTE 5: I simplified the ps|grep|grep command with a trick I learned several years ago. The '[T]extEdit' regular expression exactly matchs TextEdit, except that it DOES NOT match a ps line that has '[T]extEdit'. So I can get rid of one grep command because it will never match the grep command in the ps output.
    NOTE 6: I moved the open and osascript commands outside the if structure, as I assumed you wanted osascript to bring TextEdit to the foreground regardless of whether it was already running or not, and the open command was identical for both halfs of the if structure. If this is a bad assumption, feel free do put it back inside the if structure.
    Message was edited by: BobHarris

  • Need help on Executing this Script to update LyncDatabase remotely

    Hi All,
             I have some problem with executing the below script (to update the LyncDB post CU4 patched on Lync Servers) remotely, but it works fine Locally(from any Lync FE machine),
    Script: Install-CsDatabase -Update -ConfiguredDatabases -SqlServerFqdn "LyncDB.Julie.local" -UseDefaultSqlPaths
    When executing locally from any Lync FE Machine(LyncFE.julie.local), its working fine "Piece of Output for your reference"
    Output:
    PS C:\Users\julie> 
    Install-CsDatabase -Update -ConfiguredDatabases -SqlServerFqdn "LyncDB.Julie.local" -UseDefaultSqlPaths
    ****Creating DbSetupInstance for 'Microsoft.Rtc.Common.Data.BlobStore'****
    Trying to connect to Sql Server LyncDB.Julie.local. using windows authentication...
    Sql version: Major: 11, Minor: 0, Build 3128.
    Sql version is acceptable.
    Checking state for database rtcxds. it use to go like this for few pages to update all 06 database
    Remote Script:
    $sessionoption=new-pssessionoption -SkipRevocationCheck
    $password=ConvertTo-SecureString -String "*******" -AsPlainText -Force
    $credential=New-Object System.Management.Automation.PSCredential("******", $password)
    $session=New-pssession -ComputerName "LyncFE.julie.local" -port 5985 -Credential $credential -Authentication
    Negotiate -SessionOption $sessionoption
    Try{
    $cmd=invoke-command -session $session -scriptblock{
    Install-CsDatabase -Update -ConfiguredDatabases -SqlServerFqdn "LyncDB.Julie.local" -UseDefaultSqlPaths
    Write-Host $cmd
    Remove-PSSession -Session $Session;
    Catch
      $RetVal = "Error23: " + $error[0].Exception.toString()
    $cmd
    Error:
    Output:
    WARNING: Install-CsDatabase failed.
    WARNING: Detailed results can be found at "C:\Users\Julie\AppData\Local\Temp\Install-CsDatabase-52517af7-39ea-482e-8ba6-166a15cf8
    4d2.html".
    Command setup failed: Active Directory error "-2147016672" occurred while searching for domain
    controllers in domain 
    "ad.*****.com": "An operations error occurred.
        + CategoryInfo          : InvalidOperation: (:) [Install-CsDatabase],
    ADTransientException
        + FullyQualifiedErrorId : BeginProcessingFailed,Microsoft.Rtc.Management.Deployment.InstallDatabaseCmdlet
        + PSComputerName        : LyncDB.Julie.local.com

    I tried both the Option, both still I'm getting the same error like the below,
    Error:
    Output:
    WARNING: Install-CsDatabase failed.
    WARNING: Detailed results can be found at
    "C:\Users\Julie\AppData\Local\Temp\Install-CsDatabase-52517af7-39ea-482e-8ba6-166a15cf8
    4d2.html".
    Command setup failed: Active Directory error
    "-2147016672" occurred while searching for domain controllers in domain 
    "ad.*****.com": "An operations error occurred.
        + CategoryInfo    
         : InvalidOperation: (:) [Install-CsDatabase], ADTransientException
        + FullyQualifiedErrorId : BeginProcessingFailed,Microsoft.Rtc.Management.Deployment.InstallDatabaseCmdlet
        + PSComputerName    
       : LyncDB.Julie.local.com

  • How we can call or execute a SHELL script through Oracle forms or Reports

    How we can call or execute a SHELL script through Oracle forms or Reports.Its urgent.......

    Use HOST command.

  • ABAP program to execute shell script !

    Hi Friends,
    I have created some shell scripts and need to be executed through ABAP prog in order to automate some process. can any one tell me how to execute these scripts through ABAP program? i know that we have to setup those scripts through SM69 but i dont have clear idea about this.can some one tell me step by step how to do this. ur help will be awarded in terms of points.
    Thanks

    Define the scripts as commands in SM69. Test them in SM69/SM49 to see if they work.
    Next, go to SE37, run FM SXPG_COMMAND_EXECUTE, and specify your command there. Does it work?
    If yes, you can just code a 'CALL FUNCTION' to this FM in your ABAP program, and you are ready to invoke your script from your ABAP.
    For  a list of functions that work with commands (defined in SM69), do a drop-down on SXPG_COMMAND* in SE37.
    A sample code may look like this
    concatenate zsys_id z_infile z_extfile into parm
        separated by space.
    *C_FTP_COMMAND is a script defined in SM49
        CALL FUNCTION 'SXPG_COMMAND_EXECUTE'
          EXPORTING
            COMMANDNAME                   = C_FTP_COMMAND
            ADDITIONAL_PARAMETERS         = parm
            OPERATINGSYSTEM               = SY-OPSYS
          TABLES
            EXEC_PROTOCOL                 = PROT
          EXCEPTIONS
            NO_PERMISSION                 = 1
            COMMAND_NOT_FOUND             = 2
            PARAMETERS_TOO_LONG           = 3
            SECURITY_RISK                 = 4
            WRONG_CHECK_CALL_INTERFACE    = 5
            PROGRAM_START_ERROR           = 6
            PROGRAM_TERMINATION_ERROR     = 7
            X_ERROR                       = 8
            PARAMETER_EXPECTED            = 9
            TOO_MANY_PARAMETERS           = 10
            ILLEGAL_COMMAND               = 11
            WRONG_ASYNCHRONOUS_PARAMETERS = 12
            CANT_ENQ_TBTCO_ENTRY          = 13
            JOBCOUNT_GENERATION_ERROR     = 14
            OTHERS                        = 15.
        IF SY-SUBRC <> 0.
          MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                  WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
        else.
          write: /, 'FTP Function module executed with no errors.'.
        ENDIF.

  • Running Shell scripts through JAva

    Hi,
    I tried to execute a Shell script through a Java program.
    The code I used is as below:
    import java.lang.*;
    import java.io.*;
    public class sys {
    public static void main(String[] args) {
    Runtime rt = Runtime.getRuntime();
    String[] callAndArgs = { "chgpasswd" };
    try {
    Process child = rt.exec(callAndArgs);
    child.waitFor();
    System.out.println("Process exit code is: " + child.exitValue());
    catch(IOException e) {
    System.err.println( "IOException starting process!");
    catch(InterruptedException e) {
    System.err.println( "Interrupted waiting for process!");
    The "chgpasswd" shell script calls the "passwd" command of Unix.
    It threw out an IO exception.
    Then I gave the parameter as "./chgpasswd". It now gave an exit value of 255.
    The "chgpasswd" script exists in the same directory as the .class file.
    I checkd up the exit code reference...it says exit value of 255 could mean as exit code out of range........an exit code > 255....which unfortunately has no documentation, I guess.
    Can you help ?

    This is on a Unix platform, correct? Assuming so...
    If I remember correctly, exit codes can be greater than 255. To get the real exit code equates to something like: exitcode & 512 to obtain the real exit code.
    Make sure "chgpasswd" shell script has the execute permissions set. Additionally, make sure that the first line of the script (the magic line) has the appropriate shell/interpreter to execute specified. For example, if "chgpasswd" were a Bourne (sh) script, the first like would be:
    #!/bin/shFor perl, it may be something like:
    #!/usr/bin/perlIt needs to be the absolute path to the shell/interpreter is the point.

  • Error to execute the script through command prompt

    I tried to execute the script through command prompt. I got some following error. Could you please advice me how to rectify this.
    cscript D:\JS\Test.js
    Microsoft (R) Windows Script Host Version 5.6
    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
    D:\JS\Test.js(1, 1) Microsoft JScript runtime error: 'app' is undefined.
    Thanks,
    Prabudass

    I haven't use CS for quite some time and file associations may not work with the command prompt.
    You can try using Windows Explorer to browse to a .js file then right click on that file. From the popup menu choose Open With. Even if you see Photoshop in the file list choose Browse at the bottom. Browse to Photoshop and make sure to check 'Always use selected program...'
    If that doesn't work you will need to create an action that runs your script and make a droplet from that action. You can then use the droplet in the command prompt. You may also need to create a 'dummy' image file to launch the droplet with if you script doesn't require an open document at startup. See http://www.ps-scripts.com/bb/viewtopic.php?t=967

  • Executing shell script using OSLinetoken fetchlet

    Hii,
    I do have a requirement. I need to use a shell script in the OSLineToken fetchlet. In response metric i will be checking whether the directory exists or not on the server. In order to check the existence of the directory, i have created a shell script. But how can i relate its result with the Response metric? The shell script is as follows:
    Shell Script:
    if test -d $1 ; then
    echo "DIR exist"
    else
    echo "false"
    fi
    The Response metric for the same will be:
    <QueryDescriptor FETCHLET_ID="OSLineToken">
         <Property NAME="command" SCOPE="GLOBAL">
              sh {dir_name where the shell script is uploaded}/{shell script file name} {dir_name_parameter} </Property>
         <Property NAME="startsWith" SCOPE="GLOBAL">em_result=</Property>
         <Property NAME="delimiter" SCOPE="GLOBAL">|</Property>
    </QueryDescriptor>
    Please suggest what is the use of em_result here?
    once the existence of the directory is checked, if it up then i need to call another shell script in order concatenate the contents of all the files with extension .log(this will be the parameter of shell script). Get the output from shell script and display it into custom management plug-in. As i am using cat *.log>>consolidatefile command to concatenate the data, i need to read consolidatefile file from the server and return this concatenated file data into plug-in. Again, how can i read the content of consolidatefile file in EMF? I will be creating another matric for this purpose say "read_content". the querydesciptor of the same will be as follows:
    <QueryDescriptor FETCHLET_ID="OSLineToken">
         <Property NAME="command" SCOPE="GLOBAL">
              sh {dir_name where the shell script is uploaded}/{shell script file name} {dir_name_parameter} {extension of the files to concatenated} </Property>
         <Property NAME="startsWith" SCOPE="GLOBAL">em_result=</Property>
         <Property NAME="delimiter" SCOPE="GLOBAL">|</Property>
    </QueryDescriptor>
    I am not sure which all properties to be used in this case..I have seen multiple sample files some of them uses perbin, scriptsdir but some of them does not..The related pdf also does not say anyhting about such kind of properties. Please suggest.
    I hope the explaination of the problem is not so cumbersome. Please let me know if you have any query to understand.
    Thanks,
    AS

    If you notice, localScriptsDir is a directory within scriptsDir. If you package your plug-in up and deploy it through the UI, any scripts you create will go into %scriptsDir%/emx/<target_type>. So localScriptsDir just specifies that directory for you. You don't need it but then in the command paramater you'll have something like:
    sh %scriptsDir%/emx/yourtargettype/yourscript...
    So whether you specify it in the command or another property (localScriptsDir) doesn't really matter.
    You can create your own properties in the QueryDescriptor. Just make sure you have the correct scope specified and it should be fine (options for scope are described in the Enterprise Manager DTD section of the Extensibility Guide).
    Metric collection isn't really meant for dynamic specification of input parameters. I can think of a few solutions:
    1) Create a target instance for each log directory. When you create the instance, the directory is specified. If you need to monitor a different directory, you can just create another instance. Upside is that it's flexible and scalable, and also, when you get an error you'll know exactly which directory it is based on which instance throws the error. Downside is that you have to have a separate instance for each directory.
    2) If the log directories are well known and finite (and won't change names), hardcode them into the target metadata. Have a different metric collect for each log directory, so you'll have as many metrics as log directories you want to monitor. Even if the names of the directories are different, you can use instance properties to map them, so if you know there will always be 5 log directories you want to monitor, you can have 5 instance properties to map the names into the metrics, although this won't work if you don't have the same number each time. Upside is that there is only a single target instance. Downside is that it's not as flexible.
    3) Use a job rather than a target type to find out this information. You could create a new job type which scans the logs for information and have the directory as an input parameter to the job. You could have this job on a repeating schedule to duplicate the effect you are trying to get out of creating a target type. The upside is that you can start the job whenever you want from the UI and specify exactly which directory whenever you run it. The downside is that the job system is centered on the OMS rather than the agent, so every time it runs it will have to contact the agent to do the work. In the case of the target type, the agent acts autonomously without contact from the OMS.
    There are probably other options, but these are the quick ones off the top of my head.
    Chris

  • Finding path to source executed shell script

    Hello,
    I have shell script A which executes shell script B. The scripts A and B reside in the same directory.
    Following requirements:
    Scripts A and B need to be source executed.
    The directory where A and B resides should be anywhere.
    The present working directory from where A is executed should be anywhere.
    The directory of scripts A and B may not be defined in $PATH.
    The current shell could be any Bourne or Korn shell, Linux or Unix.
    Problem:
    Let's assume scripts A and B are installed in "/custom".
    The users working directory is /home/oracle and he executes "source /custom/A".
    If script A executes "source ./B", the result would be "source /home/oracle/B", which will fail.
    Possible Solution:
    Since script A is being sourced, $0 will always be the name of the current shell and not the name and path to script A.
    I have not found a universal solution to locate the absolute path of a shell script that is being source executed.
    So I was wondering about defining a variable in script A. e.g. SCRIPT_HOME=./custom. When script A executes "source $SCRIPT_HOME/B" it will work, but then script A needs to be customized by the user.
    I could write a script C that edits script A to search and edit the SCRIPT_HOME variable. For this to work I will have to verify that script C is not source executed, and that script A is in the same directory as C based on $0. This is not a problem..
    The question however is whether I need to create script C, or could simply execute script A with -config argument to edit itself and exit. I would prefer the later case and from what I understand, Unix and Linux do not lock files by default and this should be possible.
    Any comments or suggestions please?
    Thanks!
    Edited by: Dude on Apr 5, 2011 3:59 AM

    The $_ solution is actually very simple:
    $ cat thatsme
    mypath=$(dirname $_)
    echo "$mypath/B"
    $ source /home/oracle/thatsme
    /home/oracle/BI do not need the absolute path of script A. The relative path from my current directory will do as well.
    But, it does not work with an alias:
    $ alias thatsme='source /home/oracle/thatsme'
    $ thatsme
    ./B

  • Running Unix Shell scripts through Java

    How to run Unix shell scripts through Java program ?

    Use:
    Process p = Runtime.getRuntime().exec("sh script.sh");Then you can use:
    p.getOutputStream and read the output of your program.

  • Upgraded ROX filer not executing shell scripts

    Hi all,
    I run ICEWM+ROX filer as my lite desktop but after a recent upgrade, ROX does not execute shell scripts on mouse click. It appears that filetype detection has changed so that all scripts are shown with the shellscript icon, whereas before those without a .sh extension where shown with the kde type "cogwheel".
    Any tips much appreciated.
    My thanks in advance!

    I've found a lot of things I don't like about the latest ROX upgrade... too much caching nowadays in my  opinion.

  • Running a shell script through java

    Hi all,
    I have a simple question here.
    How can I run a shell script through java and put the text output into a string.
    I'd be very grateful if you could show me sample code...
    Have a great day,
    Pesho

    Runtime.exec()
    There are plenty of examples. Read the following before continuing, however, as it will save alot of headaches:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

Maybe you are looking for

  • The Application was unable to start correctly (0xc0000005)

    Dear Support, This is to inform you that we are using Windows Server 2008 R2 Enterprises Edition (x64) & suddently it is showing the message "The Application was unable to start correctly (0xc0000005. Click OK to close the application."   I have alre

  • How to add a new parameter to a forwarded request?

    Hi all, I have a RequestDispatcher that forwards my request into a servlet. However, if some processing error happens I would like to include another parameter (an error message) in my request being forwarded. Oh, yes, I don't want it to be via GET,

  • How to logon the j2ee engine with logon group

    hi everyone, I have installed an HA j2ee engine system with MSCS. But i donot know how to logon the DI&CI with logon group like ABAP system Thanks very much Regards Peter

  • Need help with my Muv

    Help! just got a Muvo2 and i've set everything up and transferred music onto player. That was fine, i transferred about 20 tracks, anyway, transferred another 4 or so and lost the other lot..where have they gone? Should i be doing something after tra

  • Email problem on Lumia 800

    My phone sends and receives email but it doesn't seem able to retain them even for today, never mind a week! I get an email notification, go to emails and read the message(s). Next time I get email, the earlier messages might still be there but most