0

I want to connect a Linux server and execute a command, but when I send the command sh and su - it requires password, but my program sends password just before it asks. How can i solve this problem?

public class Stream
{
    public void getStream(String fileName)
    {
        String user = usernametext.getText();
        String host = hostiptext.getText();
        String password = pass.getText();
        String command4 = "sh\nsu -\nmypassword\n";
        try
        {
            System.out.println("preparing the host information for stream.");
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(10 * 1000);
            Channel channel = session.openChannel("shell");
            InputStream is = new ByteArrayInputStream(command4.getBytes());
            channel.setInputStream(is);
            channel.setOutputStream(System.out);
            channel.connect(15 * 1000);
            session.connect(10 * 10);
            channel.disconnect();
            session.disconnect();
        }
        catch (Exception ex)
        {
            System.out.println("Exception found while streaming.");
        }
    }

}
nikis
  • 11,166
  • 2
  • 35
  • 45
RecreatioN
  • 31
  • 1
  • 10

1 Answers1

0

As you are using a shell channel why do you need to call another sh?

Any how I do the above is to pass individual command and then read the inputStream until you get back to the prompt and then you can set the next input e.g. the password or what ever.

Pseudo-code being

write "su -"
readUntil "password:"
write "******"
readUntil prompt
etc.
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • i am new to java dont know how to do it – RecreatioN Apr 04 '14 at 08:34
  • basically you are reading and writing on the input and output streams. see http://stackoverflow.com/questions/4194439/sending-commands-to-server-via-jsch-shell-channel – Scary Wombat Apr 04 '14 at 08:38
  • Have you got the solution for this, please post here. I am trying to execute "su" command and then entering root password in the next line, i am getting error like "standard in must be a tty". All i want is enter to root in linux using java. – thomson Dec 22 '17 at 07:49
  • @thomson Maybe this will help, https://stackoverflow.com/questions/14220550/jsch-sudo-su-command-tty-error – Scary Wombat Dec 22 '17 at 08:03