Java操作Linux并执行命令

通过ganymed-ssh2连接

<!--远程连接Linux并执行命令-->
        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>
        </dependency>

测试代码

public static void main(String[] args) {
		String hostname = "192.168.1.207"; //远程机器IP
		String username = "root";
		String password = "123456";

		try {
			Connection con = new Connection(hostname);

			con.connect();

			boolean isAuthenticated = con.authenticateWithPassword(username, password);
			// 是否登录成功
			if (isAuthenticated == false) {
				throw new IOException("Authentication failed.");
			}
			if (con != null) {
				Session session = con.openSession();
				session.execCommand("mv /opt/tomcat/webapps/live/000002/2020-09-04-12-25.mp4 /root/output/normal/2020-09-04-12-25.mp4");
				System.out.println("Here is some infomation about the remote host:");
				InputStream stdout = new StreamGobbler(session.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("ExitCode:" + session.getExitStatus());
				// 关闭连接
				session.close();
				con.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

工具代码

package com.corpchina.utils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @Author: w
 * @Description:
 * @Date: Created in 14:35 2020/9/4
 * @Modified By:
 */
public class RemoteCommandUtil {

    private static final Logger lg = LoggerFactory.getLogger(RemoteCommandUtil.class);
    private static String DEFAULTCHART="UTF-8";

    private static final String HOSTNAME = "192.168.1.207";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    /**
     * 登录主机
     * @return
     */
    public static Connection login() {
        Connection conn = null;
        try {
            conn = new Connection(HOSTNAME);
            // 连接
            conn.connect();
            // 认证
            boolean isAuthenticated = conn.authenticateWithPassword(USERNAME, PASSWORD);
            if (isAuthenticated == true) {
                lg.info("===========登录成功===========");
                return conn;
            }
        } catch (Exception e) {
            lg.error("===========登录失败=========");
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 执行命令或shell脚本
     * @param connection
     * @param cmd
     * @return
     */
    public static String execute(Connection connection, String cmd) {
        String result = "";
        try {
            if (connection != null) {
                Session session = connection.openSession();
                // 执行命令
                session.execCommand(cmd);
                result = processStdout(session.getStdout(), DEFAULTCHART);
                // 如果得到标准输出为空,说明脚本执行错误
                if (StringUtils.isBlank(result)) {
                    lg.info("得到标准输出为空,链接conn:" + connection + ",执行的命令:" + cmd);
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                } else {
                    lg.info("执行命令成功,链接conn:" + connection + ",执行的命令:" + cmd);
                }
                connection.close();
                session.close();
            }
        }catch (Exception e) {
            lg.info("执行命令失败,链接conn:" + connection + "执行的命令:" + cmd +" " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     * @param in
     * @param charset
     * @return
     */
    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) {
            lg.error("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            lg.error("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值