Bonjour,

je développe un logiciel en java qui permet de se connecter sur des platforms (HP, SUN) et qui permet l'exécution de commandes à distance.

J'ai un problême sur une platform HP de chez Orange lorsque je me connecte en SSH et que je fais un bond Telnet; j'ai un carriage return de trop qui se fait à l'exécution de chaque commande, ce qui fait que j'ai des décalages dans mes résultats.

Exemple :

prompt:> Commande1
Resultat Commande1
prompt:> prompt:>

au lieu de

prompt:> Commande1
Resultat Commande1
prompt:>

Je pense qu'il y a comme un double carriage return au lancement de la commande donc un de trop.

Mes données de connection (IP, protocol, port, login, mdp, loginprompt, mdpprompt, prompt...) sont dans un classeur excel.

La classe AuditSSHClient utilise la librairie "ganymed-ssh2-build210.jar" et est appellée pour la première connection SSH; La classe AuditTelnetClient utilise la librairie "commons-net-1.4.1.jar" pour la deuxième connection et on a successivement d'appelé :

MakeConnection() -> Class AuditSSHClient : Connect() -> Logon() -> MakeConnection() -> Class AuditTelnetClient : ConnectHop()

La classe AuditSSHClient :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
 
/*##################################################################
	 * 							Constructor
	 ###################################################################*/
 
	/**
         * Construct a new AuditSSHClient using a single hop
         * @param       prompt                  The string which will be printedd after each command
         * @param       host                    The adress of the remote server
         * @param       port                    The port which will be use ton connect to the remote server
         * @param       login                   The login which will be use to connect to the remote server
         * @param       password                The password which will be use to connect to the remote server
         * @param       name                    The name of the equipment
         */
	public AuditSSHClient(String prompt, String host, int port, String login, String password, String name)
        {
            ConnecInfo hop1 = new ConnecInfo(host, port, "ssh", login, password, prompt, name);
            this.hop = new ArrayList<ConnecInfo>();
            this.hop.add(hop1);
	}
 
	/**
         * Construct a new AuditSSHClient using a list of hops.
         * @param listHop       The list of the hopes which will be used to connect to the final remote server.
         */
	public AuditSSHClient(ArrayList<ConnecInfo> listHop)
        {
            this.hop = listHop;
        }
 
	/**
         * Connect the software to a remote server.
         * @return      Indicate if the ConnecInfo attempt is a success.
         */
	public boolean connect()
	{
            this.conn = new Connection(this.hop.get(0).getHostname(),this.hop.get(0).getPort());
            Report.getInstance().addReport(this.hop.get(0).getName(), "+" + File.separator + this.hop.get(0).getName(), false);
            try
            {
                Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: SNEC is connected to the remote server ("+ this.hop.get(0).getHostname() + ") by SSH");
                this.conn.connect();
            }
            catch(IOException E)
            {
                Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: SNEC can't connect the remote server ("+ this.hop.get(0).getHostname() + ") by SSH");
                return false;
            }
 
            //this.logon();
            this.currentHop=0;
            //this.currentHop=0;
            boolean res = true;
 
            while(this.currentHop < this.hop.size() && res)
            {
                res = this.logon();
		this.currentHop++;
            }
		this.currentHop--;
                return res;
	}
 
 
	/**
         * Log the software on the remote server.
         * @return      Indicate if the login attempt was a success.
         */
	private boolean logon()
	{
            if(this.currentHop == 0 && this.conn.isAuthenticationComplete()== false)
            {
            try
            {
                boolean res = this.conn.authenticateWithPassword(this.hop.get(this.currentHop).getLogin(), this.hop.get(this.currentHop).getPassword());
		if(res)
                {
                    this.sess = this.conn.openSession();
                    this.sess.requestDumbPTY();
                    this.sess.startShell();
                    this.sshOut = this.sess.getStdin();					
                    this.sshIn = this.sess.getStdout();
 
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: The LoginPrompt <" + this.hop.get(0).getLoginPrompt() + "> was found");
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: The PasswordPrompt <" + this.hop.get(0).getPasswordPrompt() + "> was found");
 
                    String prompt = this.waitFor(this.hop.get(0).getPrompt(), 10);
 
                    if(prompt == null)
                    {
                        Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: The Prompt is wrong : <"+this.hop.get(0).getPrompt()+"> expected, <"+this.failed+"> found");
                        Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: SNEC can't log to the remote server");
                        return false;
                    }
                    else
                    {
                        Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: SNEC is logged to the remote server with the " + this.hop.get(0).getLogin() + " account");
                        return true;
                    }		
                }
		else
                {
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: Wrong parameter(s) : " + this.failed);
                    /*Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]:    - Prompt : <" + this.hop.get(0).getPrompt()+"> expected");
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]:    - Login : " + this.hop.get(0).getLogin() + " found");
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]:    - Password : " + this.hop.get(0).getPassword() + " found");
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: SNEC can't log on the remote server with the " + this.hop.get(0).getLogin() + " account");
                     */
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: SNEC can't log on the remote server with the " + this.hop.get(0).getLogin() + " account");
                    return false;
                }
            }
            catch(IOException E)
            {
                Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: SNEC is logged to the remote server with the " + this.hop.get(0).getLogin() + " account");
                return false;
            }
	}
	else
	{
            Report.getInstance().writeReport(this.hop.get(this.currentHop).getName(), "[Date]: SNEC try to connect the hop number " + currentHop + " (" + this.hop.get(this.currentHop).getHostname() + ") by " + this.hop.get(this.currentHop).getProtocol());
            boolean res = new MakeConnection(this.hop.get(this.currentHop).getProtocol(),null).ConnectHop(this.hop.get(this.currentHop),this,this.currentHop);
           /*
            this.waitFor(this.hop.get(this.currentHop).getPasswordPrompt(), 10);			
            this.send(this.hop.get(this.currentHop).getPassword(),10);
            this.waitFor(this.hop.get(this.currentHop).getPrompt(), 10);
            */
            return res;		
	}
    }
 
 
	/**
         * Send a new string on the remote server.
         * @param       value           The String which will be send to the remote server.
         */
	public void write(String value)
	{
            try
            {
                this.sess.execCommand(value);
            }
            catch(IOException E)
            {
 
            }
	}
 
	/**
         * Receive the data coming from the remote server in a passive mode until a specific pattern is recognized.
         * @param       Pattern         The pattern which need to be recognized.
         * @param       timeout         The time limit of the operation
         * @return              All the data which were read until the recognition of the pattern.
         */
	public String waitFor(String Pattern, int timeout) 
	{
		//The String Buffer which will contains the response of the server
		StringBuffer in = new StringBuffer();
 
                //The objects that will identify the pattern 
		Pattern Identifier;
                Pattern Identifier2;
		Matcher Match;
                Matcher Match2;
 
                Pattern =  Pattern.replace("\\","\\\\");
                Pattern = Pattern.replace("[","\\[");
                Pattern = Pattern.replace("]","\\]");
                Pattern =Pattern.replace("^","\\^");
                Pattern = Pattern.replace("(","\\(");
                Pattern = Pattern.replace(")","\\)");
 
                Pattern = Pattern.replace("&","\\&)");
                Pattern = Pattern.replace(".","\\.");  
                Pattern = Pattern.replace("*","(.)*"); 
 
                Pattern =  Pattern.replace("{","\\{");
                Pattern =  Pattern.replace("}","\\}");
 
                Pattern =  Pattern.replace("?",".");
 
                int i=0;
                int j=0;
                for(i=0; i<Pattern.length();i++)
                {
                    if(Pattern.charAt(i) != '.')
                    {
                        break;
                    }
                    j++;
                }
                if(i!=0)
                {
                    Pattern = Pattern.substring(i);
                }
 
		//Creation of the regex compiler
		Identifier = java.util.regex.Pattern.compile(Pattern);
                Identifier2 = java.util.regex.Pattern.compile(Pattern.toLowerCase());
		//Indicate if the pattern was found
		boolean pattFound = false;
		// Timeout is set
		// Gets the present time
		Calendar endTime = Calendar.getInstance();
		// Adds the timeout at the present time
		endTime.add(Calendar.SECOND, timeout);
 
		while(true)
		{
                    int n = 0;
                    try
                    {
                        while (Calendar.getInstance().before(endTime) && this.sshIn.available() == 0) 
                        {
                            try
                            {
                                Thread.sleep(250);
                            }
                            catch(InterruptedException E2)
                            {
                                Report.getInstance().writeReport(this.hop.get(this.currentHop).getName(), "[Date]: Error, the thread was interrupted :" + E2.getMessage());
                            }
                        }
                    }
                    catch(IOException E3)
			{
 
			}
			if(!Calendar.getInstance().before(endTime))
			{
                             Pattern spl = java.util.regex.Pattern.compile("\r\n|\n|\r|\u0085|\u2028|\u2029");
                                String [] lines = spl.split(in.toString());
                                Matcher m = Identifier2.matcher(lines[lines.length-1].toLowerCase());
                                   if (lines[lines.length-1].toLowerCase().contains("more")|| lines[lines.length-1].toLowerCase().contains("press any")) {
                                        PrintStream out = new PrintStream(this.sshOut);
                                        out.println(" ");
                                        out.flush();
                                         	// Gets the present time
                                        endTime = Calendar.getInstance();
                                        // Adds the timeout at the present time
                                        endTime.add(Calendar.SECOND, timeout);
                                        //lastmore = Math.max(in.toString().toLowerCase().indexOf("more"),in.toString().toLowerCase().indexOf("press any"));
                                    }
                                    // Case Omni6800
                                    else if (lines[lines.length-1].toLowerCase().contains("next line <cr>")) {
                                            PrintStream out = new PrintStream(this.sshOut);
                                            out.println(" ");
                                            out.flush();
                                            endTime = Calendar.getInstance();
                                        // Adds the timeout at the present time
                                        endTime.add(Calendar.SECOND, timeout);
                                            //lastmore = in.toString().toLowerCase().indexOf("next line <cr>");
                                    }
                                    else
                                    {
                                        if(!m.find())
                                        {
                                            this.failed = in.toString();
                                            System.out.println(this.failed);
                                             return null;
                                        }
                                        else
                                        {
                                            return in.toString();
                                        }
                                    }
			}
			try
			{
				//Checks if any characters are waited over the session
				while (this.sshIn.available() != 0) {
					in.append((char)this.sshIn.read());
				}
			}
			catch(IOException E)
			{
 
			}
 
			Pattern spl = java.util.regex.Pattern.compile("\r\n|\u0085|\u2028|\u2029");
			String [] lines = spl.split(in.toString());
                        if(lines.length >= 1)
                        {
                            // Checks if a "more" has been find in input stream
                            if (lines[lines.length-1].toLowerCase().contains("more")|| lines[lines.length-1].toLowerCase().contains("press any")) {
 
                                 PrintStream out = new PrintStream(this.sshOut);
                                    out.println(" ");
                                    out.flush();
                                    //lastmore = Math.max(in.toString().toLowerCase().indexOf("more"),in.toString().toLowerCase().indexOf("press any"));
                            }
                            // Case Omni6800
                            else if (lines[lines.length-1].toLowerCase().contains("next line <cr>")) {
                                    PrintStream out = new PrintStream(this.sshOut);
                                    out.println(" ");
                                    out.flush();
                                    //lastmore = in.toString().toLowerCase().indexOf("next line <cr>");
                            }
                            else
                            {
                                Match2 = Identifier2.matcher(lines[lines.length-1].toLowerCase());
                                pattFound =  Match2.find();
 
                                if(pattFound)
                                {
                                            String Ret = in.toString();
                                            return Ret;
                                }
                            }
                     }      
		}		
	}
 
	/**
         * Send a new instruction to the remote server.
         * @param       cmd             The instruction to send to the remote server.
         * @param       timeout         The time limit for the operation.
         * @return                      The result of the operation.
         */
	public String send(String cmd, int timeout)
	{
            if(this.checkAccess())
            {
                PrintStream out = new PrintStream(this.sshOut);
                out.println(cmd);
 
                String Ret = this.waitFor(this.hop.get(this.currentHop).getPrompt(), timeout);
                System.out.println(cmd);
                System.out.println(Ret);
                if(Ret == null)
                {
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: Error during the execution of the command");
                }
                return Ret;
            }
            else
            {
                return "";
            }
	}
 
        /**
         * Send a new instruction to the remote server.
         * @param       cmd             The instruction to send to the remote server.
         * @param       timeout         The time limit for the operation.
         * @param       Prompt          The correct prompt
         * @return                      The result of the operation.
         */
	public String send(String cmd, int timeout, String Prompt)
        {
            if(this.checkAccess())
            {
                PrintStream out = new PrintStream(this.sshOut);
                out.print(cmd+"\r\n");
                String Ret = this.waitFor(Prompt, timeout);
                System.out.println("COMMANDE "+cmd);
                System.out.println("CMD+ RESILTAT :: "+Ret);
                if(Ret == null)
                {
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: Error during the execution of the command");
                }
                return Ret;
            }
            else
            {
                return "";
            }
        }
 
 
	}
La classe AuditTelnetClient :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
 
package snec.modules.stdaudit.model.connection;
 
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import snec.modules.stdaudit.model.treatment.Report;
 
import java.util.ArrayList;
import org.apache.commons.net.telnet.*;
 
import java.io.File;
import java.io.PrintStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Calendar;
 
/**
 * Class which allow the software to connect to a telnet server and execute instructions on it.
 */
public class AuditTelnetClient extends TelnetClient implements AuditClient {
 
        /*##################################################################
         * 							Attributes
         ###################################################################*/
    /**
     * The current connection Hop.
     * @uml.property name="hop"
     */
    private ArrayList<ConnecInfo> hop;
 
    private String failed = "";
 
    /**
     * The current hop
     * @uml.property  name="currentHop"
     */
    private int currentHop = 0;
 
    /**
     * Indicate if the telnet client is connected to the remote server
     */
    private Boolean connected = false;
        /*##################################################################
         * 							Constructors
         ###################################################################*/
 
    /**
     * Construct a new AuditTelnetClient using a single hop
     * @param   prompt                  The string which will be printedd after each command
     * @param   loginPrompt             The string which will be printed before the entry of the login
     * @param   passwordPrompt  The string which will be printed before the entry of the password
     * @param   host                    The adress of the remote server
     * @param   port                    The port which will be use ton connect to the remote server
     * @param   login                   The login which will be use to connect to the remote server
     * @param   password                The password which will be use to connect to the remote server
     * @param   name                    The name of the equipment
     */
    public AuditTelnetClient(String prompt, String loginPrompt, String passwordPrompt, String host, int port, String login, String password, String name) {
        ConnecInfo hop1 = new ConnecInfo(host, port, "telnet", login, password, loginPrompt, passwordPrompt, prompt, name);
        this.hop = new ArrayList<ConnecInfo>();
        this.hop.add(hop1);
    }
 
    /**
     * Construct a new AuditTelnetClient using a list of hopes.
     * @param listHop           The list of the hopes which will be used to connect to the final remote server.
     */
    public AuditTelnetClient(ArrayList<ConnecInfo> listHop) {
        this.hop = listHop;
    }
 
        /*##################################################################
         *                                                   Class functions
         ###################################################################*/
 
    /**
     * Connect the the software to a telnet hop
     * @param   hop             The connection hop
     * @param   remoteConnection   The remote connection which is used to do the hop
     * @param   number          The number of the hop
     * @return                  the result of the connection
     */
    public boolean ConnectHop(ConnecInfo hop, AuditClient remoteConnection, int number) {
        String nPrompt = remoteConnection.send("telnet "+ hop.getHostname(), 15, hop.getLoginPrompt());
        Report.getInstance().addReport(hop.getName(), "+" + File.separator + hop.getName(), false);
        if (nPrompt == null) {
            Report.getInstance().writeReport(hop.getName(), "[Date]: The LoginPrompt doesn't match : <" + hop.getLoginPrompt() + ">");
            Report.getInstance().writeReport(hop.getName(), "[Date]: SNEC can't log on the hop number " + number + " with the " + hop.getLogin() + " account");
            return false;
        } else {
            Report.getInstance().writeReport(hop.getName(), "[Date]: The LoginPrompt <" + hop.getLoginPrompt() + "> was found");
            String n3Prompt = remoteConnection.send(hop.getLogin(), 10 , hop.getPasswordPrompt());
            if (n3Prompt == null) {
                Report.getInstance().writeReport(hop.getName(), "[Date]: The PasswordPrompt doesn't match : : <" + hop.getPasswordPrompt() + ">");
                Report.getInstance().writeReport(hop.getName(), "[Date]: SNEC can't log on the hop number " + number + " with the " + hop.getLogin() + " account");
                return false;
            } else {
                Report.getInstance().writeReport(hop.getName(), "[Date]: The PasswordPrompt <" + hop.getPasswordPrompt() + "> was found");
                //send the password
                String n2Prompt = remoteConnection.send(hop.getPassword(), 10);
                //Waits prompt
                if (n2Prompt == null) {
                    // Waited prompt doesn't match
                     Report.getInstance().writeReport(hop.getName(), "[Date]: Wrong parameter(s) : " + this.failed);
                    /*Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]:    - Prompt : <" + this.hop.get(0).getPrompt()+"> expected");
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]:    - Login : " + this.hop.get(0).getLogin() + " found");
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]:    - Password : " + this.hop.get(0).getPassword() + " found");
                    Report.getInstance().writeReport(this.hop.get(0).getName(), "[Date]: SNEC can't log on the remote server with the " + this.hop.get(0).getLogin() + " account");
                     */
                    Report.getInstance().writeReport(hop.getName(), "[Date]: SNEC can't log on the remote server with the " + hop.getLogin() + " account");
                    return false;
                } else {
                    // Waited prompt matchs
                    Report.getInstance().writeReport(hop.getName(),"[Date]: SNEC is logged to the hop number " + number + " with the " + hop.getLogin() + " account");
                    return true;
                }           
            }        
        }    
    }