Execute a linux command on java
Hi i'm trying to execute a c binary on java ,
the binary is Tcpreplay tool , i tried with the class Runtime but it didn't work plz can any one help me thanks a lot
ok these are the details
this is what i tried
import java.io.* ;
public class test1
private static Runtime runtime=Runtime.getRuntime();
private static Process test ;
public static void main (String[] args )
try {
test=runtime.exec("tcpreplay --intf1=eth1 --intf2=eth2 --cachefile=trace-http.cache trace-http.pcap ") ;
catch (IOException ex)
System.out.println("Problem with execution");
another detail is there is no exception reported
Similar Messages
-
Hi all,
Is it possible to execute a DOS command in java? If so, how do I do that?
Also, if it is a Linux machine, may I execute a Linux command in java?
Thanks for your help.
Regards,
BernardFirst, define 'command'.
You can run external programs with Runtime.exec (eg. Runtime.getRuntime().exec("notepad");) but there are a few drawbacks regarding that method.
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html -
How to execute Linux command from Java app.
Hi all,
Could anyone show me how to execute Linux command from Java app. For example, I have the need to execute the "ls" command from my Java app (which is running on the Linux machine), how should I write the codes?
Thanks a lot,You can use "built-in" shell commands, you just need to invoke the shell and tell it to run the command. See the -c switch in the man page for your shell. But, "ls" isn't built-in anyays.
If you use exec, you will want to set the directory with the dir argument to exec, or add it to the command or cmdarray. See the API for the variants of java.lang.Runtime.exec(). (If you're invoking it repeatedly, you can most likely modify a cmdarray more efficiently than having exec() decompose your command).
You will also definitely want to save the returned Process and read the output from it (possibly stderr too and get an exit status). See API for java.lang.Process. Here's an example
java.io.BufferedReader br =
new java.io.BufferedReader(new java.io.InputStreamReader(
Runtime.getRuntime().exec ("/sbin/ifconfig ppp0").
getInputStream()));
while ((s = br.readLine()) != null) {... -
Execute linux command from java
I wanna execute linux command from java, bu the output has error:
Return code = 1
top: failed tty get
The code as:
import java.io.*;
public class Execute {
public static void main(String[] args) {
try {
final Process process = Runtime.getRuntime().exec("top");
new Thread() {
public void run() {
try {
InputStream is = process.getInputStream();
byte[] buffer = new byte[1024];
for (int count = 0; (count = is.read(buffer)) >= 0;) {
System.out.write(buffer, 0, count);
} catch (Exception e) {
e.printStackTrace();
}.start();
new Thread() {
public void run() {
try {
InputStream is = process.getErrorStream();
byte[] buffer = new byte[1024];
for (int count = 0; (count = is.read(buffer)) >= 0;) {
System.err.write(buffer, 0, count);
} catch (Exception e) {
e.printStackTrace();
}.start();
int returnCode = process.waitFor();
System.out.println("Return code = " + returnCode);
} catch (Exception e) {
e.printStackTrace();
}Help please.Your code is probably good to run a program, that does not use terminal capabilities.
Program "top" is a little bit more complicated - you have to run it with a real terminal.
Try to run "xterm -e top". You can find an example how to run an external program
from java code in cnd/gdb module on http://cnd.netbeans.org
For example, take a look at openExternalProgramIOWindow() method on this page:
http://cnd.netbeans.org/source/browse/cnd/gdb/src/org/netbeans/modules/cnd/debugger/gdb/proxy/Attic/GdbProxyCL.java?rev=1.1.2.6.2.5&only_with_tag=release551_fixes&view=markup
It runs a command with external terminal.
Thanks,
Nik -
Unable to execute Linux command from Java
Hi,
I am currently working on a code wherein i need to execute Linux command from Java. Below are some of the query i have.
1) Is there any efficient method of running OS commands from Java, rather than using Runtime and Process method.
2) Below is details of my code which fails in execution
**-- Java Version**
java version "1.6.0"
OpenJDK Runtime Environment (build 1.6.0-b09)
OpenJDK Server VM (build 1.6.0-b09, mixed mode)
-- Program Code ----
Where <path> = Path i put myself
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.*;
public class GetInode{
* @param args
public static void main(String[] args) {
GetInode test = new GetInode();
test.getInode();
public void getInode(){
String command = "/usr/bin/stat -Lt <path>;
System.out.println(command);
Process process;
Runtime rt;
try{
rt = Runtime.getRuntime();
process = rt.exec(command);
InputStreamReader isr = new InputStreamReader(process.getErrorStream());
BufferedReader bre = new BufferedReader(isr);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream());
System.out.println(bre.readLine());
System.out.println(br.readLine().split(" ")[7]);
process.destroy();
}catch (Exception ex){
System.out.println("Error :- " + ex.getMessage());
------Output -------------
/usr/bin/stat -Lt "<path>"
/usr/bin/stat: cannot stat `"<path>"': No such file or directory
Error :- null
Can any one help me what is wrong and why i am unable to run the Linux command from Java.For clarity purpose............i m submitting actual code here
--- Code ---
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.*;
public class GetInode{
* @param args
public static void main(String[] args) {
GetInode test = new GetInode();
test.getInode();
public void getInode(){
String command = "/usr/bin/stat -Lt \"/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt\"";
System.out.println(command);
Process process;
Runtime rt;
try{
rt = Runtime.getRuntime();
process = rt.exec(command);
InputStreamReader isr = new InputStreamReader(process.getErrorStream());
BufferedReader bre = new BufferedReader(isr);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println(bre.readLine());
System.out.println(br.readLine().split(" ")[7]);
process.destroy();
}catch (Exception ex){
System.out.println("Error :- " + ex.getMessage());
--- Output ---
[ratz]s0898671: java GetInode
/usr/bin/stat -Lt "/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"
/usr/bin/stat: cannot stat `"/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"': No such file or directory
Error :- null
-- Linux Terminal --
If i copy the first line from the output and execute on Linux terminal her is the output that i get
[ratz]s0898671: /usr/bin/stat -Lt "/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"
/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt 12003 24 81a4 453166 10000 1c 360466554 2 0 1 1246638450 1246638450 1246638450 4096
Can you just assist me where am i really making mistake.......i was wondering if the command that i pass from Java....can be executed on Linux terminal why is it faling to run from java.........and when i print the Error Stream for process output........it show cannot Stat....... -
Executing the top command through Java in linux
I am trying to execute the top command in Java as
Runtime.getRuntime().exec("top -n 1 >a.log");
But the command is not working in linux only through java.When i run the same command through the prompt it is working fine.Also all other commands are working fine.Is there any issue with top in linux?flounder wrote:
Try reading [this article|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]. If it does not answer your problem then try seaching for other similar articles.
The cited article does provide an answer to the problem since it explains how the shell meta character '>' must be interpretted by a shell. The code as presented does not invoke a shell. -
Executing a linux command through flash lite
Hello All,
i want to know one thing.. : is it possible to execute a linux command through flash lite?
I mean, say, in linux at the command prompt if i want to change the date and time then i will execute command date 082110452009.00 to set
21 August 2009, 11:45:00 .. i want to do this through actionscript2.. first i wil provide a UI asking the user to set date, time, year.. once he clicks OK i want to execute the above command with the user input..
This is because currently i m running this application on an embedded linux device which doesn't have a real time clock.. i mean once i switch off and ON the device the date and time will set back to default value 01 Jan 1970 as it happens in linux..
any suggestions?get the the inputStream of the runtime object after executing the command.
now use the readLine() function until it becomes null.
egs: with reference to ur code.
InputStream is=p.getInputStream()
while(is!=null)
String s=is.readLine();
if the command don't execute try giving the full path also like /sbin/ls -l -
Can I execute MySql's command from java application?
Can I execute MySql's command from java application? And how?
For example :
load data local infile 'D:\\myData.txt'
into table myTable
fields terminated by ';'
lines terminated by '\n';1. get the jdbc driver for mysql from the mysql site at: http://dev.mysql.com/downloads/connector/j/5.0.html
2. follow the installation instructiions... which you'll also find in your mysql manual...
Happy travels. Keith. -
Problem in executing Linux command from Java Programme.
hi everybody,
can anybody help me to solve one problem i have.
i want to capture the output of linux command "grep" in my java programme.but it is not working properly .(maybe this sub-process doesn't have permission to read files)
here is my code and corresponding outputs.
import java.io.*;
public class BSearch
public static void main(String kj[])
try
Runtime rt=Runtime.getRuntime();
String command="grep \"hello\" -r /usr/MyDir ";
Process rtProc=rt.exec(command);
InputStream is=rtProc.getInputStream();
BufferedReader br =new BufferedReader(new InputStreamReader(is));
String line =null;
while((line=br.readLine()) != null)
System.out.println(br.readLine());
br.close();
catch(Exception e)
System.err.println("Error in command "+e);
it finds "hello" pattern only in BSearch.class file although if i fire this command on LINUX prompt it
shows all the files in /usr/MyDir which contain "hello" pattern.
java programme output :
Binary file /usr/MyDir/BSearch.class matches.
linux command output :
/usr/MyDir/one.txt: hello sdfs
Binary file /usr/MyDir/BSearch.class matches.
/usr/MyDir/two.txt: kjsdf hello sdfsdf
will anybody help me solve this problem.It may be a Problem of Catching the Echoes back from the Processes...I have a Program which Captures the Echoes..see if it works
import java.beans.PropertyChangeEvent;import java.beans.PropertyChangeListener;import java.beans.PropertyChangeSupport;import java.lang.ref.WeakReference;/** * Implements a proxy property change listener using a weak reference to avoid memory locking that would occur if it * was a strong reference. To understand this, we hve to understand that the property change listeners themselves are * hilding onto panels and other objects with strong java references. If the panel goes away while we are viewing an * object, we have a circular emory hold situation where the panel cant be collected because it has ahold of the * property and the property cannot because it has ahold of the pane. If we use weak references instead, then the hard * link between the listener and the producer is softened to almost nothing. */public class WeakPropertyChangeListener implements PropertyChangeListener { /** * A poperty change support object is included here so that the listener can remove * himself from the listeners if the reference internally goes to null. */ private PropertyChangeSupport pcs = null; /** Holds the weak reference to the real listener. */ private WeakReference weakRef = null; /** * Constructs a new Proxy object for the given support and listener. * @param pcs The property change support that this object will be using. * @param pcl The real listener. */ public WeakPropertyChangeListener(PropertyChangeSupport pcs, PropertyChangeListener pcl) { if (pcs == null) throw new NullPointerException("pcs"); if (pcl == null) throw new NullPointerException("pcl"); this.pcs = pcs; weakRef = new WeakReference(pcl); } /** @see <{PropertyChangeListener}> */ public void propertyChange(PropertyChangeEvent changeEvent) { Object referrant = weakRef.get(); if (referrant == null) { pcs.removePropertyChangeListener(this); } else { ((PropertyChangeListener)referrant).propertyChange(changeEvent); } } /** Returns true for comparison to referrant or this. */ public boolean equals(Object obj) { if (obj instanceof WeakPropertyChangeListener) return super.equals(obj); else if (obj != null)return obj.equals(weakRef.get()); else return false; }}// snipet public void addPropertyChangeListener(PropertyChangeListener listener) { this.propertyChangeSupport.addPropertyChangeListener( new WeakPropertyChangeListener(this.propertyChangeSupport, listener)); } public void removePropertyChangeListener(PropertyChangeListener listener) { this.propertyChangeSupport.removePropertyChangeListener(listener); } -
Executing linux command from Java code
Hi ,
I have a web application running on JBoss on Linux platform.
I need to execut certain shell command of linux through servlet or JSP, so that I can display the command results on UI.
If you have done something similer sort of thing then please shed some light on it.
TIA,
SachinSorry for the wrong post...please ignore this..
Thanks, -
How to execute a shell command in java?
here, my environment is redhat 7, jdk 1.5.
i don't know how to use the shell command in java.
i want to use this function:
#include <stdlib.h>
int system(const char * string);
please give me some ideas. and Thank you so much if coming with a little demo.i know i should use JNI. because i have to use C lib.
but i have already use JNI to wrapper the original code the cpp code and java code is :
//: appendixb:UseObjImpl.cpp
//# Tested with VC++ & BC++. Include path must
//# be adjusted to find the JNI headers. See
//# the makefile for this chapter (in the
//# downloadable source code) for an example.
#include <jni.h>
#include <stdlib.h>
extern "C" JNIEXPORT void JNICALL
Java_UseObjects_changeObject(
JNIEnv* env, jobject, jobject obj) {
jclass cls = env->GetObjectClass(obj);
jfieldID fid = env->GetFieldID(
cls, "aValue", "I");
jmethodID mid = env->GetMethodID(
cls, "divByTwo", "()V");
int value = env->GetIntField(obj, fid);
printf("Native: %d\n", value);
env->SetIntField(obj, fid, 6);
env->CallVoidMethod(obj, mid);
value = env->GetIntField(obj, fid);
system("preprocess -path sha.c");
printf("Native: %d\n", value);
} ///:~
//: appendixb:UseObjects.java
// From 'Thinking in Java, 2nd ed.' by Bruce Eckel
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
class MyJavaClass {
public int aValue;
public void divByTwo() { aValue /= 2; }
public class UseObjects {
private native void
changeObject(MyJavaClass obj);
static {
// System.loadLibrary("UseObjImpl");
// Linux hack, if you can't get your library
// path set in your environment:
System.load(
"/root/jproj/UseObjImpl.so");
public static void main(String[] args) {
UseObjects app = new UseObjects();
MyJavaClass anObj = new MyJavaClass();
anObj.aValue = 2;
app.changeObject(anObj);
System.out.println("Java: " + anObj.aValue);
} ///:~
i modify this two file which is from TIJ-2edition.
the output is
Native: 2
Native: 3
Java: 3
but what i want to be executed "preprocess -path sha.c" does not work.
i have change the command to, such as "df", "ls" etc. but none of them works
please help me. -
How to create an executable File (Linux-Script) in Java
Hello,
I'm creating a script file in my Java Application.
This script should be executed by hand on my linux system. Therefor the execute flag must be set. But how can I set this flag without executing the "chmod"-command?
Is there any possiblility to do this?
Thanks,
ArminI don't think there is. But you can use Runtime.exec() to execute a chmod command.
-
hi all,
i ve to exectue linux commands in background from within the jsp /servlet/Ejb .what code lines should i write or any other procedure to execute those.
i know u guys must ve done this before.
tcIf you was writing a standa alone Java application that runs top of J2SE, then you could use java.lang.Runtime.exec() apis to call an operating system command. But since you are writing a J2EE component, as per J2EE standard, you don't have the privileges to call Runtime.exec() api because that can lead to security hole. See section #6.2.3 of J2EE 1.4 platform spec (http://java.sun.com/j2ee/download.html#platformspec) for more details about security permission set available to a J2EE component.
Sahoo -
How to execute a Unix Command in java
Hi, Iam trying to execute a unix command on Sun Solaris by passing that command to a java program. How can I achieve this?
Thanks in advance.Have a look at the javadoc around the Runtime.exec() method. If the command is a shell command then you might have to execute a shell as well as the command.
For example, if you wanted to run a unix command 'ls -l > output.txt' the you might have to pass the following string into the exec() method,
"/bin/sh ls -l > output.txt' -
Problem in executing a unix command through java
hi
i'm trying to execute unix command through java
simple shell command like "ls -l >test " but i'm not able to see the result.
there are no error messages.
Code is:
import java.lang.Runtime.*;
class ExecDemo
public static void main(String[] args)
Runtime r=Runtime.getRuntime();
Process p=null;
try
p=r.exec("ls -l > test");
catch (Exception e)
System.out.println("Error executing nedit.");
}can anyone help please.get the the inputStream of the runtime object after executing the command.
now use the readLine() function until it becomes null.
egs: with reference to ur code.
InputStream is=p.getInputStream()
while(is!=null)
String s=is.readLine();
if the command don't execute try giving the full path also like /sbin/ls -l
Maybe you are looking for
-
Usb 6009:connecting the sensor and motor
Hi there, I am new to the labview also the usb-6009. I want to know if I can connect my sensor to the device. The output of the sensor is either analog voltage, pulse width or serial.If I want to use the AN pin, can I just connect the wire to the ADC
-
iCloud in a business. Do all the computers require the same apple ID to share all the files?? Can i have two apple accounts on one device
-
Oracle RDB driver Version 3.01.00.01 Connectivity Issue
I have a SQL Server 2000 extended stored procedure connecting to an Oracle RDB data server via an ODBC connection (using Oracle RDB driver Version 3.01.00.01). The SQL Server 2000 runs on a Windows 2000 Server. This extended stored procedure opens
-
Software mirrored disk raid crashes Mac.
I had two 1TB disks mirrored raid on a Mac Pro (software raid). Took them out and sold the computer. When I connect either one externally to my new iMac they crash my computer. Please help!
-
Mass Re-Read of PP master data
Hi Is there is any transaction or Way to have MASS reread PP master data in Production orders?