前一篇文章(https://www.poisonbian.com/post-468.html)说到如何在java中调用shell脚本.

这次再说下在java中如何使用ssh命令.

首先, 需要有jsch包的支持, 下载地址: jsch-0.1.44

下面就是使用jsch远程ssh到某台机器上执行命令的代码, 调用的时候只需要按照main中的传入参数就可以了~

package dashboard;

/**
 * 
 */

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

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

/**
 * @author bian_wei
 *
 */
public class JavaSSH {
        public static String sshExecute(String host, String user, String pwd,
            String command) {
                //ps -ef¦grep tomcat¦grep -v grep¦awk '{print $2}'
                StringBuffer sb = new StringBuffer();
        try 
        {
                JSch jsch = new JSch();
            jsch.setKnownHosts("~/.ssh/known_hosts");
            Session session = jsch.getSession(user, host, 22);
            session.setPassword(pwd);
            Properties config = new Properties();  
            config.put("StrictHostKeyChecking", "no"); 
            session.setConfig(config);

            session.connect();
            Channel channel = session.openChannel("exec");
            ((ChannelExec)channel).setCommand(command);

            BufferedReader fromServer = new BufferedReader(
                        new InputStreamReader((channel.getInputStream())));
            channel.connect();
            Thread.sleep(1000);
            while (fromServer.ready()) {
                String tt = fromServer.readLine();
                sb.append(tt+'\n');
            }
            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString().trim();
    }

        /**
         * @param args
         */
        public static void main(String[] args) {
                // TODO Auto-generated method stub
                System.out.println(JavaSSH.sshExecute("machine_name","user","password","ls -l"));
        }

}