|
| 1 | +/* |
| 2 | + * To change this license header, choose License Headers in Project Properties. |
| 3 | + * To change this template file, choose Tools | Templates |
| 4 | + * and open the template in the editor. |
| 5 | + */ |
| 6 | +package com.appdynamics.tests.jschsample; |
| 7 | + |
| 8 | +/** |
| 9 | + * |
| 10 | + * @author igor.simoes |
| 11 | + */ |
| 12 | +import java.io.InputStream; |
| 13 | + |
| 14 | +import com.jcraft.jsch.Channel; |
| 15 | +import com.jcraft.jsch.ChannelExec; |
| 16 | +import com.jcraft.jsch.JSch; |
| 17 | +import com.jcraft.jsch.JSchException; |
| 18 | +import com.jcraft.jsch.Session; |
| 19 | +import java.io.IOException; |
| 20 | + |
| 21 | + |
| 22 | + |
| 23 | +public class JSchExampleSSHConnection { |
| 24 | + |
| 25 | + /** |
| 26 | + * JSch Example Tutorial |
| 27 | + * Java SSH Connection Program |
| 28 | + */ |
| 29 | + public static void main(String[] args) { |
| 30 | + String host=args[0]; |
| 31 | + String user=args[1]; |
| 32 | + String privateKey = args[2]; |
| 33 | + // |
| 34 | + //String password="sshpwd"; |
| 35 | + String command1="ls -ltr"; |
| 36 | + try{ |
| 37 | + JSch.setLogger(new JSCHLogger()); |
| 38 | + java.util.Properties config = new java.util.Properties(); |
| 39 | + config.put("StrictHostKeyChecking", "no"); |
| 40 | + JSch jsch = new JSch(); |
| 41 | + jsch.addIdentity(privateKey); |
| 42 | + System.out.println("identity added "); |
| 43 | + Session session=jsch.getSession(user, host, 22); |
| 44 | + System.out.println("session created "); |
| 45 | + //session.setPassword(password); |
| 46 | + |
| 47 | + session.setConfig(config); |
| 48 | + session.connect(); |
| 49 | + System.out.println(session.getConfig(host)); |
| 50 | + System.out.println("Connected"); |
| 51 | + |
| 52 | + Channel channel=session.openChannel("exec"); |
| 53 | + ((ChannelExec)channel).setCommand(command1); |
| 54 | + channel.setInputStream(null); |
| 55 | + ((ChannelExec)channel).setErrStream(System.err); |
| 56 | + try { |
| 57 | + InputStream in=channel.getInputStream(); |
| 58 | + channel.connect(); |
| 59 | + |
| 60 | + byte[] tmp=new byte[1024]; |
| 61 | + while(true){ |
| 62 | + while(in.available()>0){ |
| 63 | + int i=in.read(tmp, 0, 1024); |
| 64 | + if(i<0)break; |
| 65 | + System.out.print(new String(tmp, 0, i)); |
| 66 | + } |
| 67 | + if(channel.isClosed()){ |
| 68 | + System.out.println("exit-status: "+channel.getExitStatus()); |
| 69 | + break; |
| 70 | + } |
| 71 | + try{Thread.sleep(1000);}catch(Exception ee){} |
| 72 | + } |
| 73 | + } |
| 74 | + catch (IOException ioe){ |
| 75 | + System.out.println(ioe.getMessage()); |
| 76 | + ioe.printStackTrace(); |
| 77 | + } |
| 78 | + channel.disconnect(); |
| 79 | + session.disconnect(); |
| 80 | + System.out.println("DONE"); |
| 81 | + }catch(JSchException e){ |
| 82 | + System.out.println(e.getMessage()); |
| 83 | + e.printStackTrace(); |
| 84 | + } |
| 85 | + |
| 86 | + } |
| 87 | + |
| 88 | +} |
0 commit comments