Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java to implement ssh Command Log on Host and execute shell Command

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use Java to achieve ssh commands to log on to the host to execute shell commands, the article introduces in great detail, has a certain reference value, interested friends must read it!

1. SSH command

SSH is an acronym for Secure Shell and was developed by IETF's network team (Network Working Group). SSH is a security protocol based on the application layer. SSH is a reliable protocol designed to provide security for remote login sessions and other network services. The use of SSH protocol can effectively prevent information leakage in the process of remote management. SSH was originally a program on the UNIX system, and then rapidly expanded to other operating platforms. When used correctly, SSH can make up for loopholes in the network. The SSH client is suitable for a variety of platforms. Almost all UNIX platforms-including HP-UX, Linux, AIX, Solaris, Digital UNIX, Irix, and others-can run SSH.

In practice, we often use client tools (such as Secure CRT,Xshell,MobaXterm, etc.) to SSH to the host to execute some operation commands.

How to use the SSH language to connect to the host and execute the Shell command?

2. Java implements SSH command

1) the code is implemented as follows:

Import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.util.Calendar;import org.apache.commons.lang3.StringUtils;import ch.ethz.ssh3.Connection;import ch.ethz.ssh3.Session;import ch.ethz.ssh3.StreamGobbler;public class SshUtil {private static String DEFAULT_CHAR_SET = "UTF-8"; private static String tipStr = "= =% slots ="; private static String splitStr = "=" / * * Log in to the host * @ return * return true if the login succeeds, otherwise return false * / public static Connection login (String ip, String userName, String password) {boolean isAuthenticated = false; Connection conn = null; long startTime = Calendar.getInstance (). GetTimeInMillis (); try {conn = new Connection (ip); conn.connect (); / / connection host isAuthenticated = conn.authenticateWithPassword (userName, password) / / Authentication if (isAuthenticated) {System.out.println (String.format (tipStr, "Certification success");} else {System.out.println (String.format (tipStr, "Authentication failure");}} catch (IOException e) {System.err.println (String.format (tipStr, "login failure"); e.printStackTrace ();} long endTime = Calendar.getInstance () .getTimeInMillis () System.out.println ("login time:" + (endTime-startTime) / 1000.0 + "s\ n" + splitStr); return conn;} / * * remote execution of shell scripts or commands * @ param cmd * the result value returned after the upcoming command * @ return * command execution * / public static String execute (Connection conn, String cmd) {String result = "; Session session = null Try {if (conn! = null) {session = conn.openSession (); / / Open a session session.execCommand (cmd); / / execute the command result = processStdout (session.getStdout (), DEFAULT_CHAR_SET); / / if the script execution is empty, if (StringUtils.isBlank (result)) {System.err.println ("[get standard output is empty]\ nThe command executed is as follows:\ n" + cmd). Result = processStdout (session.getStderr (), DEFAULT_CHAR_SET);} else {System.out.println ("[command successfully executed]\ nThe command executed is as follows:\ n" + cmd);} catch (IOException e) {System.err.println ("[failed to execute the command]\ nThe command executed is as follows:\ n" + cmd + "\ n" + e.getMessage ()); e.printStackTrace () } finally {if (conn! = null) {conn.close ();} if (session! = null) {session.close ();}} return result;} / * parse script execution returned result set * @ param in input stream object * @ param charset encoding * @ return * return * / private static String processStdout (InputStream in, String charset) {InputStream stdout = new StreamGobbler (in); StringBuffer buffer = new StringBuffer (in) in plain text format Try {BufferedReader br = new BufferedReader (new InputStreamReader (stdout, charset)); String line = null; while ((line = br.readLine ())! = null) {buffer.append (line + "\ n");} catch (UnsupportedEncodingException e) {System.err.println ("parsing script error:" + e.getMessage ()); e.printStackTrace ();} catch (IOException e) {System.err.println ("parsing script error:" + e.getMessage ()); e.printStackTrace () } return buffer.toString ();} public static void main (String [] args) {String ip = "192.168.123.234"; / / here, according to the actual situation, replace it with the host you need to access: IP String userName = "root"; String password = "password"; Connection conn = SshUtil.login (ip, userName, password); String cmd = "cd / home/miracle&&pwd&&ls&&cat luna.txt"; String result = SshUtil.execute (conn, cmd) The result of System.out.println (splitStr + "\ nexecution is as follows:\ n" + result + splitStr);}}

2) the running result is as follows:

= = authentication succeeded = = Login time: 0.859sauthentication = [command executed successfully] the command executed by cd / home/miracle&&pwd&&ls&&cat luna.txt=== is as follows: / home/miracleluna.txtHello, Ichimm SshUtil.Nice to meet you.^ _ ^ = =

3) pom.xml reference is added as follows:

Org.apache.commons commons-lang3 3.9 ch.ethz.ganymed ganymed-ssh3 262

The above is all the contents of the article "how to use Java to achieve ssh commands to log on to the host computer to execute shell commands". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report