Java calls shell script remotely and obtains output information [recommended]
1. Add dependency
<dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>262</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
2. API description
Firstly, a connector is constructed to pass in an IP address that needs to be logged in;
Connection conn = new Connection(ipAddr);
Simulate login to the destination server and input the user name and password;
boolean isAuthenticated = conn.authenticateWithPassword(userName,passWord);
It will return a Boolean value. True represents successful login to the destination server, otherwise login fails.
Open a session and execute the Linux script commands you need;
Session session = conn.openSession(); session.execCommand(“ifconfig”);
Receive the results returned by the console on the target server and read the contents in BR;
InputStream stdout = new StreamGobbler(session.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
Get the flag of whether the script runs successfully: 0 - success, non-0 - failure
System.out.println(“ExitCode: ” + session.getExitStatus());
Close session and connection
session.close(); conn.close();
Tips:
After the second authentication is successful, the current directory is located under the / home / username / directory. You can specify the absolute path where the script file is located, or navigate to the directory where the script file is located through CD, and then pass the parameters required to execute the script to complete the script call and execution. After executing the script, you can obtain the result text of the script execution. These texts need to be correctly encoded and returned to the client to avoid random code. If you need to execute multiple Linux console scripts, for example, the return result of the first script is the input parameter of the second script, you must open multiple sessions, that is, call session sess = conn.opensession(); multiple times;, Remember to close it after use.
3. Example: tool class
public class SSHTool { private Connection conn; private String ipAddr; private Charset charset = StandardCharsets.UTF_8; private String userName; private String password; public SSHTool(String ipAddr,String userName,String password,Charset charset) { this.ipAddr = ipAddr; this.userName = userName; this.password = password; if (charset != null) { this.charset = charset; } } /** * 登录远程Linux主机 * * @return 是否登录成功 */ private boolean login() { conn = new Connection(ipAddr); try { // 连接 conn.connect(); // 认证 return conn.authenticateWithPassword(userName,password); } catch (IOException e) { e.printStackTrace(); return false; } } /** * 执行Shell脚本或命令 * * @param cmds 命令行序列 * @return 脚本输出结果 */ public StringBuilder exec(String cmds) throws IOException { InputStream in = null; StringBuilder result = new StringBuilder(); try { if (this.login()) { // 打开一个会话 Session session = conn.openSession(); session.execCommand(cmds); in = session.getStdout(); result = this.processStdout(in,this.charset); conn.close(); } } finally { if (null != in) { in.close(); } } return result; } /** * 解析流获取字符串信息 * * @param in 输入流对象 * @param charset 字符集 * @return 脚本输出结果 */ public StringBuilder processStdout(InputStream in,Charset charset) throws FileNotFoundException { byte[] buf = new byte[1024]; StringBuilder sb = new StringBuilder(); // OutputStream os = new FileOutputStream("./data.txt"); try { int length; while ((length = in.read(buf)) != -1) { // os.write(buf,c); sb.append(new String(buf,length)); } } catch (IOException e) { e.printStackTrace(); } return sb; } public static void main(String[] args) throws IOException { SSHTool tool = new SSHTool("192.168.100.40","root","123456",StandardCharsets.UTF_8); StringBuilder exec = tool.exec("bash /root/test12345.sh"); System.out.println(exec); } }
summary
The above is the Java Remote Call shell script introduced by Xiaobian to you and obtain the output information. I hope it will be helpful to you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support to our website! If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!