• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

calling a linux command

 
Arun Sanker
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9256
9
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
 
Arun Sanker
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9256
9
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Arun Sanker
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic