View Javadoc

1   /*******************************************************************************
2    * Copyright (c) 2007, 2014 Massimiliano Ziccardi
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
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   * SSH utility class
27   * 
28   * @author Frederico Campos
29   * 
30   */
31  public class SshUtils {
32  
33  	/**
34  	 * Default timeout.
35  	 */
36  	protected static final int DEFAULT_TIMEOUT = 10;
37  
38  	/**
39  	 * Default HTTP port.
40  	 */
41  	protected static final int DEFAULT_PORT = 22;
42  
43  	/**
44  	 * Starts an ssh session
45  	 * 
46  	 * @param cl
47  	 * @return
48  	 * @throws MetricGatheringException
49  	 * @throws Exception
50  	 *             Session
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  }