Gestion des exception en java avec telnet

Fermé
alffouss Messages postés 121 Date d'inscription mercredi 15 octobre 2008 Statut Membre Dernière intervention 20 octobre 2021 - 11 août 2009 à 10:14
Bonjour,
j'ai un programme java telent et j'aimerai bien gérer les exceptions du telnet.

Quand la connexion est impossible, je veux que le programme affiche: "connexion imposible"

Quand le mot de passe est faux, je veux que le programme affiche: "PB mot de passe"

Quand le login est faux, je veux que le programme affiche: "PB login"

Quand la commande est faux, je veux que le programme affiche: "votre commande est fausse"


Voici mont code java:


import org.apache.commons.net.telnet.*;
import java.io.*;

public class TelnetSample
{
private TelnetClient telnet = new TelnetClient();
private InputStream in;
private PrintStream out;
private char prompt = '$';

public TelnetSample( String server, String user, String password ) {
try {
// Connect to the specified server
telnet.connect( server, 23 );

// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream( telnet.getOutputStream() );

// Log the user on
readUntil( "login: " );
write( user );
readUntil( "Password: " );
write( password );

// Advance to a prompt
readUntil( prompt + " " );
}
catch( Exception e ) {
e.printStackTrace();
}
}

public void su( String password ) {
try {
write( "su" );
readUntil( "Password: " );
write( password );
prompt = '#';
readUntil( prompt + " " );
}
catch( Exception e ) {
e.printStackTrace();
}
}

public String readUntil( String pattern ) {
try {
char lastChar = pattern.charAt( pattern.length() - 1 );
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = ( char )in.read();
while( true ) {
System.out.print( ch );
sb.append( ch );
if( ch == lastChar ) {
if( sb.toString().endsWith( pattern ) ) {
return sb.toString();
}
}
ch = ( char )in.read();
}
}
catch( Exception e ) {
e.printStackTrace();
}
return null;
}

public void write( String value ) {
try {
out.println( value );
out.flush();
System.out.println( value );
}
catch( Exception e ) {
e.printStackTrace();
}
}

public String sendCommand( String command ) {
try {
write( command );
return readUntil( prompt + " " );
}
catch( Exception e ) {
e.printStackTrace();
}
return null;
}

public void disconnect() {
try {
telnet.disconnect();
}
catch( Exception e ) {
e.printStackTrace();
}
}

public static void main( String[] args ) {
try {
TelnetSample telnet = new TelnetSample( "192.168.1.99",
"username",
"password" );
telnet.sendCommand( "cd /mydir/mysubdir" );
telnet.su( "root-password" );
telnet.sendCommand( "./restart.sh" );
telnet.disconnect();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
=======

merci d'avance pour votre aide
A voir également: