2013-05-09 30 views
11

Sto provando a impostare una classe in modo da poter eseguire ssh su un server remoto (ho l'IP, nome utente e password) e quindi inviare un comando come " echo "test" "e quindi ricevere di nuovo l'output (ad es." test "). Sto usando JSch per farlo, ma non capisco come farlo.Invio di comandi al server remoto tramite ssh tramite Java con JSch

import com.jcraft.jsch.*; 

public class ConnectSSH { 

public int execute (String command) { 

    JSch jsch = new JSch(); 
    String ip = "00.00.00.00; 
    String user = "root"; 
    String pass = "password"; 
    int port = 22; 

    try {     
     Session session = jsch.getSession(user, ip, port); 
     session.setPassword(pass); 
     session.connect(); 

      ... 

Non sono sicuro di cosa fare, sono bloccato dopo la connessione.

Qualsiasi consiglio è molto apprezzato.

risposta

2

Suggerisco di guardare l'esempio nascosta sul sito JCraft: http://www.jcraft.com/jsch/examples/UserAuthKI.java

Il loro esempio richiede nome utente, nome host, la password, quindi è pronto per il test fuori dalla scatola. L'ho eseguito sulla mia rete e sono riuscito a connettermi a un server AIX senza modificare alcun codice.

Nota, il loro esempio ha un problema (questo potrebbe essere il motivo per cui è nascosto) .. non chiude mai il canale. Se si invia "esci", il server si disconnetterà, ma l'oggetto canale rimane aperto e il programma Java non si chiude mai. Ho fornito una correzione per questo qui: Never ending of reading server response using jSch

24

Prova questa: risposta

JSch jsch=new JSch(); 
Session session=jsch.getSession(remoteHostUserName, RemoteHostName, 22); 
session.setPassword(remoteHostpassword); 
Properties config = new Properties(); 
config.put("StrictHostKeyChecking", "no"); 
session.setConfig(config); 
session.connect(); 

ChannelExec channel=(ChannelExec) session.openChannel("exec"); 
BufferedReader in=new BufferedReader(new InputStreamReader(channel.getInputStream())); 
channel.setCommand("pwd;"); 
channel.connect(); 

String msg=null; 
while((msg=in.readLine())!=null){ 
    System.out.println(msg); 
} 

channel.disconnect(); 
session.disconnect(); 
+0

Come eseguire più comandi come se voglio eseguire "cd xx/xx/xx" e quindi controllare "pwd" – Vinod

+0

avuto la mia risposta qui: http://stackoverflow.com/questions/ 5831594/multiple-commands-through-jsch-shell/5831846 # 5831846, grazie – Vinod

9

di shamnu sopra aveva ragione. Non ho potuto aggiungere un commento, quindi ecco alcuni esempi per migliorare la sua risposta. Uno è come eseguire un'esecuzione remota di "ls -l", un'altra di "mkdir" e un'altra di una copia locale-remota. Tutto fatto con la versione 0.1.51 di jsch (http://www.jcraft.com/jsch/).

public void remoteLs() throws JSchException, IOException { 
    JSch js = new JSch(); 
    Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22); 
    s.setPassword("mypassword"); 
    Properties config = new Properties(); 
    config.put("StrictHostKeyChecking", "no"); 
    s.setConfig(config); 
    s.connect(); 

    Channel c = s.openChannel("exec"); 
    ChannelExec ce = (ChannelExec) c; 

    ce.setCommand("ls -l"); 
    ce.setErrStream(System.err); 

    ce.connect(); 

    BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream())); 
    String line; 
    while ((line = reader.readLine()) != null) { 
     System.out.println(line); 
    } 

    ce.disconnect(); 
    s.disconnect(); 

    System.out.println("Exit code: " + ce.getExitStatus()); 

    } 



    public void remoteMkdir() throws JSchException, IOException { 
    JSch js = new JSch(); 
    Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22); 
    s.setPassword("mypassword"); 
    Properties config = new Properties(); 
    config.put("StrictHostKeyChecking", "no"); 
    s.setConfig(config); 
    s.connect(); 

    Channel c = s.openChannel("exec"); 
    ChannelExec ce = (ChannelExec) c; 

    ce.setCommand("mkdir remotetestdir"); 
    ce.setErrStream(System.err); 

    ce.connect(); 

    BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream())); 
    String line; 
    while ((line = reader.readLine()) != null) { 
     System.out.println(line); 
    } 

    ce.disconnect(); 
    s.disconnect(); 

    System.out.println("Exit code: " + ce.getExitStatus()); 

    } 

    public void remoteCopy() throws JSchException, IOException, SftpException { 
    JSch js = new JSch(); 
    Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22); 
    s.setPassword("mypassword"); 
    Properties config = new Properties(); 
    config.put("StrictHostKeyChecking", "no"); 
    s.setConfig(config); 
    s.connect(); 

    Channel c = s.openChannel("sftp"); 
    ChannelSftp ce = (ChannelSftp) c; 

    ce.connect(); 

    ce.put("/home/myuser/test.txt","test.txt"); 

    ce.disconnect(); 
    s.disconnect();  
    } 
+1

Solo una nota, se tutto quello che stai facendo è operazioni sui file puoi usare [ChannelSftp] (http://epaul.github.io/jsch- documentation/simple.javadoc/com/jcraft/jsch/ChannelSftp.html) che fornisce metodi come cd(), mkdir() e put(). – perilandmishap

0
1. List item 

import java.io.InputStream; 

import com.jcraft.jsch.Channel; 
import com.jcraft.jsch.ChannelExec; 
import com.jcraft.jsch.JSch; 
import com.jcraft.jsch.Session; 

public class SSHCommandExecutor { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     String host="10.75.81.21"; 
     String user="root"; 
     String password="Avaya_123"; 
     String command1="ls -l"; 
     try{ 

      java.util.Properties config = new java.util.Properties(); 
      config.put("StrictHostKeyChecking", "no"); 
      JSch jsch = new JSch(); 
      Session session=jsch.getSession(user, host, 22); 
      session.setPassword(password); 
      session.setConfig(config); 
      session.connect(); 
      System.out.println("Connected"); 

      Channel channel=session.openChannel("exec"); 
      ((ChannelExec)channel).setCommand(command1); 
      channel.setInputStream(null); 
      ((ChannelExec)channel).setErrStream(System.err); 

      InputStream in=channel.getInputStream(); 
      channel.connect(); 
      byte[] tmp=new byte[1024]; 
      while(true){ 
       while(in.available()>0){ 
       int i=in.read(tmp, 0, 1024); 
       if(i<0)break; 
       System.out.print(new String(tmp, 0, i)); 
       }`enter code here` 
       if(channel.isClosed()){ 
       System.out.println("exit-status: "+channel.getExitStatus()); 
       break; 
       } 
       try{Thread.sleep(1000);}catch(Exception ee){} 
      } 
      channel.disconnect(); 
      session.disconnect(); 
      System.out.println("DONE"); 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 

    } 


1. List item 

} 
+0

Potete per favore elaborare la vostra soluzione? – CAFEBABE

+0

questo è da [Qui] (http://www.jcraft.com/jsch/examples/Exec.java.html) – rrw

Problemi correlati