SSHExec.java 1.96 KB
package org.emercit.sshexec;


import java.util.Properties;

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

import java.io.InputStream;
import java.io.OutputStream;

import org.apache.log4j.Logger;


public class SSHExec {
	
	private static final Logger log = Logger.getLogger(SSHExec.class);

	Properties config = new Properties(); 
	
	private String login;
	
	private String password;
	
	private String host;
	
	private int port;
	
	private String cmd;
	
	public SSHExec() { 
		 config.put("StrictHostKeyChecking", "no");
	}
	
	public void setLogin(String value) {
		this.login=value;
	}
	
	public void setPassword(String value) { 
		this.password=value;
	}
	
	public void setHost(String value) { 
		this.host=value;
	}
	
	public void setPort(int value){
		this.port=value;
	}
	
	public void setCmd(String value) {
		this.cmd=value;
	}
	
	public void Exec() throws Exception {

		JSch jsch = new JSch();
	        Session session=jsch.getSession(this.login, this.host, this.port);
	        session.setPassword(password);
	        session.setConfig(config);
	        session.connect();
        
	        Channel channel=session.openChannel("exec");
      
	        ((ChannelExec)channel).setCommand("sudo -S -p '' "+cmd);
   
	        InputStream in=channel.getInputStream();
	        OutputStream out=channel.getOutputStream();
	        ((ChannelExec)channel).setErrStream(System.err);
   
	        channel.connect();
   
	        out.write((password+"\n").getBytes());
	        out.flush();
   
	        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));
	        	}
		        if(channel.isClosed()){
		        	break;
		        }
	        	try{Thread.sleep(1000);}catch(Exception ee){}
	         }
        channel.disconnect();
        session.disconnect();

	}	
}