Sometimes you may need to use code to control the execution of linux commands to implement certain functions.
For this type of problem, JSCH can be used to implement it. The specific code is as follows:
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; // Test code 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();}}/*** Connect to the remote server* @param host ip address* @param userName Login name* @param password Password* @param port port* @throws Exception*/public static void versouSshUtil(String host,String userName,String password,int port) throws Exception{log.info("Try to connect to....host:" + host + ",username:" + userName + ",password:" + password + ",port:"+ port);JSch jsch = new JSch(); // Create JSch object session = jsch.getSession(userName, host, port); // Get a Session object session.setPassword(password); // Set password Properties config = new Properties();config.put("StrictHostKeyChecking", "no");session.setConfig(config); // Set propertiessession.setTimeout(timeout); // Set timeout session.connect(); // Create link through Session}/*** Execute command on a remote server * @param cmd Command string to be executed * @param charset Encoding * @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();}}