1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java通过SSH连接linux远程服务器操作命令

java通过SSH连接linux远程服务器操作命令

时间:2022-10-01 04:17:01

相关推荐

java通过SSH连接linux远程服务器操作命令

pom依赖

<dependency><groupId>ch.ethz.ganymed</groupId><artifactId>ganymed-ssh2</artifactId><version>262</version></dependency>

工具类

package com.mon.utils;import ch.ethz.ssh2.Connection;import ch.ethz.ssh2.Session;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;public class SSHToolUtil {private Connection conn;private String ipAddr;private Charset charset = StandardCharsets.UTF_8;private String userName;private String password;public SSHToolUtil(String ipAddr, String userName, String password) {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 {// System.out.println("登录");// 连接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()) {//System.out.println("333");// 打开一个会话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, 0, c);sb.append(new String(buf, 0, length));}} catch (IOException e) {e.printStackTrace();}return sb;}}

简单调用

SSHToolUtil sshToolUtil = new SSHToolUtil(url, user, pass);List<Map<String, Object>> list = new ArrayList<>();StringBuilder exec = sshToolUtil.exec("ls /beifen/zhujian/all/");

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。