Linux commands from java

how to run a command at terminal from java program?

I need to run a command at terminal in Fedora 16 from a JAVA program. I tried using

but this just opens the terminal, i am unable to execute any command.

I also tried this:

but still i can only open the terminal, but can’t run the command. Any ideas as to how to do it?

6 Answers 6

You need to run it using bash executable like this:

Update: As suggested by xav, it is advisable to use ProcessBuilder instead:

I vote for Karthik T’s answer. you don’t need to open a terminal to run commands.

You don’t actually need to run a command from an xterm session, you can run it directly:

If the process responds interactively to the input stream, and you want to inject values, then do what you did before:

Don’t forget the ‘\n’ at the end though as most apps will use it to identify the end of a single command’s input.

As others said, you may run your external program without xterm. However, if you want to run it in a terminal window, e.g. to let the user interact with it, xterm allows you to specify the program to run as parameter.

In Java code this becomes:

Or, using ProcessBuilder:

I don’t know why, but for some reason, the «/bin/bash» version didn’t work for me. Instead, the simpler version worked, following the example given here at Oracle Docs.

Источник

How to execute system commands (linux/bsd) using Java

I am attempting to be cheap and execute a local system command ( uname -a ) in Java. I am looking to grab the output from uname and store it in a String. What is the best way of doing this? Current code:

5 Answers 5

Your way isn’t far off from what I’d probably do:

Handle whichever exceptions you care to, of course.

That is the best way to do it. Also you can use the ProcessBuilder which has a variable argument constructor, so you could save a line or two of code

What you are doing looks fine. If your command is only returning a single string, you don’t need the while loop, just store the reader.readLine() value in a single String variable.

Also, you probably should do something with those exceptions, rather than just swallowing them.

I know this is very old but still.

Reading the article here: http://www.javaworld.com/article/2071275/core-java/when-runtime-exec—won-t.html
It is my understanding that you should first read the output and error streams of your executed command and only then waitFor the return value of your process.

I know this questionis very old, but I just wanted to add some information that might come handy to some people.

If you just want to run uname command from java code, better use the System class to get information about the system.

It will not only remove the dependency of running the terminal command, but it will also work independently of the Operating System.

System Class can give you the following information

—> os.version : OS Version
—> os.name : OS Name

—> os.arch : OS Architecture

—> java.compiler : Name of the compiler you are using

—> java.ext.dirs : Extension directory path

—> java.library.path : Paths to search libraries whenever loading

—> user.dir : Current working directory of User

—> user.name : Account name of User

—> java.vm.version : JVM implementation version

—> java.vm.name : JVM implementation name

—> java.home : Java installation directory

—> java.runtime.version : JVM version

ex : If I am running a Linux based system, Say Ubuntu, the following command will give me the information about it.

Источник

Invoking «built-in» Linux commands from Java

This post is a follow-up to a previous post of mine. As has been mentioned in that post, certain Linux «commands» are built-in and give the java.io.IOException when invoked using the Runtime.getRuntime().exec(. ) approach.

Читайте также:  Исправление mbr для windows

history is the only command with this issue that I have been able to find so far but I have no reason to believe that it is the only one.

Question: Is there a way to invoke «built-in» Linux commands, like history from Java?

3 Answers 3

Certain Linux «commands» are built-in

This is incorrect. No such thing.

You’re presumably talking about shell built-ins. There are a million linux variants and a lot of shell variants. Each shell gets to decide their own builtins. Often, things are built-in that nevertheless also exist as an actual executable. For example, I bet on your linux system /bin/ls exists, but ls is also a built-in in most shells. Try running man builtin , it should list the built-ins, probably (all of this is festooned with ‘maybe’ and ‘should’ and ‘probably’ — linux isn’t a single idea, there are many distros, many ways of packing it up. No linux spec demands that man builtin works).

You can run builtins, of course. But, /bin/bash has the code for these builtins, not ‘linux’. You can for example try this code, which is exceedingly likely to work on just about every imaginable flavour of posix, and should do what you actually intend, and should not have significant security issues.

A few things to keep in mind:

Do not, ever, use relative paths in Runtime.exec. Just don’t — it’s unlikely to work, you’re relying on JAVA‘s ability to decode $PATH (when you type, say, curl , and that this runs /usr/bin/curl because /usr/bin is on the path? Yeah that’s bash, not linux. Linux doesn’t know what PATH is.

Always use ProcessBuilder , and use the String. or List version, you don’t want to rely on java splitting on spaces (splitting on spaces? Yup — bash, not linux)

Remember that star expansion is also a shell-ism, except on windows where it isn’t. /usr/bin/imgconvert *.jpg doesn’t work with process builder, because unpacking that * is a thing bash does and java’s process builder won’t do that for you. Thus, pass only the most obvious simple thing possible for arguments. Don’t pass wildcards, don’t pass var substitutions, of any sort.

Anytime you can’t do the job unless you rely on the shell (i.e. you want to run builtins or you need that shell expansion stuff to work), run the shell and ask IT to run the command!

This will run /bin/X if it exists (many builtins do also show up as an executable, even if they are a builtin in most shells), and otherwise, bash. Don’t be tempted to run /bin/sh — whilst that is generally there, you don’t know which shell it is, and it is extremely difficult to write ‘linux shell command-ese’ in a way that it works in all shells. It can be done, but, oof. Takes special skills and considerable testing. /bin/bash exists virtually everywhere, use it. Even if bash as a shell is kinda shite.

Источник

Running Bash commands in Java

I have the following class. It allows me to execute commands through java.

When I run commands, the result of the previous command isn’t saved. For example:

Gives the output:

Why doesn’t the second ‘ls’ command show the contents of the ‘bin’ directory?

7 Answers 7

You start a new process with Runtime.exec(command) . Each process has a working directory. This is normally the directory in which the parent process was started, but you can change the directory in which your process is started.

I would recommend to use ProcessBuilder

If you want to run multiple commands in a shell it would be better to create a temporary shell script and run this.

Of course you can also use any other script on your system. Generating a script at runtime makes sometimes sense, e.g. if the commands that are executed have to change. But you should first try to create one script that you can call with arguments instead of generating it dynamically at runtime.

It might also be reasonable to use a template engine like velocity if the script generation is complex.

Читайте также:  Не запускается windows с ссд

EDIT

You should also consider to hide the complexity of the process builder behind a simple interface.

Separate what you need (the interface) from how it is done (the implementation).

You can then provide implementations that use the process builder or maybe native methods to do the job and you can provide different implementations for different environments like linux or windows.

Finally such an interface is also easier to mock in unit tests.

Источник

How to execute shell command from Java

By mkyong | Last updated: January 3, 2019

Viewed: 841,172 (+2,214 pv/w)

In Java, we can use ProcessBuilder or Runtime.getRuntime().exec to execute external shell command :

1. ProcessBuilder

2. Runtime.getRuntime().exec()

3. PING example

An example to execute a ping command and print out its output.

4. HOST Example

Example to execute shell command host -t a google.com to get all the IP addresses that attached to google.com. Later, we use regular expression to grab all the IP addresses and display it.

P.S “host” command is available in *nix system only.

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

I used the same (similar) code for my ShellWrapper. When I use commands like echo it works fine, but when I use commands like cat it returns an empty String….

can you please share your code using LS EAT AND Cat please

processBuilder.command(“bash”, “-c”, “cat /home/mkyong/web.log”);

processBuilder.command(“bash”, “-c”, “cat /home/mkyong/web.log”);

works fine, but when I pipe a string to Java process, then the

processBuilder.command(“bash”, “-c”, “cat /dev/stdin”);

I am trying to convert avro to json file through java, But it is not working
String output = obj.executeCommand(“java -jar /Users/xyz/Desktop/1server/jboss-as-7.1.1.Final/standalone/deployments/Command.war/WEB-INF/lib/avro-tools-1.7.7.jar tojson /Users/xyz/Desktop/avro/4.avro > /Users/xyz/Desktop/avro/D8EC9CC2A3E049648AFD4309B29D2A0F/4.json”);
But this is not working through java file,

I ran same command through terminal, avro is converted to json

Can you help me to run “java -jar * ” command

Did you find the solution for this ?

As a good practice, I wouldn’t catch Exception e. Just mention the two that need to be dealt with (IOException, InterruptedException) .

Why commands with pattern don’t work? Example: uptime | sed “s/^.* up \+\(.\+\), \+2 user.*$/\1/”

I am not able to execute stat command while fetching date of the file in Java code

I want to connect to DB in unix using java application and i have requirement while trying to connect with go to some specific location and then run java connection code ?
Coudl you please help me on this ?

I am trying to run a python script but it gives me error even if works in the terminal i am running from terminal in the same directory with java what problem can be it says file not found but it works in terminal

i want to write a java class which will be deployed on a server .java class has to perform
1.listing out docker containers and login to particular docker image.
2.after logging it has to execute two commands in docker image

can anyone please help

I try to run a bat file which contain a “pause” command, that lock the java thread.

I need to execute a custom unix command to run a process and it will take around 10sec for the process to run. How to do it.

The Process.waitFor() statement should instead be invoked after the BufferedReader finishes reading the input stream of the Process. This fixes an issue I am having here: the program stucks and never returns but the actual command in my Mac Terminal exits within a second.

Another tip is that it is better to use Process.waitFor(long, TimeUnit) to prevent that the Java program hangs.

I also find that I will need to have Process.waitFor() statement invoked BEFORE the BufferedReader reads the input stream of the Process if I have BufferedReader.ready() added.

As an additional remark, using Process.waitFor(long, TimeUnit) isn’t the complete solution. In my case, the command never returns and it does not print anything in Terminal.
In this case, the BufferedReader.readLine() causes the program to hang. It seems that adding an if condition to check BufferedReader.ready() before BufferedRader.readLine() can solve the issue.

Читайте также:  Windows 10 pro redstone update

I want to execute 2 commands in a sequence.
1. cd D://
2. java -jar -role hub

I tried below code but it tries to execute jar file first and then cd :

ProcessBuilder builder = new ProcessBuilder(“cmd”,”/c”,”start”,”cmd.exe”,”/K”, “java -jar -role hub && cd \”D:\\””);
builder.redirectErrorStream(true);
Process p = builder.start();

any suggestion for first cd should get execute and then .jar?

please read D://foldername and java -jar jarFile

Where do I download the shell package?

To your own machine. lol

let’s say we type ‘mysql’ in command prompt.

c:mysql
then the prompt changes to:
mysql>
now in this we type sql commands.
Can we achieve/automate this with java?

The article would be even better with a note on how to run a shell file sitting in the resources directory.
Thanks for the jump start anyway !

I really like your articles on Java. For this one i guess i could not do as mentioned. I googled and figured out that you need to first connect to the linux box from java and then you can execute shell commands. I could not make the Linux commands run from Java which is on Windows using this code.

Hi How can we add Timeout ?

If I want to check my java version on Mac, I used the “PING” example and replaced the command string with my value i.e. String command = “java -version”;
but the command does not get executed at all. Can you please let me know what am I missing?

Mkyong your tutorials are always straight to the point, bravo.

Hi I am trying to create a Terminal Emulator for Linux using Java… Can you help me by giving a direction..

Thanks in advance…

Access denied. Option -c requires administrative privileges. —-how to fix admin issue on windows 8.1

ok i got it had to read -n yea, thanks

Using array parameter is better, because…when some parameter has blank ( ex. “ABC DE” ) it will be treated as 2 parameters…

Array parameter is more safe… рџ™‚

Sorry…english is not my mother tongue…

The following code allows you to set a timer, restart the timer on keywords, and specify if you want it to be sent to your log or not. This prevents several problems I’ve run into while programming on the command line.

The method is complex, very complex, but it works well and avoids loops in favor of waiting for a synchronized notification whenever possible. It uses three threads. The main thread launches the application and waits. The reader thread processes whatever comes out of the application. The watchdog thread monitors for timeout and gets kicked by the reader thread to restart the timer whenever a keyword is detected.

public String timeoutValueCheckingShellCommand(final String[] cmd, final String[] restartTimerKeywords, final int timeout,final boolean logLevel2) <

StringBuilder sb = new StringBuilder();

ProcessBuilder p = new ProcessBuilder(cmd);

final Process process = p.start();

TimeoutLogger is a place to hold a common object for use through

the various threads. It is used for logging of data, locking the

main thread on the processRunning object, timeout status and

monitoring of if the thread is alive or not.

TimeoutLogger(boolean realtime,Process p)<

private final StringBuilder log = new StringBuilder();

AtomicBoolean timedOut = new AtomicBoolean(false);

AtomicBoolean isRunning = new AtomicBoolean(true);

final Object isRunningLock=new Object();

AtomicBoolean isLogging = new AtomicBoolean(true);

final Object isLoggingLock=new Object();

final Process processRunning;

final Timer watchDogTimer = new Timer(timeout, new ActionListener() <

public void actionPerformed(ActionEvent evt) <

Log.level4Debug(“Watchdog Triggered! Command timed out.”);

synchronized void log(char c)<

for (String check:restartTimerKeywords)<

if (logstring.endsWith(check) && isRunning.get())<

Log.level4Debug(“Timer Reset on keyword “+check);

synchronized String get()<

final TimeoutLogger tl = new TimeoutLogger(logLevel2,process);

/*if the watchDogtimer elapses, the timedOut boolean is set true

and the processRunning object is notified to release main process

/*notify the processRunning object when the thread is complete to

release the lock.

Thread processMonitor = new Thread(new Runnable() <

public void run() <

Log.level4Debug(“Process Monitor done.”);

> catch (InterruptedException ex) <

Logger.getLogger(Shell.class.getName()).log(Level.SEVERE, null, ex);

processMonitor.setName(“Monitoring Process Exit Status from ” + cmd[0]);

reads the output and restarts the timer if required.

Thread reader = new Thread(new Runnable() <

Источник

Оцените статью