java實現(xiàn)ssh登錄linux服務(wù)器并下發(fā)命令

背景:需要開發(fā)一個小工具,實現(xiàn)ssh登錄linux服務(wù)器采集cpu利用率、內(nèi)存利用率等等監(jiān)控功能

基于jsch開發(fā),jsch是一個ssh2的純java實現(xiàn),client代碼參考了jsch的大量examples

不多說話,先上code:

實現(xiàn)關(guān)鍵的3個接口:login/logout/sendCmd,分別是登錄、登出、下發(fā)命令

import com.jcraft.jsch.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

/**
 * SSHClient based on jsch
 * examples: com.wow.remoteutils.SSHClientTest
 *
 * Created by kisrosen on 17/1/22.
 */
@Component
public class SSHClient {

    /**
     * Server Host IP Address,default value is localhost
     */
    private String host = "localhost";

    /**
     * Server SSH Port,default value is 22
     */
    private Integer port = 22;

    /**
     * SSH Login Username
     */
    private String username = "";

    /**
     * SSH Login Password
     */
    private String password = "";

    /**
     * JSch
     */
    private JSch jsch = null;

    /**
     * ssh session
     */
    private Session session = null;

    /**
     * ssh channel
     */
    private Channel channel = null;

    /**
     * timeout for session connection
     */
    private final Integer SESSION_TIMEOUT = 30000;

    /**
     * timeout for channel connection
     */
    private final Integer CHANNEL_TIMEOUT = 30000;

    /**
     * the interval for acquiring ret
     */
    private final Integer CYCLE_TIME = 100;

    public SSHClient() {
        // initialize
        jsch = new JSch();
    }

    public SSHClient setHost(String host) {
        this.host = host;
        return this;
    }

    public SSHClient setPort(Integer port) {
        this.port = port;
        return this;
    }

    public SSHClient setUsername(String username) {
        this.username = username;
        return this;
    }

    public SSHClient setPassword(String password) {
        this.password = password;
        return this;
    }


    /**
     * login to server
     *
     * @param username
     * @param password
     */
    public void login(String username, String password) {

        this.username = username;
        this.password = password;

        try {
            if (null == session) {

                session = jsch.getSession(this.username, this.host, this.port);
                session.setPassword(this.password);
                session.setUserInfo(new MyUserInfo());

                // It must not be recommended, but if you want to skip host-key check,
                // invoke following,
                session.setConfig("StrictHostKeyChecking", "no");
            }

            session.connect(SESSION_TIMEOUT);
        } catch (JSchException e) {
            System.err.println(e);
            this.logout();
        }
    }

    /**
     * login to server
     */
    public void login() {
        this.login(this.username, this.password);
    }

    /**
     * logout of server
     */
    public void logout() {
        this.session.disconnect();
    }

    /**
     * send command through the ssh session,return the ret of the channel
     *
     * @return
     */
    public String sendCmd(String command) {

        String ret = "";

        // judge whether the session or channel is connected
        if (!session.isConnected()) {
            this.login();
        }

        // open channel for sending command
        try {
            this.channel = session.openChannel("exec");
            ((ChannelExec) this.channel).setCommand(command);
            this.channel.connect(CHANNEL_TIMEOUT);

            // no output stream
            channel.setInputStream(null);

            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();

            // acquire for ret
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;

                    ret = new String(tmp, 0, i);
                    System.out.print(ret);
                }

                // quit the process of waiting for ret
                if (channel.isClosed()) {
                    if (in.available() > 0) continue;
                    System.out.println("exit-status: " + channel.getExitStatus());
                    break;
                }

                // wait every 100ms
                try {
                    Thread.sleep(CYCLE_TIME);
                } catch (Exception ee) {
                    System.err.println(ee);
                }
            }

        } catch (JSchException e) {
            e.printStackTrace();
            System.err.println(e);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println(e);
        } finally {
            // close channel
            this.channel.disconnect();
        }

        return ret;
    }

    /**
     * customized userinfo
     */
    private static class MyUserInfo implements UserInfo {
        @Override
        public String getPassphrase() {
            return null;
        }

        @Override
        public String getPassword() {
            return null;
        }

        @Override
        public boolean promptPassword(String s) {
            return false;
        }

        @Override
        public boolean promptPassphrase(String s) {
            return false;
        }

        @Override
        public boolean promptYesNo(String s) {
            return true;
        }

        @Override
        public void showMessage(String s) {
            System.out.println("showMessage:" + s);
        }
    }
}

調(diào)用代碼:

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by kisrosen on 17/1/23.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:CommonUtils.xml")
public class SSHClientTest {

    @Autowired
    private SSHClient sshClient;

    @Before
    public void setUp() throws Exception {
        sshClient.setHost("localhost").setPort(10022).setUsername("root").setPassword("root");
        sshClient.login();
    }

    @Test
    public void sendCmd() throws Exception {
        String ret = sshClient.sendCmd("pwd");

        System.out.println("******************************");
        System.out.println(ret);
        System.out.println("******************************");

        Assert.assertNotNull(ret);
        Assert.assertTrue(ret.length() > 0);

        ret = sshClient.sendCmd("vmstat");

        System.out.println("******************************");
        System.out.println(ret);
        System.out.println("******************************");

        Assert.assertNotNull(ret);
        Assert.assertTrue(ret.length() > 0);
    }

    @After
    public void tearDown() throws Exception {
        sshClient.logout();
    }
}

執(zhí)行結(jié)果:


可以使用正則表達式匹配一些關(guān)鍵信息實現(xiàn)采集

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,987評論 25 709
  • 4 創(chuàng)建一個社交網(wǎng)站 在上一章中,你學(xué)習(xí)了如何創(chuàng)建站點地圖和訂閱,并且為博客應(yīng)用構(gòu)建了一個搜索引擎。在這一章中,你...
    lakerszhy閱讀 2,257評論 0 7
  • 最近在學(xué)習(xí)flask,用到flask-login,發(fā)現(xiàn)網(wǎng)上只有0.1版本的中文文檔,看了官方已經(jīng)0.4了,并且添加...
    ZZES_ZCDC閱讀 6,126評論 3 24
  • 手袋行業(yè)還能開公司嗎? Todywu2014-7-12 昨天有行業(yè)人士來到我辦公室,問起了棄高薪成立自己的公司,打...
    todywu閱讀 723評論 0 49
  • 人生取決于遇見和選擇。我對這句話深信不疑。 四只 此時正在聽四只的歌。四只正在奮戰(zhàn)六級。四只是我給他的綽號。源起于...
    無束777閱讀 413評論 2 1

友情鏈接更多精彩內(nèi)容