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

Sécurité Java Discussion :

Se connecter à un serveur via SSH


Sujet :

Sécurité Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre chevronné
    Inscrit en
    Août 2010
    Messages
    416
    Détails du profil
    Informations forums :
    Inscription : Août 2010
    Messages : 416
    Par défaut Se connecter à un serveur via SSH
    Bonjour, je veux me connecter a un serveur en utilisant SSH afin d'exécuté un script, j'ai trouvé la lib Java Secure Channel (JSCH)
    mais je n'ai pas sur comment l'utiliser

    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
    package marouene;
    import com.jcraft.jsch.*;
    import java.awt.*;
    import javax.swing.*;
     
    public class ssh{
      public static void main(String[] arg){
     
        try{
          JSch.setLogger(new MyLogger());
          JSch jsch=new JSch();
     
          Session session=jsch.getSession("usr", "server", 22);
          session.setPassword("passwd");
     
          session.connect();
     
          Channel channel=session.openChannel("shell");
     
          channel.setInputStream(System.in);
          channel.setOutputStream(System.out);
     
          channel.connect();
        }
        catch(Exception e){
          System.out.println(e);
        }
      }
     
      public static class MyLogger implements com.jcraft.jsch.Logger {
        static java.util.Hashtable name=new java.util.Hashtable();
        static{
          name.put(new Integer(DEBUG), "DEBUG: ");
          name.put(new Integer(INFO), "INFO: ");
          name.put(new Integer(WARN), "WARN: ");
          name.put(new Integer(ERROR), "ERROR: ");
          name.put(new Integer(FATAL), "FATAL: ");
        }
        public boolean isEnabled(int level){
          return true;
        }
        public void log(int level, String message){
          System.err.print(name.get(new Integer(level)));
          System.err.println(message);
        }
      }
    }
    ne marche pas


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    com.jcraft.jsch.JSchException: UnknownHostKey: server. RSA key fingerprint is ec:af:01:4b:ec:a9:a0:2

  2. #2
    Expert confirmé
    Avatar de Marco46
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Août 2005
    Messages
    4 419
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Août 2005
    Messages : 4 419
    Par défaut
    Déjà, es-tu sûr de savoir utiliser SSH ?

  3. #3
    Membre chevronné
    Inscrit en
    Août 2010
    Messages
    416
    Détails du profil
    Informations forums :
    Inscription : Août 2010
    Messages : 416
    Par défaut
    bein je l'utilise d'une facon standard (genre avec putty ...)

  4. #4
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    UnknownHostKey: server. RSA key fingerprint is ec:af:01:4b:ec:a9:a0:2
    L'hote n'est pas dans la liste des hotes reconnus (fichier "knownhosts") et donc jsch tout naturellement te dit qu'il refuse de s'y connecter puisque ça représente un trou de sécurité.

    Voir un exemple ici de confirmation de l'hote
    http://www.jcraft.com/jsch/examples/KnownHosts.java

  5. #5
    Membre chevronné
    Inscrit en
    Août 2010
    Messages
    416
    Détails du profil
    Informations forums :
    Inscription : Août 2010
    Messages : 416
    Par défaut
    D'accord je vais essayer ca merci

  6. #6
    Membre chevronné
    Inscrit en
    Août 2010
    Messages
    416
    Détails du profil
    Informations forums :
    Inscription : Août 2010
    Messages : 416
    Par défaut
    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
    /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
    import com.jcraft.jsch.*;
    import java.awt.*;
    import javax.swing.*;
     
    public class KnownHosts{
      public static void main(String[] arg){
     
        try{
          JSch jsch=new JSch();
     
          JFileChooser chooser = new JFileChooser();
          chooser.setDialogTitle("Choose your known_hosts(ex. ~/.ssh/known_hosts)");
          chooser.setFileHidingEnabled(false);
          int returnVal=chooser.showOpenDialog(null);
          if(returnVal==JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose "+
    			   chooser.getSelectedFile().getAbsolutePath()+".");
    	jsch.setKnownHosts(chooser.getSelectedFile().getAbsolutePath());
          }
     
          HostKeyRepository hkr=jsch.getHostKeyRepository();
          HostKey[] hks=hkr.getHostKey();
          if(hks!=null){
    	System.out.println("Host keys in "+hkr.getKnownHostsRepositoryID());
    	for(int i=0; i<hks.length; i++){
    	  HostKey hk=hks[i];
    	  System.out.println(hk.getHost()+" "+
    			     hk.getType()+" "+
    			     hk.getFingerPrint(jsch));
    	}
    	System.out.println("");
          }
     
          String host=null;
          if(arg.length>0){
            host=arg[0];
          }
          else{
            host=JOptionPane.showInputDialog("Enter username@hostname",
                                             System.getProperty("user.name")+
                                             "@localhost"); 
          }
          String user=host.substring(0, host.indexOf('@'));
          host=host.substring(host.indexOf('@')+1);
     
          Session session=jsch.getSession(user, host, 22);
     
          // username and password will be given via UserInfo interface.
          UserInfo ui=new MyUserInfo();
          session.setUserInfo(ui);
     
          /*
          // In adding to known_hosts file, host names will be hashed. 
          session.setConfig("HashKnownHosts",  "yes");
          */
     
          session.connect();
     
          {
    	HostKey hk=session.getHostKey();
    	System.out.println("HostKey: "+
    			   hk.getHost()+" "+
    			   hk.getType()+" "+
    			   hk.getFingerPrint(jsch));
          }
     
          Channel channel=session.openChannel("shell");
     
          channel.setInputStream(System.in);
          channel.setOutputStream(System.out);
     
          channel.connect();
        }
        catch(Exception e){
          System.out.println(e);
        }
      }
     
      public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
        public String getPassword(){ return passwd; }
        public boolean promptYesNo(String str){
          Object[] options={ "yes", "no" };
          int foo=JOptionPane.showOptionDialog(null, 
                 str,
                 "Warning", 
                 JOptionPane.DEFAULT_OPTION, 
                 JOptionPane.WARNING_MESSAGE,
                 null, options, options[0]);
           return foo==0;
        }
     
        String passwd;
        JTextField passwordField=(JTextField)new JPasswordField(20);
     
        public String getPassphrase(){ return null; }
        public boolean promptPassphrase(String message){ return true; }
        public boolean promptPassword(String message){
          Object[] ob={passwordField}; 
          int result=
    	  JOptionPane.showConfirmDialog(null, ob, message,
    					JOptionPane.OK_CANCEL_OPTION);
          if(result==JOptionPane.OK_OPTION){
    	passwd=passwordField.getText();
    	return true;
          }
          else{ return false; }
        }
        public void showMessage(String message){
          JOptionPane.showMessageDialog(null, message);
        }
        final GridBagConstraints gbc = 
          new GridBagConstraints(0,0,1,1,1,1,
                                 GridBagConstraints.NORTHWEST,
                                 GridBagConstraints.NONE,
                                 new Insets(0,0,0,0),0,0);
        private Container panel;
        public String[] promptKeyboardInteractive(String destination,
                                                  String name,
                                                  String instruction,
                                                  String[] prompt,
                                                  boolean[] echo){
          panel = new JPanel();
          panel.setLayout(new GridBagLayout());
     
          gbc.weightx = 1.0;
          gbc.gridwidth = GridBagConstraints.REMAINDER;
          gbc.gridx = 0;
          panel.add(new JLabel(instruction), gbc);
          gbc.gridy++;
     
          gbc.gridwidth = GridBagConstraints.RELATIVE;
     
          JTextField[] texts=new JTextField[prompt.length];
          for(int i=0; i<prompt.length; i++){
            gbc.fill = GridBagConstraints.NONE;
            gbc.gridx = 0;
            gbc.weightx = 1;
            panel.add(new JLabel(prompt[i]),gbc);
     
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weighty = 1;
            if(echo[i]){
              texts[i]=new JTextField(20);
            }
            else{
              texts[i]=new JPasswordField(20);
            }
            panel.add(texts[i], gbc);
            gbc.gridy++;
          }
     
          if(JOptionPane.showConfirmDialog(null, panel, 
                                           destination+": "+name,
                                           JOptionPane.OK_CANCEL_OPTION,
                                           JOptionPane.QUESTION_MESSAGE)
             ==JOptionPane.OK_OPTION){
            String[] response=new String[prompt.length];
            for(int i=0; i<prompt.length; i++){
              response[i]=texts[i].getText();
            }
    	return response;
          }
          else{
            return null;  // cancel
          }
        }
      }
    }
    je l'ai essayé ca marche, mais est ce que je dois a chaque fois spécifier le fichier ? car cette classe sera utilisé d'une facon périodique pour lancer une commande a l'aide de SSH?
    j'ai essayé ca
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     JSch jsch=new JSch();
     
    jsch.setKnownHosts("~/.ssh/known_hosts");
    mais ca ne marche pas

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

Discussions similaires

  1. Se connecter à un serveur SSH via le finder
    Par Khleo dans le forum Mac OS X
    Réponses: 3
    Dernier message: 26/07/2013, 16h17
  2. redémarrer le serveur via SSH
    Par kiamaru dans le forum Linux
    Réponses: 11
    Dernier message: 17/05/2010, 23h54
  3. Se connecter à un serveur via IOR uniquement
    Par chabimed dans le forum CORBA
    Réponses: 1
    Dernier message: 27/03/2006, 21h31
  4. se connecter à un serveur pop3 via un prory avec auth ??
    Par black_code dans le forum Programmation et administration système
    Réponses: 2
    Dernier message: 20/01/2006, 12h53
  5. putty ssh connection à un serveur apache
    Par pimpmyride dans le forum Autres Logiciels
    Réponses: 6
    Dernier message: 12/12/2005, 14h38

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