Sudo or su command using java problem

hi im having a bit of trouble with the sudo or su command using java:
e.g.
try { Process myProcess = Runtime.getRuntime().exec("sudo ....ect");  my lil application just crashes ever time i try using this command. i know you usually have to type
password in terminal to get privileges. but since my application needs output of certain commands
i need a way to get round.
i was thinking of trying to input the password some how but im pretty much stuck as to how to do it.
thanks for the help

prometheuzz wrote:
sabre150 wrote:
:-( So I'm dumb?You probably know I wasn't serious, but just for the record: note the smiley when I posted it.:-) of course! When all other tools won't do the job then I use a hammer.

Similar Messages

  • Running unix command using java shows error

    Hi All,
    I am trying to run UNIX move command using Java exec method but its throwing error, unable to rename. Here below is the code i am trying to run to move all files from one directory to another directory. source and destination directory exists.
    public class Demo
        public static void main(String args[])
            try
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("mv /home/demo1/* /home/demo2");
                int exitVal = proc.waitFor();
                System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
                t.printStackTrace();
    }if i give "mv /home/demo1 /home/demo2" in exec method, its working, with * character its giving problem.
    Please help me in resolving the problem.
    Thank you

    Characters like *, >, &, |, etc. are interpreted by the command shell--that is by the bash, zsh, etc. programs. When you execute a command with ProcessBuilder or Runtime.exec, you're not going through one of those shells, so their interpretation of those characters is not available.
    In your code, the character * is being delivered directly to the mv command (which doesn't think * is anything special), as opposed to being turned into a list of files and directories as it would be when it's interpreted by the shell. The mv command doesn't know anything about the * character being special.
    If you want to have those shell interpretations, you need to execute the command through a shell. One example is like so, but a) you'll want to read up on the methods in exec() that take arrays of String, and b) you'll want to read up on ProcessBuilder, and c) you'll need to check your shell's man pages to see the exact syntax and arguments.
    runtime.exec("/bin/bash -c 'mv x/* y'");

  • Execute unix command using java

    Hello
    Can we execute a unix command using java? If it is how we can execute. Is this affect the performance of the program.
    Thanks

    I tried what you said. But its not working and returning error message,
    java.io.IOException: CreateProcess: ls -a error=2
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(Unknown Source)
         at java.lang.ProcessImpl.start(Unknown Source)
         at java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
    If i try this statement,
    Runtime.getRuntime().exec("c\windows\notepad");
    It is working fine.
    Any idea about this.
    Plz ...........

  • To run a command using java code

    hi all,
    There is a command
    "java -jar selenium-server.jar -interactive"
    which i am running through command prompt after going to D:\MyFolder\Examples .
    i want to execute this command using java code .please help

    subratjyetki wrote:
    please answer in detail or if posible can u give the code for thisThe detail is given in the reference. Why don't you read it?
    I could give you the code but it will cost you ?100 per hour.

  • Spanish characters getting garbled while executing command using Java code

    Hi,
    I try to execute a command using java code. output of the command contains spanish characters. Few of these characters getting garbled after the command execution.
    Runtime r = Runtime.getRuntime();
              Process p = null;
    String pgm="ipconfig /all";
              try
                        p = r.exec(pgm);
    BufferedReader br=new BufferedReader(new InputStreamReader
                                  (p.getInputStream()));
    while((val = br.readLine()) != null){ System.out.println(val);
              catch (Exception e)
                        return (null);
    I tried to run the code using -Duser.language=es -Duser.region=ES -Dfile.encoding=Cp850, but this did nt help. I could see the outputs properly in command prompt,
    If i redirect the output to a text file , it is getting garbled,
    Please let me know to solve this issue.

    884543 wrote:
    Hi,
    I try to execute a command using java code. output of the command contains spanish characters. Few of these characters getting garbled after the command execution.
    Runtime r = Runtime.getRuntime();
              Process p = null;
    String pgm="ipconfig /all";
              try
                        p = r.exec(pgm);
    BufferedReader br=new BufferedReader(new InputStreamReader
                                  (p.getInputStream()));
    while((val = br.readLine()) != null){ System.out.println(val);
              catch (Exception e)
                        return (null);
    I tried to run the code using -Duser.language=es -Duser.region=ES -Dfile.encoding=Cp850, but this did nt help. I could see the outputs properly in command prompt,
    If i redirect the output to a text file , it is getting garbled,
    Please let me know to solve this issue.Set the character set to UTF-8 to your InputStreamReader, for More details on usage refer the java api :
    http://download.oracle.com/javase/6/docs/api/java/io/InputStreamReader.html

  • Creating Tail Command using Java

    Hi,
    When I was searching for tail command for windows I got site: http://dotnetjunkies.com/WebLog/johnwood/archive/2005/01/05/41694.aspx I think program thay have mentioned is writen in some .NET program.
    So I was thinking do we have any class in Java some thing similar to FileSystemWatcher so that I can write tail command using java.
    Thanks,
    Ram Das

    Virtual Programmer is in the to share the directory
    over the Internet.No, that's a file/web server. :) I see, it's a Microsoft term.

  • I want run some command using java

    hi all,
    i want run command using java code.
    from cell prompt when i run this command 'mysqldump test > /home/DBNAME.sql'
    it will create DBNAME.sql file.
    but i want to run this command using java code
    i tried the following code but it did not work.
    is any other way is their?
    try {
                   Runtime.getRuntime().exec("setxkbmap nudi");
              } catch(IOException ioe) {
                   ioe.printStackTrace();
    thanks in advance
    daya

    hello,
    thanks for replay
    i am sorry the above code should be like this.(the above code is working fine)
    public class ExportTest{
         public ExportTest(){
              try {
                   Runtime.getRuntime().exec("mysqldump test > '/root/DBNAME.sql'");
              } catch(IOException ioe) {
                   ioe.printStackTrace();
              }catch(Exception e){
                   e.printStackTrace();
         public static void main(String args[]){
              new ExportTest();
    }when run above class, it not creating DBNAME.sql file.
    when run in command prompt it creating DBNAME.sql
    ($ mysqldump test > /root/DBNAME.sql)
    but i want to run this command from java code, that's way tried to do using above
    code, but it won't create DBNAME.sql
    is it wrong what i am doing? or any other way?
    thanks inadvace
    daya

  • Running System Commands using Java

    HI,
    I am developing an application using java which requires some system commands to be run.For example i have to write a java function which can program the windows scheduler to run a particular executable at some time & another one to initiate an ftp.I however do not know how to execute the corresponding commands from java.Is there any way or some specific api(similar to the system command in c) that i can use to perform these operations.I am using j2sdk 1.4.0_01 on a win 98 machine to develop the application.

    See [url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html]java.lang.Runtime

  • Call external command using java

    Hi !
    I want to call a external command in linux system with java .I am new to this ,so need help ..
    Suppose a command is known as "foobar" in linux .generally executed by
    $./foobar
    What I was thinking is to call this using java and return the output to a file .
    how do I do this ?

    Take a look at ProcessBuilder.

  • Running Dos Command using Java

    How do i run a particular Dos command using a simple java class?

    Process process = Runtime.getRuntime().exec( ... );
    Search the forum. There are plenty of examples.

  • Run An OS Command Using Java?

    I want to write a java class that does some Unix system maintenance. In particular, I want to read some data out of a database and then do some calculations to figure out which files in particular can be tarred and zipped. The database part is already handled (in other words, I can identify the files I want to take action on) but I'm not sure how to run an operating system command (e.g. "tar cvzf myfile file1 file2 file3") using java.

    Read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    %

  • Send SSH Command using java

    Ok. I hate this, but this is they way they have implemented it. I do not have access to the server code that this applicatio sits on, so I am only able to send specif commands with java through there interface. One of the commands for example is: password_reset "username" "new_password", there is also search_user "username", and uinfo "username". One of the command I really want to send is the password_reset command, but before I can do that I need to establish a ssh connection with username, and password. Not the username or password of the user that I am resetting, but the username and password of a user that has the privilege to reset passwords.
    anyway someone said I could just user the execCommand("password_reset " + username + " " + password ) command. If that is true then How do I do the ssh connection? any examples would be great. I have one, but it is not working for some reason.
    Here is the code:
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import com.trilead.ssh2.ChannelCondition;
    import com.trilead.ssh2.Connection;
    import com.trilead.ssh2.Session;
    import com.trilead.ssh2.StreamGobbler;
    public class SshTest
      public static void main(String[] args)
        Connection conn = null;
        try
          String host = "something.server.net";
          String user = "someuser";
          String user_pass = "somepassword";
          conn = new Connection(host);
          conn.connect();
          conn.authenticateWithPassword(user, user_pass);
          Session sess = conn.openSession();
          // vusertochange
          sess.execCommand("password_reset vusertochange newpasswordtest");
          /* Read all output with streamgobblers */
          StreamGobbler stdout = new StreamGobbler(sess.getStdout());
          StreamGobbler stderr = new StreamGobbler(sess.getStderr());
          /* Send the password (with a newline!) */
          BufferedOutputStream stdin = new BufferedOutputStream(sess.getStdin());
          stdin.flush();
          //stdin.close(); // This is optional
          /* Wait until the session has ended, maximum 60secs */
          int res = sess.waitForCondition(ChannelCondition.EOF, 60 * 1000);
          if ((res & ChannelCondition.EOF) == 0)
            throw new IOException("A timeout occured while reading the output.");
          /* OK, by now the whole output has been consumed by the two StreamGobblers */
          /* Close the session */
          sess.close();
          /* Show the result of STDERR */
          BufferedReader stderr_reader = new BufferedReader(new InputStreamReader(stderr));
          while (true)
            String line = stderr_reader.readLine();
            if (line == null)
              break;
            System.out.println("STDERR:" + line);
          /* Show the result of STDOUT */
          BufferedReader stdout_reader = new BufferedReader(new InputStreamReader(stdout));
          while (true)
            String line = stdout_reader.readLine();
            if (line == null)
              break;
            System.out.println("STDOUT:" + line);
        catch (Exception e)
          e.printStackTrace();
        finally
          if (conn != null)
            conn.close();
    The error I get is:
    STDOUT:cshell won't execute arbitrary command 'password_reset vusertochange newpasswordtest'
    any ideas what I am doing wrong?

    orozcom wrote:
    STDOUT:cshell won't execute arbitrary command 'password_reset vusertochange newpasswordtest'It sounds like the permissions with the user you're connecting with won't allow this operation.
    Don't know much about this, but maybe try 'su' and then 'password_reset ...' instead?

  • Run shell commands using java program

    Hi guys,
    I am trying to run shell commands like cd /something and ./command with arguments as follows, but getting an exception that ./command not found.Instead of changing directory using "cd" command I am passing directory as an argument in rt,exec().
    String []cmd={"./command","arg1", "arg2", "arg3"};
    File file= new File("/path");
    try{
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd,null,file);
    proc.waitFor();
    System.out.println(proc.exitValue())
    BufferedReader buf = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    catch(Exception e)
    {e.printStackTrace();
    So can anyone please tell me what is wrong with this approach? or is there any better way to do this?
    Thanks,
    Hardik

    warnerja wrote:
    What gives you the idea that the process to execute is called "./command"? If this is in Windows, it is "cmd.exe" for example.It does not have to be cmd.exe in Windows. Any executable or .bat file can be executed as long as one either specifies the full path or the executable is in a directory that is in the PATH.
    On *nix the file has to have the executable bit set and one either specifies the full path or the executable must be in a directory that is in the PATH . If the executable is a script then if there is a hash-bang (#!) at the start of the first line then the rest of the line is taken as the interpreter  to use. For example #!/bin/bash or #!/usr/bin/perl .
    One both window and *nix one can exec() an interpreter directly and then pass the commands into the process stdin. The advantage of doing this is that one can change the environment in one line and it  remains in effect for subsequent line. A simple example of this for bash on Linux is
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    public class ExecInputThroughStdin
        public static void main(String args[]) throws Exception
            final Process process = Runtime.getRuntime().exec("bash");
            new Thread(new PipeInputStreamToOutputStreamRunnable(process.getErrorStream(), System.err)).start();
            new Thread(new PipeInputStreamToOutputStreamRunnable(process.getInputStream(), System.out)).start();
            final Writer stdin = new OutputStreamWriter(process.getOutputStream());
            stdin.write("xemacs&\n");
            stdin.write("cd ~/work\n");
            stdin.write("dir\n");
            stdin.write("ls\n");
            stdin.write("gobbldygook\n"); // Forces output to stderr
            stdin.write("echo $PATH\n");
            stdin.write("pwd\n");
            stdin.write("df -k\n");
            stdin.write("ifconfig\n");
            stdin.write("echo $CWD\n");
            stdin.write("dir\n");
            stdin.write("cd ~/work/jlib\n");
            stdin.write("dir\n");
            stdin.write("cat /etc/bash.bashrc\n");
            stdin.close();
            final int exitVal = process.waitFor();
            System.out.println("Exit value: " + exitVal);
    }One can use the same approach with Windows using cmd.exe but then one must be aware of the syntactic differences between commands running in .bat file and command run from the command line. Reading 'help cmd' s essential here.
    The class PipeInputStreamToOutputStreamRunnable in the above example just copies an InputStream to an OutputStream and I use
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    public class PipeInputStreamToOutputStreamRunnable implements Runnable
        public PipeInputStreamToOutputStreamRunnable(InputStream is, OutputStream os)
            is_ = is;
            os_ = os;
        public void run()
            try
                final byte[] buffer = new byte[1024];
                for (int count = 0; (count = is_.read(buffer)) >= 0;)
                    os_.write(buffer, 0, count);
            } catch (IOException e)
                e.printStackTrace();
        private final InputStream is_;
        private final OutputStream os_;
    }

  • Unable to execute a command line command using Java

    I am trying to run a command to add a group name. It is executed in command prompt of Windows 2003/2000
    Say this is the command I want to execute:
    net localgroup LordSM /add
    Here LordSM is the group name.
    I wrote the following code but it does not seem to work. Please suggest.
    String ABC=Value1TextField.getText();
    Value2Label.setText("Value is now " + ABC);
    // Above is to get value from a JText Field
    // Below is the code to run command for adding a group name to a System.
    String ExecutedCmd = "net localgroup " + ABC + "/add";
    Process p = Runtime.getRuntime().exec(ExecutedCmd);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    // read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    while ((s = stdInput.readLine()) != null)
    { System.out.println(s); }
    // read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null)
    { System.out.println(s); }
    I am trying to run a command to add a group name. It is executed in command prompt of Windows 2003/2000
    Say this is the command I want to execute:
    net localgroup LordSM /add
    Here LordSM is the group name.
    I wrote the following code but it does not seem to work. Please suggest.
    String ABC=Value1TextField.getText();
    Value2Label.setText("Value is now " + ABC);
    // Above is to get value from a JText Field
    // Below is the code to run command for adding a group name to a System.
    String ExecutedCmd = "net localgroup " + ABC + "/add";
    Process p = Runtime.getRuntime().exec(ExecutedCmd);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    // read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    while ((s = stdInput.readLine()) != null)
    { System.out.println(s); }
    // read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null)
    { System.out.println(s); }
    It does not seem to work means, that no Standard Error is defined, when it executes and group name is not added as well. The following is JUnit Test Result: Hope it gives a better idea of the problem I am facing:
    compile:
    run:
    Here is the standard output of the command:
    Here is the standard error of the command (if any):
    The syntax of this command is:
    NET LOCALGROUP [groupname [/COMMENT:"text"]] [DOMAIN]
    groupname {ADD [/COMMENT:"text"] | /DELETE} [DOMAIN]
    groupname name [...] {ADD | /DELETE} [DOMAIN]
    Got it
    BUILD SUCCESSFUL (total time: 10 minutes 49 seconds)
    I had even tried this:
    Runtime rt =Runtime.getRuntime();
    String[] cmd = new String[3];
    cmd[0] = "cmd.exe";
    cmd[1]="net localgroup";
    cmd[2] =ABC + "/add";
    rt.exec(cmd);
    but again, it does not give any error as such, but it does not create the group name either. Please suggest. We can see the group names that are added on right clicking My Computer Icon and click Manage and then go to User & Group section. On executing either of the code nothing happens.
    Thanks

    Duplicate post:
    http://forum.java.sun.com/thread.jspa?threadID=5203526&messageID=9812067#9812067

  • Problem in Execution of DOS Commands with JAVA.

    I am trying to execute DOS Commands and FTP commands using Java Programming Language and Trying to get the output for further processing.Actually I want the exact output what DOS and FTP give after execution of a their corresponding commands.

    Process p = new Process("dir");
    InputStream is = p.getInputStream();

Maybe you are looking for

  • Foreign trade! Legal regulation control

    Hello Guys, If someone has worked on FT-Legal Regulation,kindly tell me whether it is possible to control regulations on the basis of Sales Organisation rather than Country of origin(which is derived from plant). The requirement is in Intercompany Bu

  • Authorization BW7.0 and varaibles (authorizations)

    Hi all, I'm in charge of set up Authorization on BW 7.0 system. For example, to add rectriction on 0PLANT (relevant for authorizations). I would like to know if i MUST create Authorizations Varaibles on all my queries who contain 0plant ??? Is there

  • Easy Rotator Help

    When I insert an easy rotator on 4 of my 5 pages, it shows up like this : I need it to show normally. Anyone know what to do? Thank you.

  • Error -8: iChat worked, then stopped...

    After convincing a friend of mine that Mac's were the way forward and were infinitely easier to use than Windows, he bought a brand new iMac. We tried out iChat's audio, video and screen sharing features and they worked out the box. Great. My friend

  • PAI event

    Hello,                 R there any subevents in PAI.                   plzz help. regards, satish