Usando ssh2 para acessar ambiente unix

7 respostas
rjpepeu

Fala galera ,
estou fazendo um programinha que irá acessar uma máquina unix, só que eu não estou conseguindo executar os comandos do unix.

Irei descrever minhas classes abaixo:
package br.org.ecad.testeRemoto;
import java.io.BufferedReader;   
import java.io.IOException;   
import java.io.InputStream;   
import java.io.InputStreamReader;   
import java.io.OutputStream;   
import java.io.PrintStream;   
  
import ch.ethz.ssh2.ChannelCondition;   
import ch.ethz.ssh2.Connection;   
import ch.ethz.ssh2.Session;   
import ch.ethz.ssh2.StreamGobbler;   

public class Fabrica {
 
	   
	    private Connection sshConnection;   
	    private Session sshSession;   
	    private String user;   
	    private String password;   
	    private InputStream stdout;   
	    private InputStream stderr;   
	    private OutputStream stdin;   
	    private int state = 0; //0=stopped, 1=started   
	       
	    public Fabrica(String host, String user, String password) {   
	        sshConnection = new Connection(host);   
	        this.user = user;   
	        this.password = password;   
	        this.state = 0;   
	    }   
	       
	    public void start() {   
	        try {   
	            sshConnection.connect();   
	            boolean isAuthenticated = sshConnection.authenticateWithPassword(user, password);   
	               
	            if (isAuthenticated == false)   
	                throw new IOException("A autenticação Falhou.");   
	               
	            sshSession = sshConnection.openSession();             
	            sshSession.startShell();   
	               
	            stdout = new StreamGobbler(sshSession.getStdout());   
	            stderr = new StreamGobbler(sshSession.getStderr());   
	            stdin = sshSession.getStdin();   
	  
	            read(); //consume login message   
	               
	            this.state = 1;   
	               
	        } catch (IOException e) {   
	            // TODO Auto-generated catch block   
	            this.state = 0;   
	            e.printStackTrace();   
	        } catch (InterruptedException e) {   
	            // TODO Auto-generated catch block   
	            this.state = 0;   
	            e.printStackTrace();   
	        }   
	    }   
	       
	    public String read() throws IOException, InterruptedException{   
	        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));   
	        StringBuffer sb = new StringBuffer();   
	        sshSession.waitForCondition(ChannelCondition.EOF, 5000);   
	        while (br.ready())   
	        {   
	            String line = br.readLine();   
	            sb.append(line);   
	        }         
	        return sb.toString();   
	    }   
	       
	    public String readError() throws IOException, InterruptedException{   
	        BufferedReader br = new BufferedReader(new InputStreamReader(stderr));   
	        StringBuffer sb = new StringBuffer();   
	        sshSession.waitForCondition(ChannelCondition.EOF, 5000);   
	        while (br.ready())   
	        {   
	            String line = br.readLine();   
	            sb.append(line);   
	        }         
	        return sb.toString();   
	    }   
	       
	    public void write(String message){   
	        PrintStream ps = new PrintStream(stdin);           
	        ps.println(message);   
	        ps.flush();   
	    }   
	       
	    public void stop() {   
	        sshSession.close();   
	        sshSession.close();   
	        this.state = 0;   
	    }   
	       
	    public String execCommand(String command){   
	        String msg = "NO_ANSWER";   
	           
	        if (state == 0)   
	            start();       
	           
	        try {   
	            write(command);   
	            msg = read();   
	               
	            if (msg.length() <= 0)   
	                msg = readError();   
	               
	        } catch (IOException e) {   
	            e.printStackTrace();   
	        } catch (InterruptedException e) {   
	            e.printStackTrace();   
	        }   
	           
	        return msg;   
	           
	    }   
	}
Agora o main, uma classe de teste.
package br.org.ecad.testeRemoto;

import java.io.IOException;

public class Teste {

	
	public static void main(String[] args) throws IOException, Exception {
	
		Fabrica fb = new Fabrica("ipServidor", "user", "senha");
		
		fb.start();
		fb.execCommand("rm teste.txt");
		System.out.println(fb.read());
		
		
	}

}

Alguém sabe como fazer isso funcionar, porque estou tomando erro(noambiente unix) e o que eu percebi é que funciona com comandos básicos, tipo "ls", "ll", etc.

Abraços

7 Respostas

rjpepeu

estou dando um Up pra ver se alguém me ajuda!!!

Abss

will_guitar_admfar

Entao, aqui funcionou seu codigo
Porem não sai os resultados STDIN que seria a resposta unix

para resolver isso vc precisa imprir antes de fechar a sessao ssh

pois vi que no final que vc tenta imprimir o resultado

rjpepeu

Fala will_guitar_admfar, eu entendi o que você falou, mas não consigo fazer de jeito nenhum.

Tem como me ajudar?

Abs

will_guitar_admfar

Vc esta usando que distribuição ?

e

O ssh-server estar instalado no linux?

e

Vc consegue entrar via putty?

rjpepeu

Vamos lá,

eu uso Windows Xp, na máquina que desenvolvo.

O ambiente que quero acessar é HP-UX(ssh-server).

Consigo entrar sim via putty.

Obrigado!!!

will_guitar_admfar

executa isso…:

package example;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;

import ch.ethz.ssh2.Session;

import ch.ethz.ssh2.StreamGobbler;

public class Basic {

public static void main(String[] args) {
    String hostname = "ipserver";
    String username = "root"; // Caso nao seja root dar permissao nos acesos para tal.
    String password = "senha";

    try {
        /* Create a connection instance */

        Connection conn = new Connection(hostname);

        /* Now connect */

        conn.connect();

        /* Authenticate.
         * If you get an IOException saying something like
         * "Authentication method password not supported by the server at this stage."
         * then please check the FAQ.
         */

        boolean isAuthenticated = conn.authenticateWithPassword(username, password);

        if (isAuthenticated == false) {
            throw new IOException("Authentication failed.");
        }

        /* Create a session */

        Session sess = conn.openSession();

        
        sess.execCommand("useradd -c root -s /bin/false -d /dev/null firegear3");



        
       
       
        {
            System.out.println("************************ LINUX ************************");
            InputStream stdout = new StreamGobbler(sess.getStdout());

            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(line);
            }

            System.out.println("************************ LINUX ************************");
        }

        {

            System.out.println("************************ ERROR LINUX ************************");

            InputStream stdout = new StreamGobbler(sess.getStderr());

            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(line);
            }

            System.out.println("************************ ERROR LINUX ************************");

        }
        /* Show exit status, if available (otherwise "null") */

        System.out.println("ExitCode: " + sess.getExitStatus());

        /* Close this session */

        sess.close();

        /* Close the connection */

        conn.close();

    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(2);
    }
}

}

BILL

Olá pessoal!
estou usando ssh2 também, e estou com uma dúvida, se alguém puder ajudar.

estou tentando deixar uma sessão aberta, para enviar vários comandos.

a conexão já fica aberta, mas estou com problemas não enviar um segundo comando para um servidor na mesma sessão!

o erro é esse:
java.io.IOException: A remote execution has already started.

depois que é executado o primeiro comando, e retornado isso ai!

eu fiz uma modificação na classe de exemplo PublicKeyAuthentication, que vem junto no download do ganymed!

eu quero que minha aplicação finalize a sessão e a conexão!

grato!

Criado 3 de maio de 2011
Ultima resposta 20 de mai. de 2011
Respostas 7
Participantes 3