2018년 4월 10일 화요일

[Java] SSH, SFTP Client Example



Download: jsch-0.1.54.jar  Java Secure Channel Library



1. SSH, SFTP Client Example


SSHClient.java
1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
public class SSHClient {

    Session session = null;
    Channel channel = null;

    String host;
    String user;
    String password;
    byte[] privateKey;
    
    int exitStatus;

    public SSHClient(String user, String host, byte[] privateKey) {
        this.user = user;
        this.host = host;
        this.privateKey = privateKey;
    }

    public SSHClient(String user, String host, String password) {
        this.user = user;
        this.host = host;
        this.password = password;
    }
    
    public void connect() throws JSchException, IOException {
        connect(20000);
    }

    public void connect(int connectTimeout) throws JSchException, IOException {
        JSch jsch = new JSch();
        if( privateKey != null ) {
            final byte[] prvkey = privateKey;
            final byte[] emptyPassPhrase = new byte[0];
            jsch.addIdentity(user, prvkey, null, emptyPassPhrase);
        }
        
        session = jsch.getSession(user, host, 22);
        Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setTimeout(connectTimeout);
        if( password != null ) {
            session.setPassword(password);
        }
        session.connect();
    }

    public void disconnect() {
        if (session != null) {
            if (channel != null) {
                channel.disconnect();
            }
            session.disconnect();
        }
    }

    public void sftpGet(String sourceFile, String targetFile) throws JSchException, SftpException, IOException {
        Channel lchannel = session.openChannel("sftp");
        lchannel.connect();
        ChannelSftp chSftp = (ChannelSftp) lchannel;
        InputStream is = chSftp.get(sourceFile);
        InputStreamToFile(is, targetFile);
        chSftp.disconnect();
    }

    public void sftpPut(String sourceFile, String targetFile) throws JSchException, FileNotFoundException, SftpException {
        Channel lchannel = session.openChannel("sftp");
        lchannel.connect();
        ChannelSftp chSftp = (ChannelSftp) lchannel;
        chSftp.put(new FileInputStream(new File(sourceFile)), targetFile);
        chSftp.disconnect();
    }

    public String executeCommand(String command) throws JSchException, IOException {
     System.out.println("EXEC Mode : Command being executed -->"+command);
     
     StringBuilder commandOutput = new StringBuilder();
        ChannelExec execChannel = null;
        execChannel = (ChannelExec) session.openChannel("exec");

        execChannel.setPty(true);
        execChannel.setCommand(command);
        execChannel.setInputStream(null);
        execChannel.setErrStream(System.err);
        execChannel.connect();
        
        InputStream in = execChannel.getInputStream();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                commandOutput.append(new String(tmp, 0, i));
            }
            if (execChannel.isClosed()) {
                if (in.available() > 0) {
                    continue;
                }
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
            }
        }
        exitStatus = execChannel.getExitStatus();
        execChannel.disconnect();
        System.out.println("Command response -->"+commandOutput.toString());
        return commandOutput.toString();
    }

    public int getExitStatus() {
        return exitStatus;
    }
    
    public static void InputStreamToFile(InputStream is, String fileName) throws IOException, IOException{
        OutputStream os = new FileOutputStream(new File(fileName));
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = is.read(buf)) > 0){
           os.write(buf, 0, len);
        }
        os.close();
    }
}


Test.java

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
static void testCommand(String user, String host, String password) {
        try{
            SSHClient sshClient = new SSHClient(user, host, password);
            sshClient.connect();
            String fileContent = sshClient.executeCommand("cat test.txt");
            System.out.println("Content -->"+fileContent);
            sshClient.disconnect();
        }catch(Exception e){
            e.printStackTrace();
        }   
    }
    
    static void testGet(String user, String host, String password) {
        try {
            SSHClient sshClient = new SSHClient(user, host, password);
            sshClient.connect();
            sshClient.sftpGet("test.txt", "test1.txt");
            sshClient.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    static void testPut(String user, String host, String password) {
        try {
            SSHClient sshClient = new SSHClient(user, host, password);
            sshClient.connect();
            sshClient.sftpPut("test1.txt", "test2.txt");
            sshClient.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        testCommand("user", "192.168.0.1", "password");
        testGet("user", "192.168.0.1", "password");
        testPut("user", "192.168.0.1", "password");
    }    





댓글 없음:

댓글 쓰기