IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Programmation et administration système Perl Discussion :

[Net::Telnet] Problème avec le prompt


Sujet :

Programmation et administration système Perl

  1. #1
    Membre averti Avatar de max44410
    Étudiant
    Inscrit en
    Juin 2003
    Messages
    426
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2003
    Messages : 426
    Points : 301
    Points
    301
    Par défaut [Net::Telnet] Problème avec le prompt
    Bonjour,

    Je suis en train de réaliser un programme en perle pour pouvoir faire des backup automatique sur plusieurs machines. Voila comment mon programme fonctionne :

    - je regarde tous les clients qui sont connectés sur mon serveur sur un port spécifique.
    - je fais une boucle sur toutes les adresses IP que j'ai obtenu dans le premier point
    - dans cette boucle je telnet chaque adresse IP pour exécuter une commande tar sur un répertoire (répertoire que je dois backuper).
    - toujours dans la session telnet j'ouvre une connexion FTP avec mon serveur pour transférer le fichier tar en question.
    - je supprime le fichier tar sur le client, et je ferme ma session telnet, et je passe au client suivant.


    Dans la logique il n'y a pas de souci, c'est jouable...
    Mon problème c'est que le parc de machine du réseau est assez hétérogène, en l'occurrence les clients non pas tous le même prompt lors de l'ouverture d'une session telnet (il ont tous un compte commun avec le même password).

    Donc le module (ou l'objet, je ne sais pas trop) Net::Telnet n'arrive pas a tout les coups a se connecter. Il m'affiche un timeout, et s'arrête.

    Je voudrais pouvoir ouvrir une session telnet peu importe le prompt, est ce possible.

    Je ne veux pas que lorsqu'une connexion n'est pas établie, ma boucle se casse, et que l'on sorte du programme

    Je ne sais pas si cela est possible, je voudrais un peu plus d'informations sur ces 2 points.

    Merci par avance, bonne journée.

  2. #2
    Membre averti Avatar de max44410
    Étudiant
    Inscrit en
    Juin 2003
    Messages
    426
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2003
    Messages : 426
    Points : 301
    Points
    301
    Par défaut
    C'est bon j'ai trouvé la solution. Il suffit de déclarer un pattern pour le prompt.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    $prompt ='/.*[\$#:>\]\%] *$/';
    $t = new Net::Telnet (Timeout => 20, Prompt => $prompt);
    Pour les explications :

    Dans une expression régulière la chaîne a rechercher est entre '/ /'
    .* représente n'importe quel caractère.
    Les chaînes qu'il est possible de trouver sont situés entre '[ ]'
    Pour le prompt il est donc possible de trouver :

    $
    #
    :>
    %
    ]

    *$ signifie n'importe quoi jusqu'a la fin

    Pour le problème du programme qui s'arrête il fallait juste changer le retour d'erreur qui est par défaut 'die'

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    $t = new Net::Telnet (Timeout => 20, Prompt => $prompt, Errmode=>'return');
    Voila ... je pensais pas m'en sortir aussi facilement et rapidement. en espérant que cela serve a d'autres personnes.

    @ Plus

  3. #3
    Membre averti Avatar de blackstreet
    Inscrit en
    Avril 2004
    Messages
    304
    Détails du profil
    Informations forums :
    Inscription : Avril 2004
    Messages : 304
    Points : 335
    Points
    335
    Par défaut
    Bonjour,

    J'ai à faire un script qui réalise presque la même chose, est ce que tu peut m'aider en me donnant à peut près la structure du script.

    et merci.

  4. #4
    Membre averti Avatar de max44410
    Étudiant
    Inscrit en
    Juin 2003
    Messages
    426
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2003
    Messages : 426
    Points : 301
    Points
    301
    Par défaut
    Voila le code qui me permet de faire mes backup.

    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
     
    #!/usr/bin/perl -w
     
    # libraries that we are going to use
    use lib "/bin/perl/lib";
    use Net::Telnet ();
     
    # We clean the screen
    system ("clear");
     
    # We search the actual date and time and display this information to the screen
    ($date,$time) = &time_stamp();
    print $date."\n";
    print $time."\n";
     
    ###################### SEARCH CONNECTIONS #########################
    @ip = ();       # array of client IP connected to the Server
    $compt=0; # number of client found
     
    # Shell command executed to find all client which are connected on the 10014 port
    @netstat = `netstat -an | grep 9001 | grep ESTABLISHED | cut -d" " -f2`;
     
    # foreach client found
    foreach $conn (@netstat)
            {
            if($conn =~ /(\d+\.\d+\.\d+\.\d+)\.(\d+)/)
                    {
                    if($2 != 9001) # if the port connection of the client is different than 9001
                            {
                            $ip[$compt]=$1; # we add the client IP address in the array of IP
                            $compt++; # we increment the number of client found
                            }
                    }
            }
     
    #################### We search the local IP address ###############
     
    # we use the netstat because we know that the Server listen on the 9001 port
    @tablocalip = `netstat -an | grep 9001 | grep ESTABLISHED | cut -d" " -f1 | grep 9001`;
    # we format the string IP, erasing the dot and the port number
    ($iplocal) = ($tablocalip[0] =~ m/(\d+\.\d+\.\d+\.\d+)\.\d+/);
    # we display this information on the screen
    print "\nLocal IP address : ".$iplocal."\n";
    # print the number of client that we have to backup
    print "Number of clients : ".(scalar(@ip))."\n";
     
    ##################### Telnet prompt pattern ######################
     
    # for the telnet connection we have to wait for the prompt to know when the server have finish is work
    $prompt ='/.*[\$#:>\]\%] *$/';
    # we create a new telnet object
    $t = new Net::Telnet (Timeout => 20, Prompt => $prompt, Errmode=>'return');
     
     
    ####################### loop for each account ########################
    $i=1; # represent the actual client that we are backuping
     
    foreach $address (@ip)
            {
            $username="******"; # default username for ***** account
            $passwd="*****"; # default password for **** account
            print "\n########################################################################\n";
            print "Client ".$i."/".(scalar(@ip))."\n"; # print the position of the client over the number total of clients
            print $address." -> ".$iplocal."\n"; We display the IP address of the client
            if($address eq $iplocal) # if the client is the Server
                    {
                    $passwd="*****"; # we change the password, because server have a different server
                    }
     
            $t->open($address); # we open a telnet connection with the client address
            $t->login($username, $passwd); # we open a new telnet under the **** account
     
            #################### command to execute #########################
            print "Operating System : ";
            print $t->cmd("uname"); # we display the operating system of the client
            $hostname = ($t->cmd("hostname"))[0]; # we affect to the variable $hostname the name of the client box
            chomp($hostname); # we delete the last caracter of this string which is a "\n"
            print "Nom du client : ".$hostname."\n"; # we display the client name
     
            $archivename=$hostname."_".$date.".tar";
            $compressarchivename=$archivename.".gz";
     
            $t->cmd("/bin/rm -f ".$compressarchivename); # we delete the backup file on the client box if it is already exist
     
            @lines = $t->cmd("ls -l | grep watcher"); # we execut an ls command to check if the watcher directory exist
            foreach $stuff (@lines)
                    {
                    # Display that we said
                    print $stuff; # we print the result
                    }
            print "\n\n";
     
            # we execute a tar command on the watcher directory
            @lines = $t->cmd("tar -cf ".$archivename." watcher");
     
            # we compress the tar file
            @lines = $t->cmd("gzip ".$archivename);
     
            # after compress the archive we have to send it to the Server, for that we use a FTP connection
            $t->cmd("ftp $iplocal"); # open a FTP connection with server
            $t->waitfor("/): /"); # wait for the login prompt
            $t->cmd("*****"); # enter the login
            $t->waitfor("/Password:/"); # wait for password prompt
            $t->cmd("*****"); # enter the password prompt
            $t->waitfor("ftp> "); # wait for FTP prompt
            $t->cmd("bin"); # change the transfert type to binary
            $t->waitfor("ftp> "); # wait for FTP prompt
            $t->cmd("cd clients_backup"); # enter in the backup directory on the box
            $t->waitfor("ftp> "); # wait for the FTP prompt
            $t->cmd("del ".$hostname."_*"); # delete the archive if it exist on the Server
            $t->waitfor("ftp> "); # wait for the FTP prompt
            $t->cmd("put ".$compressarchivename); # transfert the compressed archive
            $t->waitfor("ftp> "); # wait for FTP prompt
            $t->cmd("quit"); # close the FTP connection
            $t->cmd("/bin/rm -f ".compressarchivename); # delete the compressed archive file on the client
            # display that we have finish to backup the box
            print "Backup Client [".$i."] ".$archivename." : Done\n";
            $i++; # increment the number of box
            }
     
    sub time_stamp
            {
            my ($d,$t);
     
     
            my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
     
            $year += 1900;
            $mon++;
     
            $d = sprintf("%4d-%2.2d-%2.2d",$year,$mon,$mday);
            $t = sprintf("%2.2d:%2.2d:%2.2d",$hour,$min,$sec);
            return($d,$t);
    }

  5. #5
    Membre averti Avatar de blackstreet
    Inscrit en
    Avril 2004
    Messages
    304
    Détails du profil
    Informations forums :
    Inscription : Avril 2004
    Messages : 304
    Points : 335
    Points
    335
    Par défaut
    C'est vraiment très gentil.

    Je vais voir de plus près et je vais adapter à mon besoin.

    Je vous remercie pleinement de cette aide si précieuse.

  6. #6
    Membre habitué
    Homme Profil pro
    ingénieur calcul
    Inscrit en
    Décembre 2007
    Messages
    363
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 59
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : ingénieur calcul
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Décembre 2007
    Messages : 363
    Points : 180
    Points
    180
    Par défaut
    C'est un peu vieux comme thread, mais moi j'ai piraté le prompt sur plusieurs machines qui me posait problème; merci,
    David
    P.S. Dis Toto, pourquoi l'univers existe-t'il ?
    Je vais y réfléchir avec Morphée et lui dès avant 22h55, donc ici, il faut se causer avant.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [VB.NET] ListView Problème avec propriété View à 'List'
    Par elkidos dans le forum Windows Forms
    Réponses: 2
    Dernier message: 25/08/2006, 18h10
  2. [VB.net][vs2005] Problème avec les expressions régulières
    Par zouhib dans le forum Windows Forms
    Réponses: 13
    Dernier message: 22/06/2006, 16h56
  3. [VB.NET]petit problème avec la classe string !!
    Par zouhib dans le forum Windows Forms
    Réponses: 6
    Dernier message: 01/06/2006, 12h58
  4. [VB.NET] [CR] Probléme avec Crystal Report.
    Par Silvia12 dans le forum Windows Forms
    Réponses: 3
    Dernier message: 15/03/2005, 15h18
  5. [.NET][GLUT] problème avec iostream
    Par polonain2 dans le forum OpenGL
    Réponses: 7
    Dernier message: 17/03/2004, 18h24

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo