Use JSCH in Java to connect to a remote server and execute linux commands
Sometimes you may need to use code to control the execution of linux commands to implement some functions.
JSCH can be used to solve such problems. 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 block e. printStackTrace ();}} /*** connect to the remote server * @ param host IP Address * @ param userName * @ param password * @ param port * @ throws Exception */public static void versouSshUtil (String host, string userName, String password, int port) throws Exception {log.info ("try to connect .... host: "+ host +", username: "+ userName +", password: "+ password +", port: "+ port); JSch jsch = New JSch (); // create JSch object session = jsch. getSession (userName, host, port); // obtain a Session object based on the user name, host ip address, and port. setPassword (password); // set the password Properties config = new Properties (); config. put ("StrictHostKeyChecking", "no"); session. setConfig (config); // set properties Session for the session object. setTimeout (timeout); // sets the timeout time session. connect (); // establish a link through Session}/*** execute the command on the remote server * @ param cmd the command character to be executed String * @ 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 InputStre AmReader (in, Charset. forName (charset); String buf = null; while (buf = reader. readLine ())! = Null) {System. out. println (buf);} reader. close (); channelExec. disconnect ();}}