Java中使用JSCH來實現串連遠程伺服器執行linux命令

來源:互聯網
上載者:User

Java中使用JSCH來實現串連遠程伺服器執行linux命令

有時候你可能需要通過代碼來控制執行linux命令實現某些功能。

針對這類問題可以使用JSCH來實現,具體代碼如下:

public class CogradientImgFileManager{    private static final Logger log     = LoggerFactory.getLogger(CogradientImgFileManager.class);    private static ChannelExec          channelExec;    private static Session              session = null;    private static int                  timeout = 60000;        // 測試代碼    public static void main(String[] args){        try{            versouSshUtil("10.8.12.189","jmuser","root1234",22);            runCmd("java -version","UTF-8");        }catch (Exception e){            // TODO Auto-generated catch block            e.printStackTrace();        }    }    /**     * 串連遠程伺服器     * @param host ip地址     * @param userName 登入名稱     * @param password 密碼     * @param port 連接埠     * @throws Exception     */    public static void versouSshUtil(String host,String userName,String password,int port) throws Exception{        log.info("嘗試串連到....host:" + host + ",username:" + userName + ",password:" + password + ",port:"                + port);        JSch jsch = new JSch(); // 建立JSch對象        session = jsch.getSession(userName, host, port); // 根據使用者名稱,主機ip,連接埠擷取一個Session對象        session.setPassword(password); // 設定密碼        Properties config = new Properties();        config.put("StrictHostKeyChecking", "no");        session.setConfig(config); // 為Session對象設定properties        session.setTimeout(timeout); // 設定timeout時間        session.connect(); // 通過Session建立連結    }    /**     * 在遠程伺服器上執行命令     * @param cmd 要執行的命令字串     * @param charset 編碼     * @throws Exception     */    public static void runCmd(String cmd,String charset) throws Exception{        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(charset)));        String buf = null;        while ((buf = reader.readLine()) != null){            System.out.println(buf);        }        reader.close();        channelExec.disconnect();    }}
  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.