java中利用jsch執行遠程命令,實現sftp

利用jsch可以執行遠程命令並實現sftp文件傳輸,以下爲自定義的util:

import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 遠程命令/sftp工具類
 *
 * @author lijiang
 * @date 2015/8/12 11:31
 */
public class SSHUtil {
    private static final String SFTP = "sftp";
    private static final String SHELL = "exec";
    private static final Logger logger = LoggerFactory.getLogger(SSHUtil.class);

    /**
     * 執行遠程命令
     *
     * @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) {
            logger.error(e.getMessage(), e);
        } finally {
            session.disconnect();
            channel.disconnect();
        }

        return result;
    }

    /**
     * 執行sftp傳輸
     *
     * @param ip
     * @param user
     * @param psw
     * @param localFile 本地文件
     * @param dstDir
     * @throws Exception
     */
    public static void sftp(String ip, String user, String psw, File localFile, String dstDir) 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();

            //本地文件
            if (!localFile.isFile())
                return;
            InputStream in = new FileInputStream(localFile);

            // 目的文件
            OutputStream out = sftp.put(dstDir + "/" + localFile.getName());

            byte b[] = new byte[1024];
            int n;
            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n);
            }
            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } 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);
    }
}

maven依賴:

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.53</version>
</dependency>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章