To run set commands within procedures
Hi,
I've even tried to run this -
execute immediate 'set serveroutput on';
within the procedure but I did not succeed in it. Actually, how about the way for running anything like this?
Thks & Rgds,
HuaMin
Dear Arun,
DBMS_OUTOUT.enable(10000)Above statement sets the buffer size. It does not sets server output on.
See the example:
"afiedt.buf" 5 lines, 73 characters
1 BEGIN
2 DBMS_OUTPUT.ENABLE(10000);
3 DBMS_OUTPUT.PUT_LINE('Hello');
4* END;
SQL>/
PL/SQL procedure successfully completed.
SQL>set serveroutput on
SQL>/
Hello
Hello
PL/SQL procedure successfully completed.
SQL>set serveroutput off
SQL>/
PL/SQL procedure successfully completed.Regards
Similar Messages
-
Unable to run Groovy scripts within procedure
Hi all,
We are managing to automate objects promotion to PROD environment using Groovy. The thing is that we are able to run the script in the Groovy tool successfully, but we are not able to run the same script within a procedure in ODI. The version that we are using is 11.1.1.6.5.
Do you know if this needs further configuration? Does it needs any updgrade?
Below, the script we are currently using, it´s just to create a new physical and logical architecture on the topology tab and write an entry on the context to link logical to physical. Any help would be highly appreciated. Thanks.
Fernando.
import oracle.odi.core.persistence.transaction.support.DefaultTransactionDefinition;
import oracle.odi.domain.util.ObfuscatedString;
import oracle.odi.domain.model.OdiModel;
import oracle.odi.domain.topology.OdiLogicalSchema;
import oracle.odi.domain.topology.OdiPhysicalSchema;
import oracle.odi.domain.topology.OdiDataServer;
import oracle.odi.domain.topology.OdiContext;
import oracle.odi.domain.topology.OdiTechnology;
import oracle.odi.domain.topology.OdiContextualSchemaMapping;
import oracle.odi.domain.topology.AbstractOdiDataServer;
import oracle.odi.domain.topology.finder.IOdiContextFinder;
import oracle.odi.domain.topology.finder.IOdiTechnologyFinder;
def createLogicalSchema(contextCode, techCode, schName, dataserverName, userName, password, url, driver, schema) {
txnDef = new DefaultTransactionDefinition();
tm = odiInstance.getTransactionManager()
txnStatus = tm.getTransaction(txnDef)
contextFinder = (IOdiContextFinder) odiInstance.getTransactionalEntityManager().getFinder(OdiContext.class);
context = contextFinder.findByCode(contextCode);
techFinder = (IOdiTechnologyFinder) odiInstance.getTransactionalEntityManager().getFinder(OdiTechnology.class);
tech = techFinder.findByCode(techCode);
lschema = new OdiLogicalSchema(tech, schName)
dserver = new OdiDataServer(tech, dataserverName)
con = new AbstractOdiDataServer.JdbcSettings(url, driver)
dserver.setConnectionSettings(con)
dserver.setUsername(userName)
dserver.setPassword(password)
pschema = new OdiPhysicalSchema(dserver)
pschema.setSchemaName(schema)
pschema.setWorkSchemaName(schema)
cschema = new OdiContextualSchemaMapping(context, lschema, pschema)
odiInstance.getTransactionalEntityManager().persist(lschema)
odiInstance.getTransactionalEntityManager().persist(dserver)
tm.commit(txnStatus)
return lschema
lschema = createLogicalSchema("DEVELOPMENT", "ORACLE", "LS_HAL_TEST", "DS_HAL_TEST", "ODI_TEST", ObfuscatedString.obfuscate("odi_test"),
"jdbc:oracle:thin:@ourservername:10710:DBAA6T", "oracle.jdbc.OracleDriver", "ODI_TEST")
Notice i've changed the actual name of our server for "ourservername" because I don't know if I´m able to post that information.
Thanks.Hi,
I did try to hard code the parameters values, and it still didn't work. However, I did get a little bit closer, I found out that it doesn't work only whne my stored procedure uses a temporary table.
Any though, why the temporary table would cause this error ?
Thanks -
Running unix commands from within a procedure
Oracle 11.1, AIX 6.1
================
A developer would like to know what the commands are to execute from within a procedure to run unix commands on the database server and capture those results back to the procedure for parsing & manipulation.
Thanks.Don't take this as the correct way to do it, but this is merely 'a' way to do it:
have a db procedure thats executes a db function
create or replace procedure csproc(p_cmd in varchar2)
as
x number;
begin
x:=csfunc(p_cmd);
dbms_output.put_line('x is: '||x);
end;
/The function calls a piece of java to execute the os command and return the return code of the os command
create or replace function csfunc( p_cmd in varchar2) return number
as language java
name 'csclass.RunThis(java.lang.String[]) return integer';
/Here is the java class to run the os command
create or replace and compile java source
named "csclass"
as
import java.io.*;
import java.lang.*;
public class csclass extends Object
public static int RunThis(String[] args)
Runtime rt = Runtime.getRuntime();
int rc = -1;
try
Process p = rt.exec(args[0]);
int bufSize = 4096;
BufferedInputStream bis =
new BufferedInputStream(p.getInputStream(), bufSize);
int len;
byte buffer[] = new byte[bufSize];
// Echo back what the program spit out
while ((len = bis.read(buffer, 0, bufSize)) != -1)
System.out.write(buffer, 0, len);
rc = p.waitFor();
catch (Exception e)
e.printStackTrace();
rc = -1;
finally
return rc;
/and finally the os command - in this case its a very simple shell script
#!/usr/bin/ksh
echo "Hi" >> /app/oracle/workdir/cs.logwill have to grant privileges to my user 'CS' to run the various os commands
exec dbms_java.grant_permission('CS','java.io.FilePermission','/app/oracle/workdir/cs.ksh','read,execute');
exec dbms_java.grant_permission('CS','java.io.FilePermission','/app/oracle/workdir/cs.log','write');
exec dbms_java.grant_permission('CS','SYS:java.lang.RuntimePermission','*','readFileDescriptor');
exec dbms_java.grant_permission('CS','SYS:java.lang.RuntimePermission','*','writeFileDescriptor');and finally can run the procedure from within the db
set serveroutput on
exec dbms_java.set_output(1000000);
exec csproc('/app/oracle/workdir/cs.ksh');
x is: 0
PL/SQL procedure successfully completed.to prove it works ok the logfile shows an entry:
'Hi' -
Can't we manually type commands within run block ?
11.2.0.3/linux
I was doing an RMAN restore to a new server.
Below is the code I wanted to execute to restore
run
SET NEWNAME FOR DATABASE TO '/fnup/hwrc/oradata/spikey';
restore database ;
}Since it is just 2 lines within a run block , so I thought of typing it manually. After typing the first line (SET NEW NAME..) ending with semi colon, i pressed ENTER key to get the next line and type the RESTORE command . But I was getting the following error.
RMAN> run
2> {
3> set new name for database to '/fnup/hwrc/oradata/spikey'; ###### After typing the semicolon I pressed ENTER here
RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-00558: error encountered while parsing input commands
RMAN-01009: syntax error: found "new": expecting one of: "archivelog, autobackup, auxiliary, auxname, backup, command, compression, controlfile, database, dbid, decryption, echo, encryption, high, incarnation, maxcorrupt, maxseq, newname, nocfau, restore, snapshot, to restore point, until restore point, until"
RMAN-01007: at line 3 column 5 file: standard input
------| Second Attempt |----------------------------------------------
RMAN> run
2> {
3> set new name for database to '/fnup/hwrc/oradata/spikey'; ###### After typing the semicolon I pressed ENTER here
RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-00558: error encountered while parsing input commands
RMAN-01009: syntax error: found "new": expecting one of: "archivelog, autobackup, auxiliary, auxname, backup, command, compression, controlfile, database, dbid, decryption, echo, encryption, high, incarnation, maxcorrupt, maxseq, newname, nocfau, restore, snapshot, to restore point, until restore point, until"
RMAN-01007: at line 3 column 5 file: standard inputEventually I had to put the above 2 lines in a script and executed it using cmdfile parameter. Can we execute RMAN commands within a run block only through a script ?A short note...
run
ALLOCATE CHANNEL ckpt_db1 DEVICE TYPE disk;
ALLOCATE CHANNEL ckpt_db2 DEVICE TYPE disk;
ALLOCATE CHANNEL ckpt_db3 DEVICE TYPE disk;
ALLOCATE CHANNEL ckpt_db4 DEVICE TYPE disk;
ALLOCATE CHANNEL ckpt_db5 DEVICE TYPE disk;
ALLOCATE CHANNEL ckpt_db6 DEVICE TYPE disk;
ALLOCATE CHANNEL ckpt_db7 DEVICE TYPE disk;
ALLOCATE CHANNEL ckpt_db8 DEVICE TYPE disk;
SET NEWNAME FOR DATAFILE 1 TO '/u02/oradata/ckpt_db/system01.dbf';
SET NEWNAME FOR DATAFILE 2 TO '/u02/oradata/ckpt_db/sysaux01.dbf';
SET NEWNAME FOR DATAFILE 3 TO '/u02/oradata/ckpt_db/undotbs01.dbf';
SET NEWNAME FOR DATAFILE 4 TO '/u02/oradata/ckpt_db/users01.dbf';
SET NEWNAME FOR DATAFILE 5 TO '/u02/oradata/ckpt_db/psdefault.dbf';
SET NEWNAME FOR DATAFILE 6 TO '/u02/oradata/ckpt_db/amapp.dbf';
SET NEWNAME FOR DATAFILE 7 TO '/u02/oradata/ckpt_db/AMARCH.dbf';
restore database;
switch datafile all;
RELEASE CHANNEL ckpt_db1;
RELEASE CHANNEL ckpt_db2;
RELEASE CHANNEL ckpt_db3;
RELEASE CHANNEL ckpt_db4;
RELEASE CHANNEL ckpt_db5;
RELEASE CHANNEL ckpt_db6;
RELEASE CHANNEL ckpt_db7;
RELEASE CHANNEL ckpt_db8;
} -
Running ls command from Java stroed procedure no output
Hi ,
I am trying to run ls command from java stored procedure in oracle
Process p = Runtime.getRuntime().exec("ls");
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("output of the command run:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
from java stored procedure in oracle.
i get output of println statments but it does not go into while loop to print from stdInput.
Result of running Java stored procedure is -
output of the command run:
Call completed.
when i run the program on client side it works fine.
Has anybody tried this from java stroed procedure.
Thanks,
JagJag,
Actually, the question of whether it works for me seems to depend on the version of the OS (or Oracle). On RedHat Linux (Oracle 8.1.6) it didn't work at all, but on Solaris (Oracle 9.0.2) it did. Here's the output from that run:
SQL> /
output of the command run:
init.ora
initDBPart9i.DBPSun01.ora
initdw.ora
lkDBPART9I
orapw
orapwDBPart9i
spfileDBPart9i.ora
Done
PL/SQL procedure successfully completed.
But, I did need to change a line of your code to this:
Process p = Runtime.getRuntime().exec("/usr/bin/ls");
your original was:
Process p = Runtime.getRuntime().exec("ls");
You might consider, if possible, use of some of the Java File classes instead of ls, as this might make things more predictable for you. There were some examples in oramag.com a few months ago, but they were pretty simple (you might not need them).
Hope this helps,
-Dan
http://www.compuware.com/products/devpartner/db/oracle_debug.htm
Debug PL/SQL and Java in the Oracle Database -
Not able to create Oracle External Procedure to Run Host Commands
Trying to follow this article
http://timarcher.com/node/9
Its related to
Oracle External Procedure to Run Host Commands
steps
1)mkdir –p /u01/app/usfapp/oracle_external_procs/oracle_host
2)
Author is suggesting to create a file
but header file is missing in very first line... may be not sure..say it is <stdio.h>Create a file named oracle_host.c. The contents of this file will be:
#include
int RunCmd(char *cmd)
return(system(cmd));
4) Create the file named makefile. The contents of this file will be:
oracle_host: oracle_host.o
gcc -shared -o oracle_host.so oracle_host.o
$ cat makefile
oracle_host: oracle_host.o
gcc -shared -o oracle_host.so oracle_host.o
5)
Now run the command make
The output on my server looks like:
[u01/app/usfapp/oracle_external_procs/oracle_host]
banner@usfbannerte [TRNG] > make
gcc -shared -o oracle_host.so oracle_host.o
here I stuck .. Not able to run this step ]$ make
gcc -shared -o oracle_host.so oracle_host.o
/usr/bin/ld: oracle_host.o: relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC
oracle_host.o: could not read symbols: Bad value
collect2: ld returned 1 exit status
make: *** [oracle_host] Error 1
Any one has any idea what went wrong
Any other link related to this is most welcomed.
Please suggest ...hi
please update
or
provide any other link / document for
Oracle External Procedure to Run Host Commands
--using c
Thanks in advance. -
Set env using a script and run the command (dependency on the env)
I need to set the env varaible by running a shell script with arguments as 'ksh setEnviron r6.1' and then run the command in the
same process. the command has dependency on the previous script which sets the env variables.
With Runtime.getRuntime().exec( cmd1); ,Runtime.getRuntime().exec( cmd2); I am not able to execute the Cmd2 as it is running in different process.
How do solve this issue.
Is there any other method to run the command to set env variables and run the second command.(dependent on the env) to get the output.
Please help me out in this.ganesh_mak wrote:
final String[] commands = {
". setEnviron r6.1",
"/usr/add-on/test/Xbin/sql name from list where date.eq.05/22/08",
Process penv = Runtime.getRuntime().exec("/bin/sh");
BufferedReader br = new BufferedReader( new InputStreamReader( penv.getInputStream() ) );
BufferedReader stdError = new BufferedReader(new InputStreamReader(penv.getErrorStream()));
final OutputStream writer = penv.getOutputStream();
for (int i=0; i<commands.length;i++)
writer.write(commands.getBytes("utf-8"));
writer.write("\n".getBytes());
String line;
while((line = br.readLine())!=null){
System.out.println(line);
br.close();
writer.close();
I tried the above code but its not working...............
please correct me.
Do you think I used the '-i' argument just for fun? Did you do a 'man sh' and 'man bash' to see what the arguments do? If not then do it now.
Do you think I used Theads to process stderr and stdout just for fun? I've shown you the basic approach. I have shown you how you need to create Threads to process stdout and stderr. If you have not understood and you have not studied http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html then do so now.
Edited by: sabre150 on Jun 2, 2008 3:43 PM -
Running a process within a java program
Hi
I have code that runs a process for performance monitoring on an installed system. When I run the code standalone as below, it runs fine. If I include the code below inside another java program, the process fails to execute and the status returned is non-zero (failed to execute).
The process requires the PATH and LD_LIBRARY_PATH to be set which seem to be set correctly when i print them out. So, I am not sure why the process doesnot run when included within another running java program.
Can someone please point out what I maybe missing?
Thanks!!
public class RunPerf
private static final String CLASS_NAME = "RunPerf"; private static Process proc = null;
public static void main(String[] args)
String INSTALLPERF_SAW_UNIX_COMMAND = "sawexe" + " " + "-perf";
StringBuffer path1 = new StringBuffer(30);StringBuffer ldlibpath1 = new StringBuffer(30);
System.setProperty("user.home", "/home/user");
StringBuilder commandToExecute = new StringBuilder();
commandToExecute.append(System.getProperty("user.home"));
commandToExecute.append(File.separator);
commandToExecute.append("web");
commandToExecute.append(File.separator);
commandToExecute.append("bin");
commandToExecute.append(File.separator);
String path = System.getProperty("user.home")+"/server/bin/" + File.pathSeparator + System.getProperty("user.home")+ "/web/bin";
path1.append( path );
path1.append( File.separator );
path1.append( System.getProperty("java.library.path") );
path1.append( File.separator );
String env_value = null;
String[] ldargs = {"LD_LIBRARY_PATH"};
for (String env: ldargs) {
env_value = System.getenv(env);
System.out.println("LD_LIBRARY_PATH value before setting property= " + env_value);
if (env_value != null) {
String newldlibpath = System.getProperty("user.home")+ "/server/bin/" + File.pathSeparator + System.getProperty("user.homee")+ "/web/bin" ;
ldlibpath1.append(newldlibpath);
ldlibpath1.append(File.separator);
ldlibpath1.append(env_value);
ldlibpath1.append( File.separator);
System.out.format("%s=%s%n", env,ldlibpath1.toString());
} else {
System.out.format("%s is not assigned.%n", env);
commandToExecute.append(INSTALLPERF_SAW_UNIX_COMMAND);
String[] envp = { "USER_HOME =" + "/home/user", "PATH=" + path1.toString(), "LD_LIBRARY_PATH=" + ldlibpath1.toString() };
int status = executeCommand1(commandToExecute.toString(), envp,null);
if(status != 0){
System.out.println("Unable to run perf Unix") ;
public static int executeCommand1(String command,String[] envp, Logger logger) {
String METHOD_NAME = "executeCommand1";
if (logger == null) { logger = Logger.getAnonymousLogger();}
logger.entering(CLASS_NAME, METHOD_NAME, new Object[] { command, envp});
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new Thread() {
public void run() {
if (proc != null) { try { proc.destroy(); if (proc != null) { proc.destroy(); }
} catch (Exception e) {
e.printStackTrace(); } } } });
int retVal = 0;
File cwd = new File(System.getProperty("user.home")+ "/web/bin/");
try {
if (envp != null) { proc = runtime.exec(command, envp,cwd); }
else { proc = runtime.exec(command); }
Thread t_err = new Thread(new StreamReader(proc.getErrorStream()));
t_err.start();
Thread t_in = new Thread(new StreamReader(proc.getInputStream()));
t_in.start();
retVal = proc.waitFor(); } catch (IOException e) { retVal = -1; logger.severe("IOException"); }
catch (Exception e) { retVal = -1; logger.severe("Exception"); }
logger.exiting(CLASS_NAME, METHOD_NAME, retVal);
return retVal;
static class StreamReader implements Runnable {
InputStream in;
public StreamReader(InputStream genericStream) { in = genericStream; }
public void run() {
try {
String strTemp = null;
BufferedReader buffReader = new BufferedReader(new InputStreamReader(in));
while ((strTemp = buffReader.readLine()) != null) {
System.out.println(strTemp); }
} catch (Exception e) { e.printStackTrace(); } } }}Either set up a script before the program runs or have the
program write a script file which contains the statements
that need to be executed. Then you will be able to
execute the script with a call to
Runtime.getRuntime().exec()Mark -
Hi
I am trying to execute some set commands in a procedure with the following sql:
create procedure test as
begin
execute immediate 'set linesize 350';
execute immediate 'set pagesize 100';
execute immediate 'set serveroutput on';
select... <sql>...
end;
I am able to create the procedure successfully, however I am unable to execute it due to the execute immediate statements.
ORA-00922: missing or invalid option
ORA-06512: at "XXX.TEST", line 3
ORA-06512: at line 1
Any idea on how to change them please?
Thank you!SQL*Plus isn't generally an end-user tool, and dbms_output is a debugging aid for programmers. PL/SQL runs on the database server and cannot control the client application that calls it.
You might look at the reporting capabilities of Application Express or SQL Developer.
Allround Automations also do a freeware app called Query Reporter that might help in presenting the results of SQL queries, although it won't handle ref cursors returned by procedures (if you used them).
There is also mod_plsql although it's kind of legacy these days, which I'm glad about because I never understood it ;) -
Run Unix command / Run Unix shell script from Forms9i
Hi,
I have a requirement to run Unix command and Unix shell scripts from Forms9i.
I know HOST command cannot be used directly. I also know we can create some JAVA stored procedure to perform the task, but I don't want to create any JAVA stored procedure as there are some security concerns.
Please point me towards any other way to achieve the same.
I would really appreciate your help.
Thanks,
KumarThere is no reason why HOST can't be used. This is what it is for. As for using Java, it is not a stored procedure that you would be using, it would be imported Java (imported into the form).
The best way to use the HOST command is to call a script (.sh) rather than calling a Unix command directly. This is because HOST will not pick up environment variables set at the system level. So the script would first need to set the necessary environment variables then call the desired commands. -
How to run OS commands from PL/SQL???
Hi
Is there any way to run OS commands(Windows Platform) from within PL/SQL?
ThanksAPC,
I am working on Discoverer, having lots of BAs & Workbooks created & stored in Database. Now if i want to move all the workbooks from one place to another (like from development to test or production) i can use Command line interface of Disco to do this. But i don't see any option there to export all the workbooks, so i thought of writing a pl/sql to get all the workbook names from the EUL then fire export Command for each record(although not a good practice but its a one time work). This is the place where i need to run OS command from within PL/SQL. Although it doesn't seem possible now(as you all said) without external procedure.
Lastly, you are right that "Oracle make databases not operating systems" but my first impression/comment about oracle is:
"Oracle is far Bigger, Powerful, Complex, Vast and Interesting System than any other..." so i believe it can do/capable doing anything :-)
thx Ashutosh,
Host is definitely an option but i can't run it from pl/sql(that i am looking for).. -
Hi,
We use JAVA source in Oracle to execute some unix commands directly from within stored procedures in Oracle.
Our Java source looks like this :
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "HOST" AS
import java.lang.*;
import java.io.*;
public class Host
public static void executeCommand (String command, String etype) throws IOException
String[] wFullCommand = {"C:\\winnt\\system32\\cmd.exe", "/y", "/c", command};
String[] uFullCommand = {"/bin/sh", "-c", command};
if (etype.toUpperCase().equals("W"))
Runtime.getRuntime().exec(wFullCommand);
else if(etype.toUpperCase().equals("U+"))
Runtime.getRuntime().exec(uFullCommand);
else if(etype.toUpperCase().equals("U"))
Runtime.getRuntime().exec(command);
CREATE OR REPLACE PROCEDURE Host_Command (p_command IN VARCHAR2, p_etype IN VARCHAR2)
AS LANGUAGE JAVA
NAME 'Host.executeCommand (java.lang.String, java.lang.String)';
We call one unix shell script and discover that some UNIX commands from this shell script are executed and others not. A cp & touch command don't give problems whilst cat & unix2dos commands don't function.
Can anybody help me on this subject?
Thanks !
KrisHi Avi, thanks for your reaction. Got it to work with the unix scripts, the problem was a syntax error in the script itself.
However I don't get it to function when I try to run a unix command directly. Normally the parameter U+ should decide to start it in a shell for scripts and otherwise it should run the command directly. (whithout the /bin/sh in front of it).
I already adapted my source to try to execute the command in a new shell but without success :
String[] uFullCommand = {"/bin/sh", "-c", "\'cp /export/home/caluwaek/test/bestand2 /export/home/caluwaek/test/bestand8\'"};
I tried to put the whole command in one string, in 3 strings, to just call the cp command without bothering the shell. Nothing seems to work.
In unix both the following work :
cp /export/home/caluwaek/test/bestand2 /export/home/caluwaek/test/bestand8
and
/bin/sh -c 'cp /export/home/caluwaek/test/bestand2 /export/home/caluwaek/test/bestand8'
Thanks for your help!
Kris -
Run shell commands using java program
Hi guys,
I am trying to run shell commands like cd /something and ./command with arguments as follows, but getting an exception that ./command not found.Instead of changing directory using "cd" command I am passing directory as an argument in rt,exec().
String []cmd={"./command","arg1", "arg2", "arg3"};
File file= new File("/path");
try{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd,null,file);
proc.waitFor();
System.out.println(proc.exitValue())
BufferedReader buf = new BufferedReader(new InputStreamReader(proc.getInputStream()));
catch(Exception e)
{e.printStackTrace();
So can anyone please tell me what is wrong with this approach? or is there any better way to do this?
Thanks,
Hardikwarnerja wrote:
What gives you the idea that the process to execute is called "./command"? If this is in Windows, it is "cmd.exe" for example.It does not have to be cmd.exe in Windows. Any executable or .bat file can be executed as long as one either specifies the full path or the executable is in a directory that is in the PATH.
On *nix the file has to have the executable bit set and one either specifies the full path or the executable must be in a directory that is in the PATH . If the executable is a script then if there is a hash-bang (#!) at the start of the first line then the rest of the line is taken as the interpreter to use. For example #!/bin/bash or #!/usr/bin/perl .
One both window and *nix one can exec() an interpreter directly and then pass the commands into the process stdin. The advantage of doing this is that one can change the environment in one line and it remains in effect for subsequent line. A simple example of this for bash on Linux is
import java.io.OutputStreamWriter;
import java.io.Writer;
public class ExecInputThroughStdin
public static void main(String args[]) throws Exception
final Process process = Runtime.getRuntime().exec("bash");
new Thread(new PipeInputStreamToOutputStreamRunnable(process.getErrorStream(), System.err)).start();
new Thread(new PipeInputStreamToOutputStreamRunnable(process.getInputStream(), System.out)).start();
final Writer stdin = new OutputStreamWriter(process.getOutputStream());
stdin.write("xemacs&\n");
stdin.write("cd ~/work\n");
stdin.write("dir\n");
stdin.write("ls\n");
stdin.write("gobbldygook\n"); // Forces output to stderr
stdin.write("echo $PATH\n");
stdin.write("pwd\n");
stdin.write("df -k\n");
stdin.write("ifconfig\n");
stdin.write("echo $CWD\n");
stdin.write("dir\n");
stdin.write("cd ~/work/jlib\n");
stdin.write("dir\n");
stdin.write("cat /etc/bash.bashrc\n");
stdin.close();
final int exitVal = process.waitFor();
System.out.println("Exit value: " + exitVal);
}One can use the same approach with Windows using cmd.exe but then one must be aware of the syntactic differences between commands running in .bat file and command run from the command line. Reading 'help cmd' s essential here.
The class PipeInputStreamToOutputStreamRunnable in the above example just copies an InputStream to an OutputStream and I use
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class PipeInputStreamToOutputStreamRunnable implements Runnable
public PipeInputStreamToOutputStreamRunnable(InputStream is, OutputStream os)
is_ = is;
os_ = os;
public void run()
try
final byte[] buffer = new byte[1024];
for (int count = 0; (count = is_.read(buffer)) >= 0;)
os_.write(buffer, 0, count);
} catch (IOException e)
e.printStackTrace();
private final InputStream is_;
private final OutputStream os_;
} -
Running Shell Commands (not Executable) in Unix from Java
What are my options to run shell commands from Java?
My goal is to change my existing shell environment variables to some new ones provided by .anotherProfile.
Using an executable from Java is not an option because it does not work i.e. ( exec(". /home/.profile") ) brings up errors.
Someone has suggested that I start a child shell with that profile and work from there, but I'm unfamiliar with that sort of syntax and programming in general.
Any good help equals duke dollars :)Well there are some possibilities. In the original thread you mentioned that you wanted the shell script to be executed to change some enviroment parameters of the shell the JVM is executing in.
If so, and you are able to rewrite the profile so you can parse it manually. Then you can change some environment setting by writing the JNI wrappers for the getenv and setenv system calls. (Check your man pages)
That will change the environment. I am just wondering what good it will do for you? What's use of sourcing the profile in a JVM? -
Applescript for running sudo commands in terminal
I'm a newbie when it comes to Applescript and was wondering if someone could help with a basic request. I need to write a small script to do the following:
1. Launch terminal
2. Run the 'Sudo -s' command
3. Enter the administrator password (in plain text)
and then
4. run some sudo commands like "sudo defaults write /Library/Preferences/com.apple.loginwindow HiddenUsersList -array-add administrator"
I actually WANT the administrator password to be in the script in plain text even though I understand the security risks (I will literally be the only person to ever see the script). I've trawled forums all over but can't seem to find what I am looking for and cannot get it working by patching together the various commands I have found. Thanks in advance for any help you can give!
SeanI've included two examples. The preferred way & the hacker way.
with administrator
It is easier to diagnose problems with debug information. I suggest adding log statements to your script to see what is going on. Here is an example.
Author: rccharles
For testing, run in the Script Editor.
1) Click on the Event Log tab to see the output from the log statement
2) Click on Run
For running shell commands see:
http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html
on run
-- Write a message into the event log.
log " --- Starting on " & ((current date) as string) & " --- "
-- debug lines
set unixDesktopPath to POSIX path of "/System/Library/User Template/"
log "unixDesktopPath = " & unixDesktopPath
set quotedUnixDesktopPath to quoted form of unixDesktopPath
log "quoted form is " & quotedUnixDesktopPath
try
set fromUnix to do shell script "sudo ls -l " & quotedUnixDesktopPath with administrator privileges
display dialog "ls -l of " & quotedUnixDesktopPath & return & fromUnix
on error errMsg
log "ls -l error..." & errMsg
end try
end run
This version has an inline password.
Notice the echo 'password' |
The single quotes are no accident.
It is easier to diagnose problems with debug information. I suggest adding log statements to your script to see what is going on. Here is an example.
Author: rccharles
For testing, run in the Script Editor.
1) Click on the Event Log tab to see the output from the log statement
2) Click on Run
For running shell commands see:
http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html
on run
-- Write a message into the event log.
log " --- Starting on " & ((current date) as string) & " --- "
-- debug lines
set unixDesktopPath to POSIX path of "/System/Library/User Template/"
log "unixDesktopPath = " & unixDesktopPath
set quotedUnixDesktopPath to quoted form of unixDesktopPath
log "quoted form is " & quotedUnixDesktopPath
try
set fromUnix to do shell script "echo 'password' | sudo ls -l " & quotedUnixDesktopPath
display dialog "ls -l of " & quotedUnixDesktopPath & return & fromUnix
on error errMsg
log "ls -l error..." & errMsg
end try
end run
Maybe you are looking for
-
Apple TV no longer appearing in iTunes
after months of working flawlessly, Apple TV is no longer syncing to iTunes. It does not appear under Devices. I have checked the Preferences Apple TV tab and although it is set to Look for Apple TVs, none appear. On the Apple TV I checked the networ
-
Using Matlab in Labwindows/CVI
I have a matlab .m file that runs a function. In my Labwindows software, I want to be able to run this function. Is this possible? Thanks.
-
Help!! iTunes wont download album artwork
itunes will not upload artwork from the cd's (albums) that were already loaded in my pc (before I added itunes and my ipod). It certainly uploaded EVERYthing else. It says that I don't have directX downloded so, I downloaded it. When I try to get it
-
If Both tables having References then how to insert the data each other
Hai EveryOne.., My Sample data., Create table emp (empno number primary key,ename varchar2(20)); Create table emp_dup (empno number references emp(empno),ename varchar2(20) primary key); alter table emp add constraint ename_fk foreign key(ename) refe
-
How can I change the margin settings in the pages inspector to make them more specific for label templates. I need margins that can be set to hundreths of a centimetre not just tenths.