Java connects to the remote server via jsch to execute the linux command

  • 2020-05-07 19:33:59
  • OfStack

Sometimes you may need to control the execution of the linux command through code to achieve certain functions.

For this kind of problem, JSCH can be used to implement, 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; 
//  The 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 block
e.printStackTrace();
}
}
/**
*  Connect to a 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); //  By username, host ip , port acquisition 1 a Session object 
session.setPassword(password); //  Set the password 
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config); //  for Session Object to set properties
session.setTimeout(timeout); //  Set up the timeout time 
session.connect(); //  through Session Link building 
}
/**
*  Execute the command on the remote server 
* @param cmd  A string of commands to execute 
* @param charset  coding 
* @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();
}
}


Related articles: