CORE
HOME > JAVA > J2SE > CORE
2018.06.06 / 10:47

J2ssh ¸¦ ÀÌ¿ëÇÑ SSH Á¢¼Ó ÀÎÁõ

ÀλçÀ̵åÀÚ¹Ù
Ãßõ ¼ö 209

J2ssh ¸¦ ÀÌ¿ëÇÑ SSH Á¢¼Ó ÀÎÁõ


Linux °ø°³Å°(Public Key) »ý¼º

> Æнº¿öµå¸¦ ÀÌ¿ëÇÑ ÀÎÁõ°ú °ø°³Å°¸¦ ÀÌ¿ëÇÑ ÀÎÁõ ¹æ½Ä

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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.authentication.PublicKeyAuthenticationClient;
import com.sshtools.j2ssh.configuration.SshConnectionProperties;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.transport.publickey.SshPrivateKey;
import com.sshtools.j2ssh.transport.publickey.SshPrivateKeyFile;
 
/**
 * # SSH Á¢¼Ó Ŭ¶óÀ̾ðÆ®
 */
public class J2sshCient {
    private Log log = LogFactory.getLog(this.getClass());   
    private SshClient ssh = null;   
    private SessionChannelClient session = null;   
    private String hostPrompt = null;       
     
    /**
     * @param server
     * @param userid
     * @param pwd
     * @throws Exception
     */
    public J2sshCient(String server, String userid, String password) throws Exception{   
        PasswordAuthenticationClient auth = null;   
 
        try {
            if (server == null || userid == null || password == null) {
                System.out.println("Parameter is null!");
            }
 
            ssh = new SshClient();
            ssh.setSocketTimeout(30000);
            SshConnectionProperties properties = new SshConnectionProperties();
            properties.setHost(server);
            properties.setPort(22);
            properties.setPrefPublicKey("ssh-dss");
            // Connect to the host
            ssh.connect(properties, new AlwaysAllowingConsoleKnownHostsKeyVerification());
 
// # Æнº¿öµå¸¦ ÀÌ¿ëÇÑ ÀÎÁõ Á¢¼Ó       
// ------------------------------------------------------------
//            PasswordAuthenticationClient authClient = new PasswordAuthenticationClient();
//            authClient.setUsername(userid);
//            authClient.setPassword(password);
// ------------------------------------------------------------
 
 
 
// # Æнº¿öµå ¾øÀÌ °ø°³Å°¸¦ ÀÌ¿ëÇÑ ÀÎÁõ Á¢¼Ó       
// ------------------------------------------------------------
            // Initialize the authentication data.
            PublicKeyAuthenticationClient authClient = new PublicKeyAuthenticationClient();
            // »ç¿ëÀÚ °èÁ¤
            authClient.setUsername(userid);
            // id_rsa ÆÄÀÏ À§Ä¡
            SshPrivateKeyFile file = SshPrivateKeyFile.parse(
                                          new File("/home/userid/.ssh/id_rsa"));
            SshPrivateKey privateKey = file.toPrivateKey(null);
            authClient.setKey( privateKey );   
// ------------------------------------------------------------
            int result = ssh.authenticate(authClient);
 
            if (result != AuthenticationProtocolState.COMPLETE) {
                throw new Exception("Login failed");
            }   
 
            // SSH Å͹̳ΠĿ¸Çµå ½ÇÇà¿ë
            session = ssh.openSessionChannel();
            session.requestPseudoTerminal("vt100", 80, 25, 0, 0 , "");
            session.startShell();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e);
            throw e;
        }   
    }  
 
    /*    * Ä¿¸Çµå ½ÇÇà ÇÔ¼ö(ex : ls -l\n)    */
    public String exec(String cmd) throws Exception
    {
        StringBuffer returnValue = null;
        boolean promptReturned = false;
        byte[] buffer = null;
        OutputStream out = null;
        InputStream in = null;
        int read;
        String response = null;
        int i = 0;
 
        try {
            if (session == null) {
                log.error("Session is not connected!");
                throw new Exception("Session is not connected!");
            }
 
            out = session.getOutputStream();
            cmd = cmd+"\n"; // Çà´ÜÀ§ ¸í·ÉÀ» À§ÇØ \n Ãß°¡
            out.write(cmd.getBytes());
            out.flush();
            in = session.getInputStream();
            buffer = new byte[255];
            returnValue = new StringBuffer(300);
 
            while(promptReturned == false && (read = in.read(buffer))> 0) {
                response = new String(buffer, 0, read);
                if (i == 1)
                    returnValue.append(response.toString());
                if (!StringUtils.isEmpty(response)
                   && response.indexOf(this.hostPrompt) >= 0) {
                    ++i;
                    if (i >= 2) {
                        promptReturned = true;
                    }
                }
            }
            log.error("returnValue : " + returnValue.toString());
 
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e);
        }
        return returnValue.toString();
    }
 
    public boolean isClosed() throws Exception
    {
        boolean rtn = true;
        try {
 
            if (session != null)
                rtn = session.isClosed();
        } catch(Exception e) {
            e.printStackTrace();
            log.error(e);
        }
        return rtn;
    }
 
    public boolean logout() throws Exception
    {
        boolean rtn = false;
 
        try {
            if (session != null) {
                session.getOutputStream().write("exit\n".getBytes());
                session.close();
            }
            if (ssh != null)
                ssh.disconnect();
            rtn = true;
        } catch(Exception e) {
            e.printStackTrace();
            log.error(e);
        }
        return rtn;
    }
 
    public String getHostprompt() {
 
        return this.hostPrompt;
    }
 
    public void setHostprompt(String hostPrompt) {
 
        this.hostPrompt = hostPrompt;
    }
 
    public static void main(String[] args)     {
        try {
 
            J2sshCient jsclient = new J2sshCient("192.168.1.10", "userid", "password");
            jsclient.setHostprompt("> ");
            String result = jsclient.exec("ls -al");
            System.out.println("jsclient.exec :" + result);
            jsclient.logout();
            System.out.println("isClosed : " + jsclient.isClosed());
             
        } catch (Exception e) {
            System.out.println(e);
        }   
    }
 
}



°ü·Ã ¹®¼­ :