Advertisement
Guest User

Untitled

a guest
Apr 20th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. public class Sudo {
  2. private static final int timeout = 10000;
  3. public static String sudo_pass = "john123";
  4.  
  5. public static void main(String[] arg) {
  6. try {
  7. JSch jsch = new JSch();
  8. String user = "john";
  9. String host = "192.168.56.103";
  10. Session session = jsch.getSession(user, host, 22);
  11. UserInfo ui = new MyUserInfo();
  12. session.setUserInfo(ui);
  13. session.connect(timeout);
  14.  
  15. String command = "sudo poweroff";
  16.  
  17. ChannelExec channel = (ChannelExec) session.openChannel("exec");
  18.  
  19. // man sudo
  20. // -S The -S (stdin) option causes sudo to read the password from the
  21. // standard input instead of the terminal device.
  22. // -p The -p (prompt) option allows you to override the default
  23. // password prompt and use a custom one.
  24.  
  25. channel.setCommand("sudo -S -p '' " + command);
  26. channel.setPty(true);
  27.  
  28. InputStream in = channel.getInputStream();
  29. OutputStream out = channel.getOutputStream();
  30.  
  31. channel.setErrStream(System.err);
  32.  
  33. channel.connect();
  34.  
  35. out.write((sudo_pass + "n").getBytes());
  36. out.flush();
  37.  
  38. byte[] tmp = new byte[1024];
  39. while (true) {
  40. while (in.available() > 0) {
  41. int i = in.read(tmp, 0, 1024);
  42. if (i < 0) break;
  43. System.out.print(new String(tmp, 0, i));
  44. }
  45. if (channel.isClosed()) {
  46. System.out.println("exit-status: " + channel.getExitStatus());
  47. break;
  48. }
  49. try {
  50. Thread.sleep(1000);
  51. } catch (Exception ee) {
  52. }
  53. }
  54. channel.disconnect();
  55. session.disconnect();
  56. } catch (Exception e) {
  57. System.out.println(e);
  58. }
  59.  
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement