I'm trying to write Java code that executes some terminal commands. The code should execute this command sudo mount -o loop system.img system. But there are several problems. First, to execute this command I have to be root. I know that I can be by sudo su, but how can I stay as root when I close the terminal window? If I use the command sudo mount -o loop system.img system how can I provide the password in the Java code?
The second issue is: can I execute the command as below?
File f2 = new File("/home/user1/Desktop/aDirectory");
String[] commands = new String[]{"sudo mount", "-o", "loop", "/home/user1/Desktop/aDirectory/system.img"};
Runtime.getRuntime().exec(commands, null, f2);
I think I can't. So how can I do it? Any ideas?
Notes: system.img is a compiled Android os file. and the system is an empty directory. The thing I'm trying to do is mount the system.img file into the system directory.
Programs like sudo read the password directly from the terminal device, not from stdin, so this is unfortunately not a trivial thing to do. I'm not sure if this is realistic for Android or not, but on a general UNIX system the easiest solution is to use expect, which is a library for simulating a terminal and thereby automating these kinds of interactions. It's often used as a standalone program embedded in Tcl, and I've thrown together systems in which Java launched expect to talk to tools like sudo, and it works fine.
expect includes a sort of declarative scripting language that tells it how to run another program and how to react to that program's output.
What you would do is use Runtime.exec() to execute the expect program, supplying a script that just runs "sudo mount", watches for the password prompt, and provides the password. The script would probably just look something like (G4rb4geB4rg3 is the password):
spawn sudo mount -o loop /home/user1/Desktop/aDirectory/system.img
expect "password:"
send "G4rb4geB4rg3\r"
expect eof
The problem was solved, by using shell script.
I wrote a script includes just this line :
echo myPassword | sudo -S mount -o loop system.img system
then I run it in my java code, such :
Runtime.getRuntime().exec("sh 1.sh");
I'm pretty sure 'sudo' and 'mount' would be separate, since it's not a single executable you're invoking. Also, if you start sudo with the -S command line switch it can take the password directly from stdin, so you just need to start the process and pass in whatever the password's configured as to the input stream.
Related
I want my directory to give executable permissions (by default) to all the shell scripts which are going to be created in that directory after I run my Java program. I tried the following commands:
setfacl -d -m group:name:rwx /path/to/your/dir
find ./ -name "*.sh" -exec chmod +x {} \;
The first one is not showing any response while the second one works fine but I have to execute this command manually in terminal after my Java program has created all the scripts. This is not what i seek. I want this thing to be automatic. Here is what I am trying to achieve:
My Java program creates the .sh files in a directory.
Now the program would try to execute this script file.
Here is a Java code snippet which shows how it is going to execute the script files:
ExecuteShellComand obj = new ExecuteShellComand();
String command2 = "./script.sh";
String output2 = obj.executeCommand(command2);
It doesn't run unless I give the executable permissions to the script.sh. How do I do it? Is there any way around it? If I am not doing something in a way it should be done, feel free to give your suggestions. Thanks
Default ACL permissions are masked by the file's creation mode as specified in open and mkdir syscalls.
Since files are usually created with a default mode of 0666, execute permissions will be masked instead of inherited.
It's the responsibility of the program that creates the files to create them with the right permissions. If you set the permissions correctly when creating the scripts, you won't need ACL or chmod at all. The best way to fix this would be for your program to set the mode in the open call to 0777.
Java appears to have Files.createFile for this. Additionally, you have a more fuzzy File.setExecutable to do it after the fact, which is not Unix canonical behavior, but probably fine for your use case.
Environment: mac
Precondition: I already configured 'adb' full path to my bash_profile. and when I tried type 'adb' in my terminal, it is working.
But, I tried to exec 'adb' command from java, 'adb' is not working, instead I need to pass the full adb path to make it work.
I guess this is probably something to do with the bash_profile setting, anyone know the exact reason for this issue?
Runtime.getRuntime().exec() runs /bin/sh -c <command>. If this is or points to a bash shell on your system: A non-interactive bash does not read .bash_profile unless explicitly (--login) told to do so.
From the documentation:
When Bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
It's a little convoluted, but non-interactive, non-login bash instances don't read the profile files.
Your path settings does not get picked up by the subshell (which is actually /bin/sh which might not even be bash at all).
If you want, you can add the path to adb system wide by adding an appropriate entry to to /etc/paths.d.
I have written a java program with jar file. The java program is to update status of linux server so it need to keep running, but the linux server is in data center, so I need to remote to server to open the program. I use ssh to login linux server. Use command of "java -jar file.jar" to run the program.
However, the java program of the linux server will close if I close the terminal in my computer. Since I cannot keep opening my computer, I wanna know how to open the java programming without holding my computer terminal.
you need to use nohup to keep the program running after you log out.:
server:~name$> nohup java -jar file.jar &
this will keep your program running
Two ways
One
nohup java -jar file.jar &
Another
java -jar file.jar &
In both cases your process will go in background however the process will terminate in the second approach when shell terminates in second case.
If this program is intended to be running on all your machines for monitoring purposes, you should be running it as a service from your server's init system (systemd for most systems these days). You can use the Java Service Wrapper or jsvc or write your own init script.
Another solution apart from the proposed one:
screen -d -m java -jar your.jar
You will then have a detached screen with your java command in it. List with screen -l, reattach with screen -D -RR <screenid_obtained_via_screen_-ls>
I have a java application and I want to run a script whenever it experiences and OutOfMemoryException
This works great:
$ java -server -XX:OnOutOfMemoryError="./oom_script %p" TestOOMClass
Unfortunately my application is run by a bash script in production. The script boils down to this:
cmd='java -server -XX:OnOutOfMemoryError="./oom_script %p" TestOOMClass'
##does a lot of checking and cmd building here
exec -a app ${cmd}
When run like this java never respects the double quotes and thinks %p is the class. how do I prevent this? I've tried double escaping but that doesn't work.
Since your program is run as a shell script, I would suggest putting this as the first line in your shell script after the shebang:
set -xv
Then, in the crontab, put 2>&1 at the end of the command line, so STDERR and STDOUT are merged. Crontab usually emails out the STDOUT of a command to root, so you can see what the output is. If not, then apend the following to the end of the command in your crontab:
> /somedir/output.$$ 2>&1
Make sure somedir exists, and after crontab runs your command, you'll see the verbose and debug output. Each line in your shell script will be displayed before it is executed -- both as written and as the shell actually interprets it.
The set -xv becomes very useful in debugging any sell script. There could be all sorts of environmental issues involved between the cronjob and the script running under your login. You might even find a shell issue. For example, crontab usually executes shell scripts in Bourne shell and you probably have Bash or Kornshell as your default shell. Whatever it is, you'll usually find out the issue very quickly when you turn on verbose/debug mode.
You don't even have to do this to the entire script. You can put set -xv anywhere in your script to turn on verbose/debug mode, and set +xv to turn it off.
I could make several pious high minded recommendations (use quotes, don't assume environment things, prefix your command line with "bash -c" to make sure you're using the right shell, etc.), but this would be guessing what could be wrong. In order to really debug this issue, I would need to see the machine, know the OS, see your entire shell script, and understand the entire environment. And, the first thing I would do is add set -xv in your shell script.
Quotes and escaping is an art. I would suggest you add echo ${cmd} before calling exec so you can see what it looks like then.
I would suggest using
cmd='java -server -XX:OnOutOfMemoryError=\\"./oom_script %p\\" TestOOMClass'
instead (untested). You need it to look like \" when being echoed.
an alternative i suggest (to bypass the problem, not solve it indeed) is to rung and bash script and access the $PPID:
PPID The process ID of the shell's parent. This variable is readonly.
then kill the process with that ID (please bare in mind that is an untested suggestion)
I need to call Cygwin from Java code ( example : to call make command in Cygwin from Java app which run on linux and windows ).Does anybody have experience with this problem ?
I think you have to differentiate youre code for linux and windows
on linux simply execute the command
on windows lauch your command in cygwin with
C:\cygwin\bin\bash.exe --login -i -c <cmd>
note: you may use apache commons exec to lauch an external command from java
Use ProcessBuilder from Java:
http://download.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
You will need to make sure your path/environment is set up properly, but that depends on your machine and set up.
Also, note that many cygwin "capabilities" (e.g., less, awk, sed, etc) are simply binaries (executables) that you can call directly -- no need for the bash shell to facilitate access to those. Look at the actual files in wherever your bin folder is (usually c:/cygwin/bin) and try calling those directly from ProcessBuilder. If you need to actually leverage the shell (e.g., pipes, variables, globbing, etc) then that's a different story -- you would then integrate with the bash.exe file itself (check the man page for usage info).