Working with Unix server... My requirement is to read the name of the file that is there at /a/b/c/node01/d.ear location on a Unix server and I have do the same through a java program. The problem is that the directory a is a restricted directory and is accessible only to certain users. On the Unix side, I first issue a become command like become a, then supply the password and then using cd command, I reach the d.ear directory and then get to see the name of the file.
How do I do all of this via a Java program?
I don't mind if my Java program calls a shell script that accesses the restricted directory and then reach d.ear and fetch the name of the file and returns the same to the java program. Do we have a way of doing this? Maybe issuing the become command inside the script which is called from the Java program and the password which is asked after become command is supplied as a parameter while calling the script???
Is this approach doable? I am very new to Unix commands and JSch library. Kindly provide the code or any other alternate solutions...
Thanks!!!
As I have suggested you already, your become command seems to behave the same way (from an interface/API point of view) as common *nix su or sudo.
So, use the same solution as for those. There are many questions on Stack Overflow covering use of su/sudo with JSch.
There's even an official JSch example Sudo.java:
http://www.jcraft.com/jsch/examples/Sudo.java.html
In short:
Execute become command
Feed a password to its input
Assuming the become starts a new shell (as su or sudo do), you feed the commands to be executed in the elevated environment to become input (the same was as the password).
I am using Runtime.exec() to run an executable file. I have been researching and found out that there could be security concerns when using this in a application. Are there any security concerns when using Runtime.exec() to run an executable file?
#Jeanne Boyarsky: Apparently you cannot inject into Runtime.exec() in the way you mentioned, unless Runtime.exec() first spawns a shell (cmd.exe on Windows or sh/bash/csh/ksh on Linux) to run the command. Here is a good link which talks about this.
I wrote a small program to test this out. It takes a command as user input. So if I enter 'pwd' (Linux system) it will print the current directory to the System Console. This works perfectly.
If however I try and run two commands, as is permitted in Linux, such as pwd;id it throws an Exception straight away. The Exception thrown is as follows.
javax.faces.el.EvaluationException: java.io.IOException: Cannot run program "pwd;ls": error=2, No such file or directory
Having said that though there is a situation when this can be a problem. If I have a piece of code as follows:
Process proc = runtime.exec(cmd);
... the user could provide an input of sh -c pwd;id, thus causing a shell to run and then chaining commands inside it.
So in short, best to not use Runtime.exec() if you can help it. If you MUST use it, make sure you canonicalize all user input and allow only specific characters and commands.
Here is a good read on how to write secure code.
The biggest one I can think of is Command Injection. YOu want to whitelist what gets run so someone can't run "rm /" via your Runtime.exec. There are more ways for this to happen than you might think. For example what if a "directory" name is passed in as "foo; rm -r ; ls".
Another one - if this is a web application - is that the permissions for the application (and therefore your Runtime.exec() command line aren't the same as what the person hitting the web page has. Which means the person could delete your Tomcat or insert data into a database or ...
I am starting a server application (normally to be started from the Unix command line) by using Runtime.getRuntime().exec("path/mmserver"). My problem is now that as long as my Java program, which started that server runs, the server is correctly accessible (from command line and other programs). But when my Java program exits the sever is not accessible anymore (the process of the server is still running). I just get such a error message when trying to access the server: "Error: permission_error(flush_output(user_output),write,stream,user_output,errno(32))".
The server is a blackbox for me.
I am just looking for other ways to start a new process. And maybe someone has a hint why I get that permission error (even if one doesn't know what that server exactly is ... you rather won't know it).
I'm guessing your server program is trying to write to standard output or perhaps standard error (System.out / System.err in Java terms) which it implicitly inherited from your Java program but which turn into pumpkins when your Java program goes away.
A simple solution might be for your Java program to exec a shell script which starts your server as a background process (using START (Windows) or & (Unix)) with explicitly redirected I/O streams.
The Java library has recently gotten some nice updates to the Process class (I think) that allow you to do a lot of fiddling with the streams, but I don't have much experience there so I can't offer a detailed suggestion.
EDIT: My suggestion from the middle paragraph. Untested, sorry!
File server-runner.sh:
#!/bin/bash
/path/mmserver >/dev/null &
You'll need to chmod +x server-runner.sh, of course.
Then, from your Java program, you exec the script server-runner.sh rather than your mmserver.
If you want to kill mmserver, you'll have to find it in ps -ux and use kill on the process number.
Is there a way to find the width of the console in which my Java program is running?
I would like this to be cross platform if possible...
I have no desire to change the width of the buffer or the window, I just want to know its width so I can properly format text that is being printed to screen.
There are no reliable cross-platform solutions to this problem. Indeed, there are situations where it is not possible to know what the real console width is.
(See other answers for approaches that work some of the time and/or on some platforms. But beware of the limitations ...)
For example, on a Linux system you can typically find out the notional terminal dimensions from the LINES and COLUMNS environment variables. While these variables are automatically updated when you resize some "terminal emulator" windows, this is not always the case. Indeed, in the case of a remote console connected via telnet protocol, there is no way to get the actual terminal dimensions to the user's shell.
EDIT: Just to add that if the user changes the dimensions of his/her xterm on Linux after launching a Java app, the Java app won't be notified, and it won't see the new dimensions reflected in its copy of the LINES and COLUMNS environment variables!
EDIT 2: My mistake: LINES and COLUMNS are bash shell variables, and they are not exported to the environment by default. You can "fix" this by running export COLUMNS LINES before you run your Java application.
Actually, a Java library already exists to do this in Java: JLine 2. (There's an old version on SourceForce, but that link to GitHub seems to be the latest.)
This worked for me under Linux (Mint 14) and Windows (I don't know what version), using JLine 2.11:
terminalWidth = jline.TerminalFactory.get().getWidth();
JLine promises to work on Mac, too.
I've found that it returns bad widths (like 1!) under the Eclipse console (but even Java's native Console doesn't work under Eclipse!), and, unfortunately, under Cygwin. But I've worked around this with code that checks for unreasonable values (< 10) and just uses 80 in those cases.
Update for JLine 3 (per Mark—thanks, mate!):
terminalWidth = org.jline.terminal.TerminalBuilder.terminal().getWidth()
There's a trick that you can use based on ANSI Escape Codes. They don't provide a direct way to query the console size, but they do have a command for requesting the current cursor position. By moving the cursor to a really high row and column and then requesting the cursor position you can get an accurate measurement.
Combine this with commands to store/restore the cursor position, as in the following example:
Send the following sequences to the terminal (stdout)
"\u001b[s" // save cursor position
"\u001b[5000;5000H" // move to col 5000 row 5000
"\u001b[6n" // request cursor position
"\u001b[u" // restore cursor position
Now watch stdin, you should receive a sequece that looks like \u001b[25;80R", where 25 is the row count, and 80 the columns.
I first saw this used in the Lanterna library.
Update:
There are really four different ways that I know of to achieve this, but they all make certain assumptions about the environment the program is running in, or the terminal device/emulator it is talking to.
Using the VT100 protocol. This is what this solution does, it assumes you are talking over stdin/stdout to a terminal emulator that honors these escape codes. This seems like a relatively safe assumption for a CLI program, but e.g. if someone is using cmd.exe this likely won't work.
terminfo/termcap. These are databases with terminal information, which you can query for instance with tput. Operating system dependent, and assumes you are connected to a TTY device. Won't work over ssh for instance.
Using the telnet protocol. Telnet has its own affordances for querying the screen size, but of course this only works if people connect to your application via the telnet client, not really an option in most cases.
Rely on the shell (e.g. bash), this is what solutions that use COLUMNS/ROWS variables do. Far from universal, but could work quite well if you provide a wrapper script for your app that makes sure the necessary env vars are exported.
Edit: See #dave_thompson_085's comment about ProcessBuilder, as that's almost certainly a better approach.
Another answer mentioned running tput cols in a script before you start your command. But if you want to run that after Java has already started, using Runtime.getRuntime().exec(), you'll find that tput can't talk to your terminal, because Java has redirected stdout and stderr. As a not-at-all-portable workaround, you can use the magical /dev/tty device, which refers to the terminal of the current process. That lets you run something like this:
Process p = Runtime.getRuntime().exec(new String[] {
"bash", "-c", "tput cols 2> /dev/tty" });
// Read the output of this process to get your terminal width
This works for me on Linux, but I wouldn't expect it to work everywhere. It will hopefully work on Mac. It definitely won't work on Windows, though it might with Cygwin.
Java 6 has a class java.io.Console, but it unfortunately lacks the functionality you're asking for. Getting the console window width is not possible with the standard Java library and pure, cross-platform Java.
Here is an alternative Java console library which allows you to get the screen size, but it includes a Windows-specific DLL. You might be able to take the source code and compile the C part into a Linux or Mac OS X shared library, so that it will work on those platforms as well.
I have been working on this problem before. I use a couple of different techniques. However it is difficult to have a truly cross platform solution.
I tried doing try something like this:
String os = System.getProperty("os.name").toLowerCase();
//Windows
if(os.contains("win")){
System.out.append("Windows Detected");
//set Windows Dos Terminal width 80, height 25
Process p = Runtime.getRuntime().exec("mode 80, 25");
}
//Mac
if(os.contains("mac")){
System.out.println("Macintosh Detected");
//... I dont know...try Google
}
//Linux
if(os.contains("linux")){
System.out.println("Linux Detected");
You can read/test and append "export COLUMNS" to the .bashrc file in every Linux users home directory with the String.contains("export COLUMNS") method and the user.dir property.
That would allow you to get the columns to load up every time the java app starts up.
Then I would pass it to a temp file. Like this:
try {
ProcessBuilder pb = new ProcessBuilder("bash","-c","echo $COLUMNS >/home/$USER/bin/temp.txt" );
pb.start();
}catch (Exception e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
Another option you have is to execute yor Java.jar with a bash script at startup. Inside the script you can use "tput cols" to get the width. Then pass that value to your Java app as a String[] arg.
Like so:
//#!/bin/bash
//#clear the screen
clear
//#get the console width and height
c=$[$(tput cols)]
l=$[$(tput lines)]
//#pass the columns, lines and an optional third value as String[] args.
java -jar ~/bin/Plus.jar $c $l $1
why is this such a difficult task with Java? Obviously a good place to write a good API. I guess we could try Apache.commons.exec as well?
For me, the only way to get an idea of the terminal window (still not correct when the window resizes) is to use a command like
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "mode con");
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
When run without the cmd.exe part, it shows that the command could not be found. Also note the redirectError part. If not used then the Java output size will be used, not the actual one. Only with this combination it was possible to grab the actual size.
Python seems to have a good solution: 11.9.3. Querying the size of the output terminal. I wouldn't hold my breath waiting for this to be available in core Java, but you might be able to use Jython to make the Python functionality available.
Scenerio: I'd like to run commands on remote machines from a Java program over ssh (I am using OpenSSH on my development machine). I'd also like to make the ssh connection by passing the password rather than setting up keys as I would with 'expect'.
Problem: When trying to do the 'expect' like password login the Process that is created with ProcessBuilder cannot seem to see the password prompt. When running regular non-ssh commands (e.g 'ls') I can get the streams and interact with them just fine. I am combining standard error and standard out into one stream with redirectErrorStream(true); so I am not missing it in standard error...When I run ssh with the '-v' option, I see all of the logging in the stream but I do not see the prompt. This is my first time trying to use ProcessBuilder for something like this. I know it would be easier to use Python, Perl or good ol' expect but my boss wants to utilize what we are trying to get back (remote log files and running scripts) within an existing Java program so I am kind of stuck.
Thanks in advance for the help!
The prompt might only be shown when ssh is connected to a TTY, which it isn't in the case of Java.
There's probably a way to supply the password on the command-line in your ssh application. That will be the way to get past the prompt.
Alternately, consider connecting directly to the host server from native Java code rather than running an external application. There's a million libraries that will do this.
Rather than using an external ssh program, why not use a Java ssh library:
Trilead
JTA
Are two I found with google - that'll avoid the problem that openssh will be working very hard to prevent entering the password on stdin - it'll be opening the terminal directly. expect has to work very hard to simulate a tty in order to work.
Why not use a Java ssh client? This one is BSD-licensed, and there are more clients listed here.
Most security minded programs don't use stdin/stdout for capturing passwords, they capture the TTY or some equivalent method.
Echoing others' suggestion to use a Java SSH library. But wanted to comment on Cohen's response. Sending your password over the command line when establishing the connection is insecure and also not permitted by many sshd servers (based on configuration).
You might want to look into setting up keys for this, so you can perform ssh commands between the machines without a password.
Basic steps
- use openssh to create a keypair (I've done RSA but I know there's a better method now)
- create a .ssh directory in your home folder on the SOURCE machine
- create a .ssh directory in your home folder on the TARGET machine
- keep your private key in your source machine's .ssh folder
- copy your public key into a file called authorized_keys in the target's .ssh folder
Some instructions can be found here
You can run commands using edtFTPj/PRO, as well as performing file transfers via SFTP. It's Java.