有時候你可能需要通過代碼來控制執行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 blocke.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對象設置propertiessession.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();}}
新聞熱點
疑難解答