It's not a secret anymore!*
The moose likes Java in General and the fly likes calling a linux command Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "calling a linux command" Watch "calling a linux command" New topic
Author

calling a linux command

Arun Sanker
Ranch Hand

Joined: Mar 21, 2007
Posts: 44
Hi Guys,

From Java,I want to change the current user to "su",providing the password as well under linux.Do some tasks and go back to the last user.

For example,I tried something as follows which didnt work!

String cmd[]={"su","password"};
Runtime.getRuntime().exec(cmd);

Finish some tasks with the super user like deleting some files

Go back to the previous user.
//
String cmd[]={"Exit"};
Runtime.getRuntime().exec(cmd);

These are the commands normally used on a Linux shell command.How to do it from a java program.I use Java5.

Thanks
P
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8836
    
    7

Each time you invoke exec() you are starting a new process. What you want to do is exec() the shell and feed that process commands through an output stream (invoke getOutputStream() on the Process object).
Have a look at this article, which explains the pitfalls with exec().


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
Arun Sanker
Ranch Hand

Joined: Mar 21, 2007
Posts: 44
Hi Joe,

Could you post a sample code on how to do it in my case.....

That would be a great Help.....

Thanks
P
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8836
    
    7

There's numerous code samples in the article I linked. Have you read it? What exactly do you have a problem with?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

You can execute a single command with su using its -c flag:

Note: don't ever ever ever execute that! It will destroy your installation. I was just using it as an example

You can use the Process' getOutputStream to send the password to the process.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Arun Sanker
Ranch Hand

Joined: Mar 21, 2007
Posts: 44
Thanks all....Will look into the tutorial.

I also have to find out how to pass the password to the process using the ouput stream and execute it....

Thanks any way....
 
Consider Paul's rocket mass heater.
 
subject: calling a linux command
 
Similar Threads
Open url from Servlet
How to execute a command from Java in Linux?
executing scripts
super user session
trying to run a linux commands from a java app