brauche Hilfe für ssh connection in java

sanaline

Mitglied
Hallo Alle,

ich bin ziemlich neu mit Java Programmierung und ich muss eine Aufgabe erledigen.

Ich muss durch den click von "start" mit dem eingegebenen Servername, User und Password durch ssh Verbindung in einem Rechner unter Unix zugreifen und alles durch cron-jobs.

Ich habe schon das 1. Teil der Aufgabe erledigt entspricht die GUI Programmierung...
Jetzt weiss ich nicht wie ich genau starten soll um die ssh verbindung zu programmieren (mit cron-jobs da hinter).
Es wurde mir Generated Documentation (Untitled) - für SSH

cron4j - Documentation and manual - für cron-Jobs

hat jemand schon damit programmiert und kann mir Tipps oder schrittweise erklären wie ich mit dem Problem klar kommen kann?

MfG.

Javacode:

Java:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;


public class Test extends JFrame {

    /**
     * @param args
     */

    final static int width = 400;
    final static int length = 400;


    public Test () {
        setTitle("Erste Gui Fenster");
        setSize (width, length);
        GridBagLayout layout = new GridBagLayout();

        setLayout(new GridBagLayout());

        JPanel pnl = new JPanel(layout);


        GridBagConstraints cons = new GridBagConstraints();
        cons.gridx =1;
        cons.gridy =2;
        cons.anchor = GridBagConstraints.LINE_END;
        JButton start = new JButton("start");
        getContentPane().add(start,cons);

        GridBagConstraints c = new GridBagConstraints();
        JLabel texte1 = new JLabel("Servername:");
        c.anchor = GridBagConstraints.LINE_START;
        c.gridx = 1;
        c.gridy = 1;
        pnl.add(texte1, c);
        JLabel texte2 = new JLabel("Rechnerprogramme:");
        c.gridy = 2;
        pnl.add(texte2, c);
        JLabel texte3 = new JLabel("User:");
        c.gridy = 3;
        pnl.add(texte3, c);
        JLabel texte4 = new JLabel("Passwort:");
        c.gridy = 4;
        pnl.add(texte4, c);





        JTextField eingabe1 = new JTextField();
        eingabe1.setPreferredSize(new Dimension(200,20));
        c.gridx = 2;
        c.gridy = 1;
        pnl.add(eingabe1,c);
        JTextField eingabe2 = new JTextField();
        eingabe2.setPreferredSize(new Dimension(200,20));
        c.gridy = 2;
        pnl.add(eingabe2, c);
        JTextField eingabe3 = new JTextField();
        eingabe3.setPreferredSize(new Dimension(200,20));
        c.gridy = 3;
        pnl.add(eingabe3, c);
        JPasswordField passwordField = new JPasswordField();
        passwordField.setPreferredSize(new Dimension(200,20));
        c.gridy = 4;
        pnl.add(passwordField, c);

        setVisible(true);
        cons.gridy = 1;
        cons.anchor = GridBagConstraints.LINE_START;
        getContentPane().add(pnl,cons);



    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new Test();

    }

}
 
vielleicht löst du die probleme nacheinander und nicht alle auf einmal.
wie man eine verbindung mit einem server via ssh aufnimmt verrät dir google. wenn du das geschafft hast, ist es zeit sich gedanken darüber zu machen was genau cron-jobs sind und wie man sie einrichtet. im übrigen verrät auch das dir google.
 
hallo,

ich habe versuch aber es macht gar nichts was ich will....

Ich mochte nach dem click des Starts, das ein shell console sich oeffnen um fragt noch mal nach passwort und danah kann ich noch den pfad eingeben usw....

ich habe das Gefuehl dass die Loesung ist wenn ich diese beide Programme richtig binden kann...
aber wie genau was ich noch nicht...

Ich bitte um Hilfe.

Java:
import java.awt.Dimension;
//import java.awt.Frame;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
//import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//import java.awt.event.WindowListener;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Properties;
//import java.util.Properties;


import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import com.mindbright.gui.AWTConvenience;
import com.mindbright.jca.security.SecureRandom;
import com.mindbright.ssh2.SSH2ConsoleRemote;
import com.mindbright.ssh2.SSH2FTPProxyFilter;
import com.mindbright.ssh2.SSH2HostKeyVerifier;
import com.mindbright.ssh2.SSH2Interactor;
import com.mindbright.ssh2.SSH2Preferences;
import com.mindbright.ssh2.SSH2SimpleClient;
import com.mindbright.ssh2.SSH2StreamFilterFactory;
import com.mindbright.ssh2.SSH2StreamSniffer;
import com.mindbright.ssh2.SSH2TerminalAdapterImpl;
import com.mindbright.ssh2.SSH2Transport;
import com.mindbright.ssh2.SSH2UserCancelException;
import com.mindbright.terminal.GlobalClipboard;
import com.mindbright.terminal.LineReaderTerminal;
import com.mindbright.terminal.TerminalFrameTitle;
import com.mindbright.terminal.TerminalMenuHandler;
import com.mindbright.terminal.TerminalMenuHandlerFull;
import com.mindbright.terminal.TerminalMenuListener;
import com.mindbright.terminal.TerminalWin;
import com.mindbright.util.RandomSeed;
import com.mindbright.util.SecureRandomAndPad;
import com.mindbright.util.Util;

public class BasicClient2 extends javax.swing.JFrame implements SSH2Interactor, TerminalMenuListener, Runnable{

   private Frame              frame;
    private TerminalWin        terminal;
   private SSH2Transport      transport;
    private SSH2SimpleClient   client;
    private SSH2ConsoleRemote  console;
    private Properties         props;
   private LineReaderTerminal lineReader;
   private int                exitStatus;
    private String             host;
    private String             passwd;
    @SuppressWarnings("unused")
    private String             pfad;
    private String             user;
    private JButton start ;
    private JLabel texte1 , texte2 , texte3 , texte4;
    final static int width = 400;
    final static int length = 400;


    public BasicClient2(Properties props) {
        this.props      = props;
        this.exitStatus = 1;

    setTitle("Erste Gui Fenster");
        setSize (width, length);
        GridBagLayout layout = new GridBagLayout();

        setLayout(new GridBagLayout());

        JPanel pnl = new JPanel(layout);


        GridBagConstraints cons = new GridBagConstraints();
        cons.gridx =1;
        cons.gridy =2;
        cons.anchor = GridBagConstraints.LINE_END;
         start = new JButton("start");
        getContentPane().add(start,cons);

        GridBagConstraints c = new GridBagConstraints();
         texte1 = new JLabel("Servername:");
        c.anchor = GridBagConstraints.LINE_START;
        c.gridx = 1;
        c.gridy = 1;
        pnl.add(texte1, c);
         texte2 = new JLabel("Rechnerprogramme:");
        c.gridy = 2;
        pnl.add(texte2, c);
         texte3 = new JLabel("User:");
        c.gridy = 3;
        pnl.add(texte3, c);
         texte4 = new JLabel("Passwort:");
        c.gridy = 4;
        pnl.add(texte4, c);





        JTextField eingabe1 = new JTextField();
        eingabe1.setPreferredSize(new Dimension(200,20));
        c.gridx = 2;
        c.gridy = 1;
        pnl.add(eingabe1,c);
        JTextField eingabe2 = new JTextField();
        eingabe2.setPreferredSize(new Dimension(200,20));
        c.gridy = 2;
        pnl.add(eingabe2, c);
        JTextField eingabe3 = new JTextField();
        eingabe3.setPreferredSize(new Dimension(200,20));
        c.gridy = 3;
        pnl.add(eingabe3, c);
        JPasswordField passwordField = new JPasswordField();
        passwordField.setPreferredSize(new Dimension(200,20));
        c.gridy = 4;
        pnl.add(passwordField, c);

        setVisible(true);
        cons.gridy = 1;
        cons.anchor = GridBagConstraints.LINE_START;
        getContentPane().add(pnl,cons);

        start.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startActionPerformed(evt);
            }


        });
    
    }



 int port = 22 ;
 
    //############################################################################
 
private void startActionPerformed(ActionEvent evt) {
    BasicClient2 ssh2 = new BasicClient2(props);
    ssh2.run();
    System.exit(ssh2.getExitStatus());
    
 }
 
 @SuppressWarnings("deprecation")
    public void run() {
     try {
         int port;
         //String user;
         host = texte1.getText();
         pfad = texte2.getText();
         user = texte3.getText();
         passwd = texte4.getText();

         /*
          * Create and show terminal window
          */
         boolean haveMenus = Boolean.valueOf(
             props.getProperty("havemenus")).booleanValue();
       
         frame = (haveMenus ? AWTConvenience.newFrameWithMenuBar() :
                  new Frame());
         terminal = new TerminalWin(frame, props);

         RandomSeed seed = new RandomSeed();
         terminal.addAsEntropyGenerator(seed);

         frame.setLayout(new BorderLayout());
         frame.add(terminal.getPanelWithScrollbar(), BorderLayout.CENTER);

         TerminalFrameTitle frameTitle =
             new TerminalFrameTitle(frame, getTitle());
         frameTitle.attach(terminal);

         if(haveMenus) {
             try {
                 TerminalMenuHandler tmenus =
            TerminalMenuHandlerFull.getInstance(frame);
            tmenus.setTitleName(getTitle());
            tmenus.addBasicMenus(terminal, frame);
            tmenus.setTerminalMenuListener(this);
             } catch (Throwable t) {
             }
         } else {
             terminal.setClipboard(GlobalClipboard.getClipboardHandler());
         }
         frame.addWindowListener(terminal);

         frame.pack();
         frame.show();

         /*
          * Prompt for where to connect to
          */
         lineReader = new LineReaderTerminal(terminal);

         host = props.getProperty("server");
         port = getPort(props.getProperty("port"));
         user = props.getProperty("user");

         terminal.write("Basic SSH2 client demo\n\r");
        
          while (host == null) {
             host = lineReader.promptLine("\r\nssh2 server[:port]: ",
                                          null, false);
         }

         port = Util.getPort(host, port);
         host = Util.getHost(host);

         while (user == null) {
             user = lineReader.promptLine(host + " login: ", null, false);
         }

         // Create the preferences object
         SSH2Preferences prefs = new SSH2Preferences(props);

         // This shows how to force certain properties
         //prefs.setPreference(SSH2Preferences.CIPHERS_C2S, "blowfish-cbc");
         //prefs.setPreference(SSH2Preferences.CIPHERS_S2C, "blowfish-cbc");
         //prefs.setPreference(SSH2Preferences.LOG_LEVEL, "9");
         //prefs.setPreference(SSH2Preferences.LOG_FILE, "ssh2out.log");

         // It is important that the random number generator here is good!
         SecureRandomAndPad secureRandom =
             new SecureRandomAndPad(new SecureRandom(seed.getBytesBlocking(20, false)));

         /*
          * Open the TCP connection to the server and create the
          * SSH2Transport object. No traffic will be sent yet.
          */
         transport = new SSH2Transport(new Socket(host, port), prefs,
                                       secureRandom);

         /*
          * Prepare for host fingerprint verification.
          * This implementation check fingerprints agains properties of
          * the form: fingerprint.HOSTNAME.PORT
          */
         String fingerprint = props.getProperty("fingerprint." +
                                                host + "." + port);

         /*
          * If we found a fingerprint property for this host:port then
          * create a key verifier which checks that the fingerprint of the
          * actual host matches.
          */
         if(fingerprint != null) {
             transport.setEventHandler(new SSH2HostKeyVerifier(fingerprint));
         }

         client = null;

         /*
          * This simple client can only authenticate using either
          * publickey or passwords. Depending on which it uses
          * different constructors of SSH2SimpleClient.
          *
          * The actual password to use can be stored in the
          * properties. This has severe security implications
          * though.
          *
          * The construction of SSH2SimpleClient will start up the
          * session and cause the encrypted connection to be
          * establiushed and the user to be authenticated.
          */
         String auth = props.getProperty("auth-method");
         if("publickey".equals(auth)) {
             String keyFile   = props.getProperty("private-key");
             String keyPasswd = props.getProperty("passphrase");
             client = new SSH2SimpleClient(transport, user, keyFile,
                                           keyPasswd);
         } else {
             passwd = props.getProperty("password");
             while (passwd ==  null) {
                 passwd = lineReader.promptLine(
                     user + "@" + host + "'s password: ", null, true);
             }
             client = new SSH2SimpleClient(transport, user, passwd);
         }

         // This class will not interact with the user anymore.
         lineReader.detach();

         // Start any portforwards defined in the preferences.
         startForwards();

         /*
          * Create the remote console to use for command execution.
          */
         console = new SSH2ConsoleRemote(client.getConnection());

         SSH2TerminalAdapterImpl termAdapter =
             new SSH2TerminalAdapterImpl(terminal);

         if(!console.terminal(termAdapter)) {
             throw new Exception("Couldn't start terminal!");
         }

         // Wait for user to close remote shell
         exitStatus = console.waitForExitStatus();

     } catch (LineReaderTerminal.ExternalMessageException e) {
         // ignore
     } catch (Exception e) {
         System.out.println("An error occured: " + e.getMessage());
     } finally {
         if(frame != null) {
             frame.dispose();
         }
     }
 }

 /**
  * Get the exit status from the SSH2ConsoleRemote instance
  *
  * @return the exit status
  */
 public int getExitStatus() {
     return exitStatus;
 }

 /**
  * Starts any portforwards specified in the properties.
  */
 private void startForwards() {
     int i;
     for(i = 0; i < 32; i++) {
         String spec = props.getProperty("local" + i);
         if(spec == null)
             break;
         Object[] components = Util.parseForwardSpec(spec, "127.0.0.1");
         try {
             SSH2StreamFilterFactory filter = null;
             if("ftp".equals(components[0])) {
                 filter = new SSH2FTPProxyFilter((String)components[1],
                                                 host);
             } else if("sniff".equals(components[0])) {
                 filter = SSH2StreamSniffer.getFilterFactory();
             }
             client.getConnection().
             newLocalForward((String)components[1],
                             ((Integer)components[2]).intValue(),
                             (String)components[3],
                             ((Integer)components[4]).intValue(),
                             filter);
             terminal.write("started local forward: " + spec + "\n\r");
         } catch (IOException e) {
             terminal.write("failed local forward: " + spec +
                            e.getMessage() + "\n\r");
         }
     }
     for(i = 0; i < 32; i++) {
         String spec = props.getProperty("remote" + i);
         if(spec == null)
             break;
         Object[] components = Util.parseForwardSpec(spec, "127.0.0.1");
         client.getConnection().newRemoteForward((String)components[1],
                                                 ((Integer)components[2]).intValue(),
                                                 (String)components[3],
                                                 ((Integer)components[4]).intValue());
         terminal.write("started remote forward: " + spec + "\n\r");
     }
 }

 /**
  * Get the port number of the ssh server stored in the
  * string. Defaults to 22, the ssh standard port, if none is
  * specified.
  */
 private static int getPort(String port) {
     int p;
     try {
         p = Integer.parseInt(port);
     } catch (Exception e) {
         p = 22;
     }
     return p;
 }

 /*private String getTitle() {
     return "Basic SSH2 Client";
 }*/

 /**
  * Close the connection to the server (if any) in a controlled way.
  */
 public void doClose() {
     if(lineReader != null) {
         lineReader.breakPromptLine("");
     }
     if(console != null) {
         console.close();
     }
     if(transport != null) {
         transport.normalDisconnect("User disconnects");
     }
 }

 /**
  * Overide corresponding function in java.awt.event.WindowAdapter
  */
 public void windowClosing(WindowEvent e) {
     doClose();
 }

 /*
  * TerminalMenuListener interface implementation
  */
 public void close(TerminalMenuHandler origMenu) {
     doClose();
 }

 public void update() {
     // Ignore
 }

 /**
  * Run the application
  */
 


 public static void main(String[] argv) {
     Properties props = new Properties();
     if(argv.length > 0) {
         String propsFile = argv[0];
         try {
             props.load(new FileInputStream(propsFile));
         } catch (Exception e) {
             System.out.println("Error loading properties: " +
                                e.getMessage());
         }
     }
     new BasicClient2(props);
    
 }

 /*
  * SSH2Interactor interface
  */
 public String promptLine(String prompt, boolean echo)
     throws SSH2UserCancelException {
     return passwd;
 }
 public String[] promptMulti(String[] prompts, boolean[] echos)
     throws SSH2UserCancelException {
     return promptMultiFull("", "", prompts, echos);
 }
 public String[] promptMultiFull(String name, String instruction,
                                 String[] prompts, boolean[] echos)
     throws SSH2UserCancelException {
     if (prompts.length == 1) {
         return new String[]{passwd};
     } else if (prompts.length == 0) {
         return new String[0];
     }
     throw new SSH2UserCancelException();
 }
 public int promptList(String name, String instruction, String[] choices)
     throws SSH2UserCancelException {
     throw new SSH2UserCancelException();
 }
}
 
Hallo,

was ist den die Frage? - Wenn du hier eine fertige Lösung haben möchtest ohne eigene Bemühungen, dann wird das nur jemand machen, dem du Geld gibst 😉

Wo genau ist das Problem? Was verstehst du nicht?

Gruß,

Martin
 
hallo,

ich verstehe nicht mit welche methode kann ich was ich in dem Gui Fenster eingebe, in dem Console oder shell Fenster lesen kann so dass ich direct in den shell fenster zu dem eingegebene Pfad zugreifen kann und den rest zum beispiel starten einem bestimmten Programm die sich auf den pfad befinden, kann.

Ich möchte nicht unbedingt die gesamte Lösung aber Tipps , methode...

MfG.
 
Hi,

das ist nicht das trivialiste Thema.

Man kann auch nicht sagen "Diese Methode musst du nehmen", weil hier bestimmte Konzepte angewendet werden.

Du musst das PW/Account von dem User abfragen. Das kann man am einfachsten mit einer JOption Pane.

Dann musst du die Resultate in das Framework schicken. Habe den code nicht ganz gelesen, aber es sind die notwendigen Felder schon vorhanden.
 
Ich habe selber probiere und schaffe ich schon die gegebene Eingabe im Fenster für die SSH Verbindung zu lesen. Es fehlt mir noch das richtige methode um verbindung zu bauen.
Ich habe den Code für SSH1Connection schon in einem Beispiel genommen.
Ich schicke in den nächsten die beide Code.

MfG.
 

Neue Themen


Zurück
Oben