java:远程命令/sftp工具类

java 连接linux,上传下载文件,执行命令或shell脚本

普通项目自行下载jar包或在此下载链接: https://pan.baidu.com/s/1ZgIAr0f3-k4BA22mDT5_Og 提取码: 9ecq

maven项目在pom.xml加入

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
    <scope>compile</scope>
</dependency>


package com.tanzhao.utils;

import com.jcraft.jsch.*;
import java.io.File;
import java.io.InputStream;

/**
 * 远程命令/sftp工具类
 *
 * @author tz
 * @date 2019/9/23
 */
public class SSHUtil {
    private static final String SFTP = "sftp";
    private static final String SHELL = "exec";


    /**
     * 执行远程命令
     *
     * @param ip
     * @param user
     * @param psw
     * @throws Exception
     */
    public static String execCmd(String ip, String user, String psw, String cmd) throws Exception {
        //连接服务器,采用默认端口
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, ip);
        Channel channel = connect(session, psw, SHELL);
        String result = null;

        try {
            ChannelExec channelExec = (ChannelExec) channel;
            //获取输入流和输出流
            InputStream in = channel.getInputStream();
            channelExec.setCommand(cmd);
            channelExec.connect();

            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0)
                        break;
                    result = new String(tmp, 0, i);
                }
                if (channel.isClosed()) {
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    result = e.toString();
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            session.disconnect();
            channel.disconnect();
        }

        return result;
    }

    /**
     * 执行sftp传输
     *
     * @param ip
     * @param user
     * @param psw
     * @param filename 文件名
     * @param localDir 本地文件地址
     * @param sftpDir  sftp连接地址
     * @param rename  重命名
     * @throws Exception
     */
    public static boolean putFile(String ip, String user, String psw, String filename, String localDir, String sftpDir ,String rename) throws Exception {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, ip);
        //连接服务器,采用默认端口
        Channel channel = connect(session, psw, SFTP);

        try {
            ChannelSftp sftp = (ChannelSftp) channel;
            sftp.connect();

            String localFilePath = localDir + '/' + filename;
            String sftpFilePath = sftpDir + '/' + rename;

            File localFile = new File(localFilePath);
            if (!localFile.exists()||!localFile.isFile()){
                return false;
            }

            System.out.println("开始上传,本地服务器路径:["+localFilePath +"]目标服务器路径:["+sftpFilePath+"]");
            sftp.put(localFilePath,sftpFilePath);
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        } finally {
            session.disconnect();
            channel.disconnect();
        }
    }

    /**
     * 执行sftp传输,获取日志文件
     *
     * @param ip
     * @param user
     * @param psw
     * @param filename 文件名
     * @param localDir 本地文件地址
     * @param sftpDir  sftp连接地址
     * @param rename  重命名
     * @throws Exception
     */
    public static boolean getFile(String ip, String user, String psw, String filename, String localDir, String sftpDir ,String rename) throws Exception {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, ip);
        //连接服务器,采用默认端口
        Channel channel = connect(session, psw, SFTP);

        try {
            ChannelSftp sftp = (ChannelSftp) channel;
            sftp.connect();

            String localFilePath = localDir + '/' + rename;
            String sftpFilePath = sftpDir + '/' + filename;

            System.out.println("开始下载,sftp服务器路径:["+sftpFilePath +"]目标服务器路径:["+localFilePath+"]");
            sftp.get(sftpFilePath,localFilePath);
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        } finally {
            session.disconnect();
            channel.disconnect();
        }
    }

    /**
     * 连接服务器
     *
     * @param session
     * @param psw
     * @param type
     * @return
     * @throws Exception
     */
    private static Channel connect(Session session, String psw, String type) throws Exception {
        //如果服务器连接不上,则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }
        //设置登陆主机的密码
        session.setPassword(psw);//设置密码
        //设置第一次登陆的时候提示,可选值:(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        session.connect(30000);
        //创建通信通道
        return session.openChannel(type);
    }

    /**
     * 测试连接服务器情况
     *
     * @param ip
     * @param user
     * @param psw
     * @return
     * @throws Exception
     */
    public static boolean testSSH(String ip, String user, String psw){
        JSch jsch = new JSch();
        Session session = null;
        Channel channel = null;
        try {
            //连接服务器,采用默认端口
            System.out.println("测试["+ip+"]连接情况:");
            session = jsch.getSession(user, ip);
            channel = connect(session, psw, SHELL);
            session.disconnect();
            channel.disconnect();
            System.out.println("ok");
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            session.disconnect();
            return false;
        }
    }

    public static void main(String[] args) {
        boolean a = testSSH("192.168.160.110","root", "123456");
        System.out.println(a);
        try {
            System.out.println(putFile("192.168.160.110","root","123456","test2.sh", "F:\\项目\\test","/usr/local","test2.sh"));
            System.out.println(getFile("192.168.160.110","root","123456","pg_log.txt", "F:\\项目\\test","/usr/local","200.200.200.84_pg_log.txt"));
            System.out.println(execCmd("192.168.160.110","root", "123456","chmod 777 /usr/local/test2.sh"));
            System.out.println(execCmd("192.168.160.110","root", "123456","cd /usr/local/ && ./test2.sh >>pg_log.txt 2>&1"));
            System.out.println(testSSH("192.168.160.110","root", "123456"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值