Opening a UNIX shell in Java
Hi,
I need to simulate the machine's native shell (e.g. cmd\sh in case of windows\unix respectively). For that I open up a UNIX shell in my Java program using the usual manner:
Runtime.getRuntime().exec("sh");Then I use the input and output streams of the Process in order to "communicate" with the process.
My code works fine with windows shell ('cmd') but with unix ('sh') I failed to retrieve the machine's prompt. I believe that the issue is unix-related and that the process I launched has no appropriate environment parameter.
Any idea?
Thanks in advance
Thanks for your fast reply.
Although the article was interesting and did review the java.lang.Runtime quite good, it didn't help me as I have a specific problem with Unix OS and the article deliberately (or not) ignored that.
I noticed that when I print the environments variables in my java application I get a partial list which doesn't contain the prompt (for instance the SP1 variable) whilst execute the 'set' command (not from java) i get a longer list and the prompt variable appears there.
Any idea how should I execute the shell through java in order to receive the prompt?
Similar Messages
-
Executing Unix shell from Java Program
Hi,
I have written a java application using Maverick J2sshtools API which connects to a Unix box using SSH.The program authenticates with the remote box successfully,but It dosen't return the environment info or execute the test script.Have attached the complete code.
package shellInteraction;
import com.maverick.ssh.*;
import com.maverick.ssh2.Ssh2Client;
import com.maverick.ssh2.Ssh2Context;
import com.maverick.ssh2.Ssh2PasswordAuthentication;
import com.sshtools.net.*;
import java.io.*;
import java.util.Iterator;
import java.util.Vector;
public class JavaShell{
public static void main(String[] args) {
SshConnector con = null;
SshClient ssh = null;
ShellProcess process = null;
Shell shell = null;
try{
// Create a session to remote host
con = SshConnector.getInstance();
ssh = connectionSetup(con);
System.out.println(ssh);
// Start a session and do basic IO
if (ssh.isAuthenticated()) {
shell = new Shell(ssh);
System.out.println("Authenticated");
if(shell.getEnvironment().hasEnvironmentVariable("hostname"))
System.out.println("We are connected to " + shell.getEnvironment().getEnvironmentVariable("hostname"));
//System.out.println("Remote operating system is " + shell.getEnvironment().getOperatingSystem());
// boolean isWindows = shell.getEnvironment().getOSType()==ShellEnvironment.OS_WINDOWS;
//if(shell.getEnvironment().hasEnvironmentVariable("USERPROFILE")) {
//System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("USERPROFILE"));
//} else if(shell.getEnvironment().hasEnvironmentVariable("HOME")) {
//System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("HOME"));
// Commands only executed for Unix OS
//if(!isWindows) {
// Execute a script
traverseDirectory(shell);
shell.exit();
ssh.disconnect();
System.out.println("Shell has exited");
} catch(Throwable t) {
t.printStackTrace();
private static void traverseDirectory(Shell shell) throws Exception{
System.out.println("\n\nTraverse Directory");
// Execute a simple script than prints a directory tree
ShellProcess process = shell.execute("bash test.sh ");
try{
process.expect("Total directories", 1000, true);
System.out.print(process.toString());
} catch (ShellTimeoutException ex1) {
System.out.println("TRAVERSE Expect operation timed out. Sending interrupt to kill the process");
process.interrupt();
}finally {
process.close();
static private Ssh2Client connectionSetup(SshConnector con)throws SshException{
Ssh2Client ssh = null;
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Hostname: ");
String hostname = reader.readLine();
int idx = hostname.indexOf(':');
int port = 22;
if(idx > -1) {
port = Integer.parseInt(hostname.substring(idx+1));
hostname = hostname.substring(0, idx);
System.out.print("Username [Enter for " + System.getProperty("user.name") + "]: ");
String username = reader.readLine();
if(username==null || username.trim().equals(""))
username = System.getProperty("user.name");
System.out.println("Connecting to " + hostname);
* Create an SshConnector instance
con = SshConnector.getInstance();
// Lets do some host key verification
HostKeyVerification hkv = new PasswordHostKey();
con.setSupportedVersions(SshConnector.SSH2);
* Set our preferred public key type
con.getContext(SshConnector.SSH2).setHostKeyVerification(hkv);
((Ssh2Context)con.getContext(SshConnector.SSH2)).setPreferredPublicKey(Ssh2Context.PUBLIC_KEY_SSHDSS);
* Connect to the host
ssh = (Ssh2Client)con.connect(new SocketTransport(hostname, port), username, true);
* Authenticate the user using password authentication
Ssh2PasswordAuthentication passwordAuthentication = new Ssh2PasswordAuthentication();
System.out.print("Password: ");
passwordAuthentication.setPassword(reader.readLine());
if(ssh.authenticate(passwordAuthentication)!=SshAuthentication.COMPLETE) {
System.out.println("Authentication failed!");
System.exit(0);
}catch(Exception ex1) {
throw new SshException(ex1.getMessage(), ex1.getCause());
return ssh;
When I execute the program
Hostname:****
Username [Enter for thaya]: **
Connecting to CATL
The connected host's key (ssh-dss) is
b6:85:91:6b:8b:ea:cb:40:b5:6f:01:2e:66:78:7f:62
Password: *****
SSH2 CATLMSXP62:22 [kex=diffie-hellman-group1-sha1 hostkey=ssh-dss client->server=aes128-cbc,hmac-sha1,none server->client=aes128-cbc,hmac-sha1,none]
Authenticated
Traverse Directory
com.maverick.ssh.ShellTimeoutException: The shell did not return to the prompt in the given timeout period 10000ms
at com.maverick.ssh.Shell.A(Unknown Source)
at com.maverick.ssh.Shell.execute(Unknown Source)
at shellInteraction.ShellInteraction.traverseDirectory(ShellInteraction.java:108)
at shellInteraction.ShellInteraction.main(ShellInteraction.java:68)
This is the error message what i get.use code tags if you want a response,
ive done the same thing once using
ssh2.ethz.ch ie:
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ServerHostKeyVerifier;
import ch.ethz.ssh2.Session;
the code looked something like this:
try
conn.connect(new ServerHostKeyVerifier() {
public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
return true;
conn.authenticateWithPassword(username, password);
try {
sess = conn.openSession();
} catch (java.lang.IllegalStateException e) {
return;
// JOptionPane.showMessageDialog(null, "Could not autheticate.\nCheck username and password.\nTerminating.", "Authentication Failed", JOptionPane.ERROR_MESSAGE);
// System.exit(-1);
sess.requestPTY("dumb", 50, 50, 0, 0, null);
sess.startShell();
}and after that sess has getStdIn() and getStdOut() that get the streams from which you read and write. -
Pass commands to UNIX shell opened in Windows XP OS
I am currently running Labview 7.1 on a Windows XP box. I use Exceed to open a UNIX shell to do work in UNIX from my windows machine. I can open the UNIX shell with the sys exec vi but how do I pass commands to the UNIX shell I opened?
Purp1eOne wrote:
I went to the sourceforge site to take a look and started the install process but after looking at the install instructions it says I need a run time engine of 8 or greater which I don't have:
Kind of a novice here but I don't think this will work with LabView 7.1, will it?
Also make sure you have
the LabVIEW 8.2.1 Run-Time Engine installed.
View Member Profile
ipsmenu.register( "post-member-26", '', 'popmenubutton-new', 'popmenubutton-new-out' );
Jul 17 2006, 08:53 PM
Post
#1
Group: JKI Team
Posts: 167
Joined: 10-July 06
Member No.: 7
Note: The LabVIEW 8.0.1 and 8.2.1 run-time engines can co-exist
together with the LabVIEW 8.5 (and newer) run-time engine. You still
need to install the run-time engine's listed below to use VIPM, even if
you have a newer version of LabVIEW installed.
VIPM 1.1 and 2.0
VIPM 1.1 and 2.0 require the LabVIEW 8.2.1 run-time engine installed on your machine.
See also:Where do I get the LabVIEW 8.2.1 Run-Time Engine?
VIPM 1.0
VIPM 1.0 requires the LabVIEW 8.0.1 run-time engine installed on your machine.
See also:
Smercurio is right, and their is no OpenG package for the newer VIs so you will actually want to get them directly from CVS.
Rolf Kalbermatter
Rolf Kalbermatter
CIT Engineering Netherlands
a division of Test & Measurement Solutions -
Trouble in Unix calling a Java utility from another shell script
Hi,
I'm able to run a shell script (call it script B) in Unix which calls a Java utility. When I call script B from another script (script A) I get the error below. I have done much work to make sure the environment variables are the same.
java.util.zip.ZipException: error in opening zip f
ile
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:69)
at com.something.runtime.ZipFileApplicationSource.<init>(ZipFileApplicationSource.java:22)
at com.something.runtime.ZipFileRuntime.main(ZipFileRuntime.java:35
ANY HELP WOULD BE GREATLY APPRECIATED.
ThanksHere's my guess, if this doesn't work, post your scripts and maybe that will help.
When you run your script B, you said it works. I think the problem is that when you run script B, your shell and envirenment variables are set by the window you're working in. When you call script B from script A, it creates a new shell to run it and it doesn't run the files that are run when you start a terminal or a telnet(it won't run .cshrc, .kshrc or .login). Depending on what OS you're using, I think the default shell is sh for most of them. The first line of script B should be
#!/(your bin directory)/(shell you're using)
for me it's
#!/bin/tcsh
then you might want to run your startup file to set envirenment variables, paths, etc...
source (your user directory)/(the file name)
for me it's
source ~/.cshrc
Then if you need to set the environment variables in your script.
set CLASSPATH /usr/local/j2ee/bin.....
set PATH /bin:/xyz....
If that doesn't help post your scripts, or if I didn't explain it will enough, just ask. -
Error while trying to execute a unix shell script from java program
Hi
I have written a program to execute a unix shell script in a remote machine. I am using J2ssh libraries to estabilish the session connection with the remote box.The program is successfully able to connect and authenticate with the box.
The runtime .exec() is been implemented to execute the shell script.I have given below the code snippet.
try {
File file_location = new File("/usr/bin/");
String file_location1 = "/opt/app/Hyperion/scripts/daily";
String a_mib_name = "test.sh";
String cmd[] = new String[] {"/usr/bin/bash", file_location1, a_mib_name};
Runtime rtime = Runtime.getRuntime();
Process p = rtime.exec(cmd, null, file_location);
System.out.println( "Connected to the server1" );
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = br.readLine();
while(line !=null)
System.out.println(line);
line = br.readLine();
br.close();
p.getErrorStream ().close ();
p.getOutputStream().close();
int retVal = p.waitFor();
System.out.println("wait " + retVal);
//session.executeCommand("ls");
catch (IOException ex) {
I get an error message
Connected to the server
java.io.IOException: Cannot run program "/usr/bin/bash" (in directory "\usr\bin"
): CreateProcess error=3, The system cannot find the path specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at SftpConnect.main(SftpConnect.java:143)
Caused by: java.io.IOException: CreateProcess error=3, The system cannot find th
e path specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
I am sure of the file path where the bash.sh and test.sh are located.
Am i missing something? Any help would be greatly appreciated.
Thanks
SenthilHi, I am using a simple program to connect to a RMI server and execute shell script. I use the Runtime.exec aommand to do the same.
The script is sh /tmp/pub/alka/test.sh /tmp/pub/alka/abc/xyz/ul ul
The script when run from the server, gives no errors. But when ran using rthe above method in java, gives errors as follows,
Mycode:
String command = "/bin/sh /tmp/pub/alka/test.sh /tmp/pub/alka/abc/xyz/ul ul";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
int exitVal = proc.exitValue();
System.out.println("Process exitValue: " + exitVal);
java.io.IOException: CreateProcess: /bin/sh /tmp/pub/alka/test.sh /tmp/pub/alka/abc/xyz/ul ul error=3
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at DecryptTest.main(DecryptTest.java:18)
Can anyone please help -
Error while executing unix shell script from java program
Hi All,
I am trying to execute unix shell script from a java program using Runtime.execute() method by passing script name and additional arguments.
Code snippet :
Java Class :
try{
String fileName ="test.ksh";
String argValue ="satish"; // value passed to the script
String exeParam = "/usr/bin/ksh "+fileName+" "+argValue;
Process proc = Runtime.getRuntime().exec(exeParam);
int exitValue = proc.waitFor();
sop("Exit Value is : "+exitValue);
catch(Exception e)
e.printStackTrace();
}Test.ksh
export -- application realated paths..
nohup abc.exe 1> test.log 2>&1;
$1
exit.By running the above java class , i am getting exit Value: 139 and log file test.log of 0 bytes.
when i am running the same command (/usr/bin/ksh test.ksh satish) manually, it's calling abc.exe file successfully
and able generate the logs properly.
Pls let us know where exactly i am stuck..
Thanks in advance,
Regards,
SatishHi Sabre,
As per the guidelines provided by the article, i had done below changes..
InputStream is = null;
InputStreamReader iStreamReader = null;
BufferedReader bReader = null;
String line = null;
try{
String fileName ="test.ksh";
String argValue ="satish"; // value passed to the script
String exeParam = "/usr/bin/ksh "+fileName+" "+argValue;
Process proc = Runtime.getRuntime().exec(exeParam);
is = proc.getErrorStream();
iStreamReader = new InputStreamReader(is);
bReader = new BufferedReader(iStreamReader);
System.out.println("<ERROR>");
while((line = bReader.readLine()) != null)
System.out.println("Error is : "+line);
System.out.println("</ERROR>");
int exitValue = proc.waitFor();
sop("Exit Value is : "+exitValue);
catch(Exception e)
e.printStackTrace();
Now , it's showing something like..
<ERROR>
</ERROR> -
Exit status running java classpath in a unix shell script
I'm new to putting java into unix scripts. I have a java classpath running inside of a unix shell script. During my testing it will error with java.io.FileNotFoundException error, which I know why that is, but when I set in my unix shell script this to see the right exit status of success/fail, it always shows a 0 for success when that isn't really the case. Below is the two lines I have set to capture the exit status and just display that exit status for now.
notifycode=$?
echo $notifycode
I have these 2 lines above on a line right below my java command in my unix shell script. How can I get my unix shell script to show the right exit status if the java classpath command fails? Thanks for any help.That's Java code, it says "End this Java application and send return code 1 back to the shell". As for how the shell gets the return code from the application, that's a question about your shell and not about Java programming, no?
-
Running UNIX shell scripts from a Java app
I want to build a GUI in Java as a front-end to a collection of UNIX shell scripts I have written. Is this possible?
It is possible, but it kinda defeats the purpose of shell scripts no?
-
How to execute unix shell script from Java ...
Hi,
Anyone know how to execute unix shell script from Java?
Suppose I have several shell scripts written in perl or tcl or bash.
I just want to catch the output of that script.
Is there any ready to use module/object for this?
Please let me know, this is quite urgent for my study assigment.
Thanks in advance,
Regards,
meLook up Runtime.exec()
-
Invoking unix shell scripts from java?
Hi,
could someone explain to me how one wuld invoke unix shell scripts from java.
Also, could you invoke Visual Basic scripts from java.
Finally, could you do this from an EJB?
thanks for any help....
suduI just posted a snippet of this solution in the topic about widows commands chech it out it works just fine for unix shell scripts.
--Ian -
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. -
Executing java from unix shell script
Hi, I am trying to execute java program from a unix shell script and the program has a command line parameter. I have tried in ways like
/opt/java1.4/bin/java CollExtractLoadProcess /home/inbox/archive/file_name
/opt/java1.4/bin/java CollExtractLoadProcess "/home/inbox/archive/file_name"
/opt/java1.4/bin/java CollExtractLoadProcess '/home/inbox/archive/file_name'
/opt/java1.4/bin/java CollExtractLoadProcess file_name
No matter how I execute it gives me the following error
Exception in thread "main" java.lang.ClassFormatError: CollExtractLoadProcess (C
ode segment has wrong length)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:537)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:12
3)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)
Could someone please let me know what is the correct way of doing this?
Thanks.Sounds like you either have a corrupt class file or you're using an older version of the JVM to try to execute classe that were compiled for a newer version.
-
Java exec() of UNIX shell script
I have a java application that uses:
p = Runtime.getRuntime().exec( cmdLine);
to execute a UNIX shell script, for example:
#!/bin/ksh
. /export/pc112477/freeware/work1/wsEnv
export PATH=/opt/sfw/bin:/usr/ccs/bin:/usr/bin:/usr/ucb:$PATH
cd /export/pc112477/freeware/work1/usr/src/pkgdefs/SFWnmap
/usr/ccs/bin/make -e ROOT=$ROOT install
RESULT=$?
if [ $RESULT = 0 ]
then
echo "Package source"
cd /export/pc112477/freeware/work1/usr/src/pkgdefs/SFWnmapS
/usr/ccs/bin/make -e ROOT=$ROOT install
RESULT=$?
fi
exit $RESULT
Some times the running of the script locks up depending on how much work the script has to, eg. if the make calls pkgmk for a small package it runs okay but if its a large package it locks up in pkgmk.
The script itself works okay if run directly
Does anyone have any ideas on why this locks up and how I could stop it doing it.
ThanksFor anyone who stumbles across this and needs an answer:
To empty the standard error and output, you need to use getErrorStream() and getInputStream() on the Process object created when you execed your command. Create new InputStreamReaders with the streams from the process, then wrap those with BufferedReaders and read each line with a while loop. This is the basic thing you need to do:
try{
Process proc = Runtime.getRuntime().exec(command);
InputStreamReader isr = new InputStreamReader(proc.getErrorStream());
BufferedReader errReader = new BufferedReader(isr);
String line;
while((line = errReader.readLine()) != null)
<do something with each line of error>
} //end try
catch(<errors>) {
<do something with errors>
} //end catch
What you really should do is put the stream handling in a separate class that extends Thread, create an instance for the error and output streams, and start each one. There is a class called StreamGobbler that does this sort of thing. Look at http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html to find out more about it and read a detailed explanation of different problems with exec(). -
Calling linux / unix shell scripts from APEX
Hi -- I'm doing some prototyping, and would like to try calling a unix shell script on the server from within APEX.
Is this possible? Maybe thru Javascript? Other ways? Not sure if it's possible thru pl/sql.
FYI, I'm attempting to check username/password specified at login to see if it's a valid login
to another database (also specified at login). If there's an easier way to do this, I'd love to hear it!
We're highly motivated to have a single apex app work on multiple databases -- largely because of a lack of
administration resources on the other databases. All databases are accessible via database links from
the apex server (the links are necessary to implement other business rules), and I know I can get
the DML working. Powers that be prefer that Database Account authentication (or a facsimile thereof)
be used. I suspect I'm opening myself up to lots of criticism by disclosing this ... :)
Thanks for any ideas,
CarolR -- If I understand you correctly, a pl/sql process in APEX could invoke a java program on the server. Is that correct?
If so, is there any reason it couldn't just call a unix shell script? Seems they're both just executables recognized by the OS....
I know I called unix scripts from embedded sql a billion years ago, but don't recall the method for doing that. What is
the syntax I'd use in apex / pl/sql?
thanks,
Carol -
Calling a report from unix shell script
Hi,
I had to call a report from unix shell script.
May i know the procedure to accomplish this
Thanks in Advance
A.GopalFirst you should not include the whole path to your report in the call ...
Use like this:
/ora/u01/oracle/v101/as2/bin/rwrun.sh report=an_stati destype=file desname=/ora/u01/oracle/v101/as2/test.pdf desformat=pdf
In $ORACLE_HOME/bin/reports.sh:
1) Verify that you have updated the REPORTS_PATH variable to include your folder where you have the report in question
REPORTS_PATH=/ora/u20/app/qits/env1/run:$ORACLE_HOME/reports/templates:$ORACLE_HOME/reports/samples/demo: ....
2) Verify that the REPORTS_TMP variable is pointing to a valid location and that the oracle user has access to write on it.
After that, post the content of the tracefile located at $ORACLE_HOME/reports/logs/{in-process report server name folder}/rwserver.trc
If no file is present then it means that you need to enable trace in your reports's conf file.... go to the $ORACLE_HOME/reports/conf folder and and locate the .conf file that correspond to your in-process reports server name (as specified in the rwservelet.properties file)... open/edit the file to enable trace logs ..
i.e.
Change the following line:
<!--trace traceOpts="trace_all"/-->
to <trace traceOpts="trace_all"/>
Bounce the reports server and try to run the report again, this time the .trc file should be generated, post the content so that we can take a look.
Maybe you are looking for
-
HP Envy 5660 - Paper jam message
Our HP Envy 5660 printer is 2 weeks old. It was purchased at an electronics chain store. Set-up was easy. No issues until the second week of ownership. An error message popped up reporting a paper jam issue. Followed directions to take out the j
-
No goods receipt possible for purchase order
Hi Experts, Received the goods 10 PC from Vendor on one date, then reversing the GRN on another date, So now GRN total quantity is zero. I am getting error u201CERROR - 036No goods receipt possible for purchase order 43086066 00220 " while again
-
My 3gs phone is not activate please help meee
not support sim after update my phoneee
-
Hello. I use Oracle 8.1.7 at Solaris OS. I have table with CLOB field. This field is indexed. create index IDX_CLOB on QX_CLOB (DATA) indextype is ctxsys.context parameters('filter ctxsys.INSO_FILTER'); I tried to add records in this table from anoth
-
i preordered an album with two songs released on the album already. I downloaded the preordered album on my device from another account who purchased the album. Now, I don't know whether it's going to charge me any money, or that it's not going to do