使用unixsudo和ssh通过java连接到hadoop

hmtdttj4  于 2021-05-30  发布在  Hadoop
关注(0)|答案(0)|浏览(180)

我正在尝试使用java程序连接到hadoop。首先让我告诉你,我对java是新手,但我能理解基本代码。
以下是我如何通过putty连接到hadoop(在unix上):
连接到unix(通过提供主机名、用户名和密码)
运行sudo命令(sudo su-)(我必须在这里提供密码)
从当前主机运行ssh命令到hadoop主机(ssh defgh)
使用java程序,我能够连接到unix(步骤1)。我甚至可以在我连接的目录中运行一个unix命令。就像 ls , wc-l 等。
但我还是要用密码再给一次 sudo 命令(步骤2)。之后,我运行ssh命令(步骤3)
有人能帮我完成剩下的步骤吗?如果我要导入任何jar文件,请帮助我的链接也。我在下面提供我当前的unix连接java程序。我下载了jar文件 com.jcraft.jsch_0.1.31 我的java程序。

  1. package com.abc;
  2. import java.io.InputStream;
  3. import com.jcraft.jsch.Channel;
  4. import com.jcraft.jsch.ChannelExec;
  5. import com.jcraft.jsch.JSch;
  6. import com.jcraft.jsch.Session;
  7. import com.jcraft.jsch.UserInfo;
  8. public class First
  9. {
  10. public static void main(String args[])
  11. {
  12. String user="User ID";
  13. String host="host Name";
  14. String cmd="ls";
  15. JSch jsch = new JSch();
  16. try
  17. {
  18. Session session=jsch.getSession(user,host,22);
  19. session.setPassword("pwd");
  20. UserInfo usrInfo=new MyUserInfo();
  21. session.setUserInfo(usrInfo);
  22. session.connect();
  23. Channel channel=session.openChannel("exec");
  24. System.out.println("***1***");
  25. ((ChannelExec) channel).setCommand(cmd);
  26. channel.setXForwarding(true);
  27. InputStream in = channel.getInputStream();
  28. channel.connect();
  29. channel.setInputStream(System.in);
  30. byte[] tmp = new byte[1024];
  31. while (true)
  32. {
  33. System.out.println("***2***");
  34. while (in.available() > 0)
  35. {
  36. int i = in.read(tmp, 0, 1024);
  37. if (i < 0)
  38. break;
  39. System.out.print(new String(tmp, 0, i));
  40. System.out.println("***3***");
  41. }
  42. if (channel.isClosed())
  43. {
  44. in.close();
  45. break;
  46. }
  47. try
  48. {
  49. Thread.sleep(1000);
  50. }
  51. catch (Exception ee) {}
  52. }
  53. channel.disconnect();
  54. session.disconnect();
  55. }
  56. catch(Exception e)
  57. {
  58. e.printStackTrace();
  59. System.out.println("Exception"+e);
  60. }
  61. }
  62. public static class MyUserInfo implements UserInfo
  63. {
  64. public String getPassword() { return "password"; }
  65. public String getPassphrase() { return ""; }
  66. public boolean promptPassword(String arg0) { return true; }
  67. public boolean promptPassphrase(String arg0) { return true; }
  68. public boolean promptYesNo(String arg0) { return true; }
  69. public void showMessage(String arg0) { }
  70. }
  71. }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题