1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package it.jnrpe.plugin.utils;
17
18 import it.jnrpe.ICommandLine;
19 import it.jnrpe.Status;
20 import it.jnrpe.plugins.MetricGatheringException;
21
22 import com.jcraft.jsch.JSch;
23 import com.jcraft.jsch.Session;
24
25
26
27
28
29
30
31 public class SshUtils {
32
33
34
35
36 protected static final int DEFAULT_TIMEOUT = 10;
37
38
39
40
41 protected static final int DEFAULT_PORT = 22;
42
43
44
45
46
47
48
49
50
51
52 public static Session getSession(final ICommandLine cl)
53 throws MetricGatheringException, Exception {
54 JSch jsch = new JSch();
55 Session session = null;
56 int timeout = DEFAULT_TIMEOUT;
57 int port = cl.hasOption("port") ? Integer.parseInt(cl.getOptionValue("port")) : + DEFAULT_PORT;
58 String hostname = cl.getOptionValue("hostname");
59 String username = cl.getOptionValue("username");
60 String password = cl.getOptionValue("password");
61 String key = cl.getOptionValue("key");
62 if (cl.getOptionValue("timeout") != null) {
63 try {
64 timeout = Integer.parseInt(cl.getOptionValue("timeout"));
65 } catch (NumberFormatException e) {
66 throw new MetricGatheringException(
67 "Invalid numeric value for timeout.", Status.CRITICAL,
68 e);
69 }
70 }
71 session = jsch.getSession(username, hostname, port);
72 if (key == null) {
73 session.setConfig("StrictHostKeyChecking", "no");
74 session.setPassword(password);
75 } else {
76 jsch.addIdentity(key);
77 }
78 session.connect(timeout * 1000);
79 return session;
80 }
81
82 }