JSch-遠(yuǎn)程調(diào)用linux命令和文件上傳

pom.xml配置依賴

        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.53</version>  
        </dependency> 

一、遠(yuǎn)程調(diào)用linux命令

1、如果服務(wù)器只是單純的用戶名,密碼登錄代碼如下:

public class RemoteShellUtils {
    private static final Logger LOG = Logger.getLogger(RemoteShellUtils.class);
    private Channel channel = null;
    private Session session = null;
    // 用戶名
    private static String user;
    // 密碼
    private static String passwd;
    // ip地址
    private static String host;
    // 端口號(hào)
    private static int port;

    static {
        InputStream in = ClassLoader
                .getSystemResourceAsStream("store.properties");
        Properties prop = new Properties();
        try {
            prop.load(in);
            user = prop.getProperty("server.user");
            passwd = prop.getProperty("server.passwd");
            host = prop.getProperty("server.host");
            port = Integer.valueOf(prop.getProperty("server.port"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 獲取session
     * 
     * @param user服務(wù)器用戶名
     * @param passwd服務(wù)器密碼
     * @param host服務(wù)器ip地址
     * @param port服務(wù)器端口號(hào)
     * @return
     * @throws JSchException
     */
    public Session getSession() throws JSchException {
        // 創(chuàng)建JSch對(duì)象
        JSch jsch = new JSch();
        session = jsch.getSession(user, host, port);
        LOG.info("session創(chuàng)建成功");
        // 設(shè)置密碼
        session.setPassword(passwd);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        // 設(shè)置timeout時(shí)間
        session.setTimeout(timeout);
        // 通過(guò)Session建立連接
        session.connect();
        LOG.info("session連接成功");
        return session;
    }

    /**
     * 創(chuàng)建ChannelExec
     * @return
     * @throws JSchException
     */
    private ChannelExec getExecChannel() throws JSchException {
        if (session == null) {
            session = getSession();
        }
        // 打開(kāi)SFTP通道
        channel = session.openChannel("exec");
        // LOG.info("Connected successfully to " + host + ":" + port);
        return (ChannelExec) channel;
    }
    /**
     * 執(zhí)行shell命令
     * 
     * @param command
     */

    public boolean execShell(String command) {
        BufferedReader reader = null;
            channel = getExecChannel();
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            channel.connect(); // 建立SFTP通道的連接
            InputStream in = channel.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in));
            String buf = null;

            while ((buf = reader.readLine()) != null) {
                System.out.println(buf);
            }
        }
      /**
      *關(guān)閉連接資源
      */
      public void closeChannel() {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
    }

2、如果服務(wù)器是秘鑰加密碼登錄,則創(chuàng)建session方法需要修改

    /**
     * 獲取session
     * 
     * @param user
     * @param passwd
     * @param host
     * @param port
     * @return
     * @throws JSchException
     */
    public Session getSession() throws JSchException {
        // 創(chuàng)建JSch對(duì)象
        JSch jsch = new JSch();
    // 根據(jù)用戶名,主機(jī)ip,端口號(hào),獲取一個(gè)Session對(duì)象
        //獲取秘鑰
        String privateKey = ClassLoader.getSystemResource("lie_rsa").getPath()
            .substring(1);
        jsch.addIdentity(privateKey, passwd);
        session = jsch.getSession(user, host, port);
        LOG.info("session創(chuàng)建成功");
        // 設(shè)置密碼
        //session.setPassword(passwd);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        // 設(shè)置timeout時(shí)間
        session.setTimeout(timeout);
        // 通過(guò)Session建立連接
        session.connect();
        LOG.info("session連接成功");
        return session;
    }

二、上傳文件

    /**
     * 文件上傳
     * 
     * @param src本地文件路徑
     * @param dst上傳到服務(wù)器的地址
     */
    public void uploadFile(String src,String dst) {
        ChannelSftp channelSftp = null;
        FileInputStream fileInputStream = null;
        channelSftp = getSFTPChannel();
        fileInputStream = new FileInputStream(src);
        channelSftp.put(fileInputStream,dst,ChannelSftp.OVERWRITE);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容