Linux command from java

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

Читайте также:  Как поставить mac os mojave

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

Источник

Как запустить команды linux в коде java?

Я хочу создать diff из двух файлов. Я попытался найти код на Java, который это делает, но не нашел для этого простого кода/ кода утилиты. Поэтому я подумал, что если я могу каким-то образом запустить команду linux diff/sdiff из моего java-кода и заставить ее вернуть файл, в котором хранится diff, тогда было бы здорово.

предположим, что есть два файла fileA и fileB. Я должен иметь возможность хранить их diff в файле с именем fileDiff через мой java-код. Тогда извлечение данных из fileDiff не будет крупная сделка.

10 ответов

можно использовать java.lang.Runtime.exec для запуска простого кода. Это дает вам обратно Process и вы можете прочитать свой стандартный выход сразу без временно хранить выход на диске.

например, вот полная программа, которая продемонстрирует, как это сделать:

при компиляции и запуске он выводит:

как и ожидалось.

вы также можете получить поток ошибок для стандартной ошибки процесса, и выходной поток для стандартного ввода процесса, достаточно запутанно. В этом контексте входные и выходные данные реверсируются, так как это input С процесс к этому (т. е. стандарт выход процесса).

если вы хотите объединить стандартный вывод процесса и ошибку из Java (в отличие от использования 2>&1 в фактической команде), вы должны посмотреть в ProcessBuilder .

вы также можете написать файл сценария оболочки и вызвать этот файл из кода java. как показано ниже

напишите команды linux в файле сценария, как только выполнение закончится, вы можете прочитать файл diff на Java.

преимущество этого подхода заключается в том, что вы можете изменить команды без изменения кода 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.

Читайте также:  Matlab для windows 10 64 bit

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 bash command with sudo privileges in Java?

I’m using ProcessBuilder to execute bash commands:

But I want to make something like this:

How to pass superuser password to bash?

(«gksudo», «gedit») will not do the trick, because it was deleted since Ubuntu 13.04 and I need to do this with available by default commands.

gksudo came back to Ubuntu 13.04 with the last update.

6 Answers 6

I think you can use this, but I’m a bit hesitant to post it. So I’ll just say:

Use this at your own risk, not recommended, don’t sue me, etc.

Edit /etc/sudoers with visudo and grant your user a NOPASSWD right for a specific script:

username ALL=(ALL) NOPASSWD: /opt/yourscript.sh

My solution, doesn’t exposes the password in the command line, it just feed the password to the output stream of the process. This is a more flexible solution because allows you to request the password to the user when it is needed.

Do not try to write a system password plainly in a file, especially for a user that have the sudo privilege, just as @jointEffort answered, issued privilege should be solved by system administrators not by app writers.

sudo allow you to grant privileges for specific command to specific user, which is precisely enough, check this post

and you can choose to manage the privilege in a separated file other than the main sudoers file if you want just append #includedirs /etc/sudoers.d/ in the main /etc/sudoers file(most Linux distributions have already done that) and make a file like ifconfig-user with:

Читайте также:  Windows издает странные звуки

Another thing, remember to edit the config file with visudo in case you lost control of your system when there is syntax error.

Источник

How to run the Linux «cd» command from Java?

I want to write a Java program to delete

12 directories or files which are under my home directory. I am able to do this by using

But I have to run this command 12 times or I can keep it in loop. What I really want is to have a file in my home directory that contains the names of all the directories and files to delete in it. My Java program should go to the home directory, read the file, and delete all the specified files.

I am stuck at the very first step – I am not able to cd to the home directory. Please let me know how can I achieve this.

Thanks for all of your replies.

But, here I don’t really want to use the Java util classes rather I want to learn a way using which I can run Linux commands in my Java class. Being a deployment Intern, I have to reset the environment every time before deploying a new environment for the customer. For this, I repeatedly use some basic Linux commands. I can write a shell script to do this but for this time, I want to write a Java class in which I can put all these Linux commands and run from one class.

The commands which I use are:

  1. kill all java processes which are started by the admin ONLY – for this I need to use multiple Linux commands with “pipe”
  2. Remove all 12-directories/files from home directory
  3. stop some services (like siebel, etc.) – for this I need to go under the particular directories and run ./shutdown.sh or ./stop_ns, etc.
  4. run some database scripts – to reset the database schemas
  5. again start the services – same as step 2 except this time I need to run ./start_ns, etc.

I really appreciate if you can let me know a. How can I navigate into a directory using Java code b. How can I run multiple Linux commands using pipe using Java code

Источник

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