Guest User

Untitled

a guest
Mar 8th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. public static void main (String args[]) {
  2. String user = "user";
  3. String password = "password";
  4. String host = "hostName";
  5. int port=22;
  6.  
  7. //String remoteFile="/home/john/test.txt";
  8. //String yes="yes";
  9.  
  10. try {
  11. JSch jsch = new JSch();
  12. Session session = jsch.getSession(user, host, port);
  13. session.setPassword(password);
  14. session.setConfig("StrictHostKeyChecking", "no");
  15. System.out.println("Establishing Connection...");
  16. session.connect();
  17. Channel channel = session.openChannel("exec");
  18.  
  19. // After this it'll ask for confirmation and password
  20. ((ChannelExec)channel).setCommand("ssh myServerName");
  21. channel.connect();
  22.  
  23. InputStream output = channel.getInputStream();
  24.  
  25. System.out.println("aafter stream");
  26. int readByte = output.read();
  27. StringBuilder outputBuffer = new StringBuilder();
  28. while (readByte != 0xffffffff) {
  29. //System.out.println("read byte" + readByte);
  30. outputBuffer.append((char)readByte);
  31. readByte = output.read();
  32. }
  33. System.out.println(outputBuffer.toString());
  34. channel.disconnect();
  35. } catch (Exception e){
  36. System.err.print("error message" + e);
  37. }
  38. }
  39.  
  40. try {
  41. session = jsch.getSession(user, host, port);
  42. }
  43. catch (JSchException e) {
  44. throw new TransferException("Failed to open session - " + params, e);
  45. }
  46.  
  47. session.setPassword(password);
  48.  
  49. // Create UserInfo instance in order to support SFTP connection to any machine
  50. // without a key username and password will be given via UserInfo interface.
  51. UserInfo userInfo = new SftpUserInfo();
  52. session.setUserInfo(userInfo);
  53.  
  54. try {
  55. session.connect(connectTimeout);
  56. }
  57. catch (JSchException e) {
  58. throw new TransferException("Failed to connect to session - " + params, e);
  59. }
  60.  
  61. boolean isSessionConnected = session.isConnected();
  62.  
  63. Channel channel = session.openChannel("exec");
  64. ((ChannelExec) channel).setCommand("sudo -S -p '' " + command);
  65. channel.setInputStream(null);
  66. OutputStream out = channel.getOutputStream();
  67. ((ChannelExec) channel).setErrStream(System.err);
  68. InputStream in = channel.getInputStream();
  69. ((ChannelExec) channel).setPty(true);
  70. channel.connect();
  71. out.write((password + "n").getBytes());
  72. out.flush();
Add Comment
Please, Sign In to add comment