有时候你可能需要通过代码来控制执行linux命令实现某些功能。
针对这类问题可以使用JSCH来实现,具体代码如下:
1public class CogradientImgFileManager{ 2 3 private static final Logger log = LoggerFactory.getLogger(CogradientImgFileManager.class); 4 5 private static ChannelExec channelExec; 6 7 private static Session session = null; 8 9 private static int timeout = 60000; 10 11 // 测试代码 12 public static void main(String[] args){ 13 try{ 14 versouSshUtil("10.8.12.189","jmuser","root1234",22); 15 runCmd("java -version","UTF-8"); 16 }catch (Exception e){ 17 // TODO Auto-generated catch block 18 e.printStackTrace(); 19 } 20 } 21 22 /** * 连接远程服务器 * @param host ip地址 * @param userName 登录名 * @param password 密码 * @param port 端口 * @throws Exception */ 23 public static void versouSshUtil(String host,String userName,String password,int port) throws Exception{ 24 log.info("尝试连接到....host:" + host + ",username:" + userName + ",password:" + password + ",port:" 25 + port); 26 JSch jsch = new JSch(); // 创建JSch对象 27 session = jsch.getSession(userName, host, port); // 根据用户名,主机ip,端口获取一个Session对象 28 session.setPassword(password); // 设置密码 29 Properties config = new Properties(); 30 config.put("StrictHostKeyChecking", "no"); 31 session.setConfig(config); // 为Session对象设置properties 32 session.setTimeout(timeout); // 设置timeout时间 33 session.connect(); // 通过Session建立链接 34 } 35 36 /** * 在远程服务器上执行命令 * @param cmd 要执行的命令字符串 * @param charset 编码 * @throws Exception */ 37 public static void runCmd(String cmd,String charset) throws Exception{ 38 channelExec = (ChannelExec) session.openChannel("exec"); 39 channelExec.setCommand(cmd); 40 channelExec.setInputStream(null); 41 channelExec.setErrStream(System.err); 42 channelExec.connect(); 43 InputStream in = channelExec.getInputStream(); 44 BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset))); 45 String buf = null; 46 while ((buf = reader.readLine()) != null){ 47 System.out.println(buf); 48 } 49 reader.close(); 50 channelExec.disconnect(); 51 } 52 53}