java使用ssh2远程登录linux/windows并执行命令

阅读更多

1、需要依赖的pom文件配置:


            ch.ethz.ganymed
            ganymed-ssh2
            build209

2、linux下远程可直接连接,windows下需要安装freeSSHd.exe;

3、安装freeSSHd.exe可以参考https://www.cnblogs.com/fuhengheng/p/8043647.html;

4、安装freeSSHd.exe不能安装有空格的地方;如果报错“the specified address is already in use” 运行services.msc停止FreeSSHDService服务;

5、java客户端连接的工作类:

package com.cn.linux.ssh;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class RemoteCommandUtil
{
    private static final Logger log = LoggerFactory.getLogger(RemoteCommandUtil.class);
   
    private static String DEFAULTCHART = "UTF-8";
   
    public static Connection login(String ip, String userName, String userPwd)
    {
        boolean flg = false;
        Connection conn = null;
        try
        {
            conn = new Connection(ip);
            conn.connect();
            flg = conn.authenticateWithPassword(userName, userPwd);
            if (flg)
            {
                log.info("=========登录成功=========" + conn);
                return conn;
            }
        }
        catch (IOException e)
        {
            log.error("=========登录失败=========" + e.getMessage());
            e.printStackTrace();
        }
        return conn;
    }
   
    public static String execute(Connection conn, String cmd)
    {
        String result = "";
        try
        {
            if (conn != null)
            {
                Session session = conn.openSession();
                session.execCommand(cmd);
                result = processStdout(session.getStdout(), DEFAULTCHART);
                if (StringUtils.isBlank(result))
                {
                    log.info("得到标准输出为空,链接conn:" + conn + ",执行的命令:" + cmd);
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                }
                else
                {
                    log.info("执行命令成功,链接conn:" + conn + ",执行的命令:" + cmd);
                }
                conn.close();
                session.close();
            }
        }
        catch (IOException e)
        {
            log.info("执行命令失败,链接conn:" + conn + ",执行的命令:" + cmd + "  " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
   
    private static String processStdout(InputStream in, String charset)
    {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null)
            {
                buffer.append(line + "\n");
            }
        }
        catch (UnsupportedEncodingException e)
        {
            log.error("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        }
        catch (IOException e)
        {
            log.error("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }
   
    public static void main(String[] args)
    {
        Connection conn = RemoteCommandUtil.login("192.168.20.240", "root", "tcrj2018");
        System.out.println(RemoteCommandUtil.execute(conn, "uname -a && date && uptime && who"));
    }
}

你可能感兴趣的:(java使用ssh2远程登录linux/windows并执行命令)