java shell 調用


public void cc() throws JSchException, IOException {
    JSch jsch = new JSch(); // 創建JSch對象
    String userName = "root";// 用戶名
    String password = "123456";// 密碼
    String host = "6.6.6.74";// 服務器地址
    int port = 22;// 端口號
   String  cmd = " sh /uiscell/bin/test.sh";// 要運行的命令
    Session session = jsch.getSession(userName, host, port); // 根據用戶名,主機ip,端口獲取一個Session對象
    session.setPassword(password); // 設置密碼
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config); // 爲Session對象設置properties
    int timeout = 60000000;
    session.setTimeout(timeout); // 設置timeout時間
    session.connect(); // 通過Session建立鏈接
    ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
    channelExec.setCommand(cmd);
    channelExec.setInputStream(null);
    channelExec.setErrStream(System.err);
    channelExec.connect();
    InputStream in = channelExec.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
    String buf = null;
    StringBuffer sb = new StringBuffer();
    while ((buf = reader.readLine()) != null) {
        sb.append(buf);
        System.out.println(buf);// 打印控制檯輸出
    }
    reader.close();
    channelExec.disconnect();
    if (null != session) {
        session.disconnect();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章