Java中通過jsch來連接遠程服務器執(zhí)行l(wèi)inux命令
更新時間:2016年03月04日 17:07:55 作者:孫琛斌
這篇文章主要介紹了Java中通過jsch來連接遠程服務器執(zhí)行l(wèi)inux命令的相關資料,需要的朋友可以參考下
有時候你可能需要通過代碼來控制執(zhí)行l(wèi)inux命令實現(xiàn)某些功能。
針對這類問題可以使用JSCH來實現(xiàn),具體代碼如下:
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(); // 創(chuàng)建JSch對象 session = jsch.getSession(userName, host, port); // 根據(jù)用戶名,主機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建立鏈接 } /** * 在遠程服務器上執(zhí)行命令 * @param cmd 要執(zhí)行的命令字符串 * @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(); } }
相關文章
java中@JSONField和@JsonProperty注解的使用說明及對比
@JSONField與@JsonProperty隸屬兩個不同的包,前者是阿里系的fastjson包,后者是spring?boot官方使用的jackson包,本文主要介紹了java中@JSONField和@JsonProperty注解的使用說明及對比,感興趣的可以了解一下2023-11-11Java SpringBoot 使用攔截器作為權限控制的實現(xiàn)方法
這篇文章主要介紹了Java SpringBoot 使用攔截器作為權限控制的實現(xiàn),文中通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-10-10解決java.sql.SQLException:?validateConnection?false問題的方法匯總(最
這篇文章主要給大家介紹了關于解決java.sql.SQLException:?validateConnection?false問題的方法匯總,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2023-03-03RocketMQ NameServer保障數(shù)據(jù)一致性實現(xiàn)方法講解
這篇文章主要介紹了RocketMQ NameServer保障數(shù)據(jù)一致性實現(xiàn)方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12