View Javadoc

1   /**
2    * Esta clase .
3    * <p>
4    * 
5    * .
6    * <p>
7    * 
8    *             
9    * @version $Revision: 1.1.2.1 $, Jan 17, 2007
10   * @author Gonzalo Espert 
11   */
12  package net.sf.provisioner.connectors;
13  
14  
15  import java.io.*;
16  
17  import net.sf.provisioner.config.NetworkElement;
18  
19  import ch.ethz.ssh2.Connection;
20  import ch.ethz.ssh2.Session;
21  import ch.ethz.ssh2.StreamGobbler;
22  
23  
24  /**
25   * @author Gonzalo
26   *
27   */
28  public class SSHConnector extends Connector{
29  	
30  	NetworkElement ne;
31  	
32  	Session sesion;
33  	
34  	public InputStream reader;
35  	
36  	public PrintWriter writer;
37  	
38  	Connection conexion;
39  
40  	/**
41       * .
42       * <p>
43       * 
44       * .
45       * <p>
46       * 
47       * 
48       * 
49       * @param 
50       *            
51       * @throws 
52       *            
53       *           
54       */
55  	public SSHConnector(NetworkElement ne) { this.ne = ne; }
56  	
57  	/**
58       * .
59       * <p>
60       * 
61       * .
62       * <p>
63       * 
64       * 
65       * 
66       * @param 
67       *            
68       * @throws 
69       *            
70       *           
71       */
72  	public void Connect() throws Exception{
73  		
74  		boolean isAuthenticated = false;
75  		
76  		try
77  		{
78  			/* Creamos una instancia de conexion */
79  			this.conexion = new Connection(this.ne.name);
80  
81  			/* Nos conectamos */
82  			this.conexion.connect();
83  
84  			/* Nos autenticamos */
85  			logger.info("Iniciando sesion en: " + this.ne.name + " .............");
86  			
87  			/* Vemos que tipo de autenticacion exige el server */
88  			if (this.conexion.isAuthMethodAvailable(this.ne.user, "password")) {
89  			
90  			
91  				isAuthenticated = this.conexion.authenticateWithPassword(this.ne.user, this.ne.password);
92  			
93  			} else {
94  				if (this.conexion.isAuthMethodAvailable(this.ne.user, "publickey")) {
95  					
96  					File keyfile = new File("config/private_key");
97  					isAuthenticated = this.conexion.authenticateWithPublicKey(this.ne.user, keyfile, this.ne.password);
98  					
99  				} else {
100 					
101 					//String[] metodos = this.conexion.getRemainingAuthMethods(this.ne.user);
102 				
103 					throw new IOException("El servidor no soporta autenticacion por el metodo de password ni publickey");
104 				}
105 			}
106 			
107 			if (isAuthenticated == false)
108 				throw new IOException("Fallo la autenticacion ssh con usuario : " + this.ne.user + " y password : " + this.ne.password);
109 			else {
110 			
111 				if (this.conexion.isAuthenticationComplete())
112 					logger.info("Autenticacion exitosa!");
113 				else
114 					throw new IOException("El procedimiento de autenticacion no esta completo");
115 			}
116 		
117 			/* Creamos una sesion */
118 			this.sesion = this.conexion.openSession();
119 			logger.info("Sesion iniciada exitosamente!");
120 			
121 			/* Iniciamos un shell para poder ejecutar mas de un comando en la misma sesion */
122 			this.sesion.requestDumbPTY();
123 			this.sesion.startShell();
124 			
125 			/* Creamos un stream buffer para leer */
126 			this.reader = new StreamGobbler(this.sesion.getStdout());
127 			while (this.reader.available() > 0) 
128 				this.reader.read(); // limpiamos el buffer
129 
130 			/* Creamos un stream para escribir */
131 			this.writer = new PrintWriter(new OutputStreamWriter(this.sesion.getStdin()), true);
132 		
133 			/* Si el elemento de red requiere el uso de sudo */
134 			if (!this.ne.sudoPassword.equalsIgnoreCase("")) {
135 				
136 				logger.info("El elemento de red requiere el uso de sudo");
137 				this.writer.println("su \r\n");
138 				
139 				try {
140 					Thread.sleep(500);
141 				}
142 				catch (Exception e) {
143 					throw e;
144 				}
145 				
146 				/* leemos la respuesta del server */
147 				StringBuffer result = new StringBuffer();
148 				while (this.reader.available() > 0) 
149 					result.append((char) this.reader.read());
150 				
151 				/* chequemos si la respuesta contiene el pedido de password del sudo */
152 				if (result.toString().endsWith(this.ne.sudoPasswordPrompt))
153 					this.writer.println(this.ne.sudoPassword + "\r\n");
154 				else
155 					throw new IOException("No se recibio el prompt para ingresar el password del sudo");
156 				
157 				
158 				try {
159 					Thread.sleep(500);
160 				}
161 				catch (Exception e) {
162 					throw e;
163 				}
164 				
165 				logger.info("El shell para sudo fue iniciado con exito, ya tenemos prompt de sistema");
166 				while (this.reader.available() > 0) 
167 					this.reader.read(); // limpiamos el buffer
168 					
169 			}
170 			
171 		} catch (IOException e)
172 		{
173 			throw e;
174 		}
175 
176 	}
177 	
178 	/**
179      * .
180      * <p>
181      * 
182      * .
183      * <p>
184      * 
185      * 
186      * 
187      * @param 
188      *            
189      * @throws 
190      *            
191      *           
192      */
193 	public void Disconnect() {
194 		
195 		/* Cerramos la sesion */
196 		this.sesion.close();
197 
198 		/* Cerramos la conexion */
199 		this.conexion.close();
200 			
201 	}
202 	
203 }