1. 程式人生 > >java中利用jsch執行遠端命令,實現sftp

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>