SSHUtil.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. package com.nokia.common.ssh;
  2. import com.jcraft.jsch.*;
  3. import com.nokia.common.ssh.entity.SSHServer;
  4. import com.nokia.common.ssh.entity.UserInfoImpl;
  5. import com.nokia.common.ssh.exception.SSHUtilException;
  6. import com.nokia.common.ssh.exception.ScpAckErrorException;
  7. import lombok.Getter;
  8. import lombok.Setter;
  9. import lombok.extern.slf4j.Slf4j;
  10. import java.io.*;
  11. import java.nio.file.NoSuchFileException;
  12. import java.util.*;
  13. /**
  14. * 使用jsch库实现的ssh的工具类
  15. * <p>
  16. * todo: scpTo和scpFrom 在本机和targetServer默认编码不一致的时候,文件名中的中文会乱码,但是不会影响到文件内容,
  17. */
  18. @Slf4j
  19. public class SSHUtil {
  20. @Getter
  21. @Setter
  22. private SSHServer targetServer = new SSHServer();
  23. private Session session = null;
  24. private Channel channel = null;
  25. private JSch jSch = null;
  26. private FileInputStream fileInputStream = null;
  27. private FileOutputStream fileOutputStream = null;
  28. private OutputStream outputStream = null;
  29. private InputStream inputStream = null;
  30. private ChannelSftp channelSftp = null;
  31. public SSHUtil() {
  32. }
  33. public SSHUtil(String host, String user, String password) {
  34. targetServer = new SSHServer(host, 22, user, password);
  35. }
  36. public SSHUtil(String host, Integer port, String user, String password) {
  37. targetServer = new SSHServer(host, port, user, password);
  38. }
  39. /**
  40. * 获取文件列表
  41. */
  42. public List<String> ls(String path) throws JSchException, SftpException {
  43. session = getConnectSession();
  44. channelSftp = (ChannelSftp) session.openChannel("sftp");
  45. channelSftp.connect();
  46. List<String> fileNameList = new ArrayList<>();
  47. Vector fileList = channelSftp.ls(path);
  48. for (Object o : fileList) {
  49. String fileName = ((ChannelSftp.LsEntry) o).getFilename();
  50. if (".".equals(fileName) || "..".equals(fileName)) {
  51. continue;
  52. }
  53. fileNameList.add(fileName);
  54. channelSftp.quit();
  55. session.disconnect();
  56. }
  57. return fileNameList;
  58. }
  59. /**
  60. * 删除文件
  61. */
  62. public void delete(String fileName) throws JSchException, SftpException {
  63. session = getConnectSession();
  64. channelSftp = (ChannelSftp) session.openChannel("sftp");
  65. channelSftp.connect();
  66. channelSftp.rm(fileName);
  67. channelSftp.quit();
  68. session.disconnect();
  69. }
  70. /**
  71. * 远程执行指令
  72. */
  73. public String exec(String command) throws JSchException, IOException {
  74. StringBuilder stringBuilder = new StringBuilder();
  75. try {
  76. session = getConnectSession();
  77. channel = session.openChannel("exec");
  78. // jsch的登陆是无环境登陆即非login状态登陆,因此是没有环境变量的,
  79. String execCommand;
  80. // 在命令前添加 bash --login -c "command"以获取环境变量
  81. // source .bashrc && command 也可以解决问题, 但是可能环境加载不全
  82. if (command.startsWith("bash --login -c")) {
  83. execCommand = command;
  84. } else {
  85. execCommand = String.format("bash --login -c \"%s\"", command);
  86. }
  87. ((ChannelExec) channel).setCommand(execCommand);
  88. channel.setInputStream(null);
  89. ((ChannelExec) channel).setErrStream(System.err);
  90. InputStream in = channel.getInputStream();
  91. channel.connect();
  92. byte[] tmp = new byte[1024];
  93. while (true) {
  94. while (in.available() > 0) {
  95. int i = in.read(tmp, 0, 1024);
  96. if (i < 0) {
  97. break;
  98. }
  99. stringBuilder.append(new String(tmp, 0, i));
  100. }
  101. if (channel.isClosed()) {
  102. if (in.available() > 0) {
  103. continue;
  104. }
  105. break;
  106. }
  107. }
  108. } finally {
  109. disconnect();
  110. }
  111. return stringBuilder.toString();
  112. }
  113. /**
  114. * 使用SCP把本地文件推送到targetServer目录下
  115. * <p>
  116. * 注意,文件名不能包含中文
  117. */
  118. public boolean scpTo(String sourceFilePath, String targetPath) throws JSchException, IOException, SSHUtilException {
  119. try {
  120. session = getConnectSession();
  121. // scp内置了两个参数 -t 和 -f ,这两个参数是隐藏的,不会被用户显式提供,
  122. // 两个scp进程之间传输数据时,远端机器上的scp进程被本地scp进程启动起来时提供上去。
  123. // 需要说明的是,这是通过本地scp进程经ssh远程过去开启远端机器的scp进程来实现的。
  124. // -t 指定为to 也就是目的端模式 指定的对象就是session对应的连接对象targetServer
  125. String command = "scp " + "-t " + targetPath;
  126. channel = session.openChannel("exec");
  127. ((ChannelExec) channel).setCommand(command);
  128. outputStream = channel.getOutputStream();
  129. inputStream = channel.getInputStream();
  130. channel.connect();
  131. if (checkAck(inputStream) != 0) {
  132. log.error("scpTo 执行失败");
  133. return false;
  134. }
  135. File sourceFile = new File(sourceFilePath);
  136. if (sourceFile.isDirectory()) {
  137. log.error("sourceFilePath 必须是文件");
  138. return false;
  139. }
  140. long fileSize = sourceFile.length();
  141. command = "C0644 " + fileSize + " " + sourceFile.getName() + "\n";
  142. outputStream.write(command.getBytes());
  143. outputStream.flush();
  144. if (checkAck(inputStream) != 0) {
  145. log.error("scpTo 执行失败");
  146. return false;
  147. }
  148. fileInputStream = new FileInputStream(sourceFile);
  149. byte[] buffer = new byte[1024];
  150. while (true) {
  151. int len = fileInputStream.read(buffer, 0, buffer.length);
  152. if (len <= 0) {
  153. break;
  154. }
  155. outputStream.write(buffer, 0, len);
  156. }
  157. buffer[0] = 0;
  158. outputStream.write(buffer, 0, 1);
  159. outputStream.flush();
  160. return checkAck(inputStream) == 0;
  161. } finally {
  162. disconnect();
  163. }
  164. }
  165. /**
  166. * 使用scp把targetServer目录下的文件复制到本地
  167. */
  168. public boolean scpFrom(String sourceFilePath, String targetPath) throws JSchException, IOException, SSHUtilException {
  169. try {
  170. log.debug(sourceFilePath);
  171. session = getConnectSession();
  172. // scp内置了两个参数 -t 和 -f ,这两个参数是隐藏的,不会被用户显式提供,
  173. // 两个scp进程之间传输数据时,远端机器上的scp进程被本地scp进程启动起来时提供上去。
  174. // 需要说明的是,这是通过本地scp进程经ssh远程过去开启远端机器的scp进程来实现的。
  175. // -f 指定对端为from 也就是源端模式 指定的对象就是session对应的连接对象targetServer
  176. String command = "scp -f " + sourceFilePath;
  177. Channel channel = session.openChannel("exec");
  178. ((ChannelExec) channel).setCommand(command);
  179. outputStream = channel.getOutputStream();
  180. inputStream = channel.getInputStream();
  181. channel.connect();
  182. byte[] buf = new byte[1024];
  183. // 发送指令 '0'
  184. // 源端会一直等宿端的回应, 直到等到回应才会传输下一条协议文本.
  185. // 在送出最后一条协议文本后, 源端会传出一个大小为零的字符'0'来表示真正文件传输的开始.
  186. // 当文件接收完成后, 宿端会给源端发送一个'0'
  187. buf[0] = 0;
  188. outputStream.write(buf, 0, 1);
  189. outputStream.flush();
  190. // 接收C0644 这条消息携带了文件的信息
  191. while (true) {
  192. int c = checkAck(inputStream);
  193. // 遇到C时跳出循环
  194. if (c == 'C') {
  195. break;
  196. }
  197. }
  198. // 接收 '0644 ' 这段字符表示文件的权限
  199. inputStream.read(buf, 0, 5);
  200. // 获取filesize
  201. long filesize = 0L;
  202. while (true) {
  203. if (inputStream.read(buf, 0, 1) < 0) {
  204. break;
  205. }
  206. if (buf[0] == ' ') {
  207. break;
  208. }
  209. filesize = filesize * 10L + (long) (buf[0] - '0');
  210. }
  211. // 从 C0644命令读取文件名,命令中的文件名是不带路径的
  212. String file = null;
  213. for (int i = 0; ; i++) {
  214. inputStream.read(buf, i, 1);
  215. // 0x0a 是LF 换行符
  216. if (buf[i] == (byte) 0x0a) {
  217. file = new String(buf, 0, i);
  218. break;
  219. }
  220. }
  221. log.debug("filesize={}, file={}", filesize, file);
  222. // 发送 '0'
  223. buf[0] = 0;
  224. outputStream.write(buf, 0, 1);
  225. outputStream.flush();
  226. // 如果目标是目录,则需要加上文件名
  227. File target = new File(targetPath);
  228. if (target.isDirectory()) {
  229. log.debug("{} 是目录,需要添加文件名", target.getAbsolutePath());
  230. target = new File(targetPath + File.separator + file);
  231. }
  232. fileOutputStream = new FileOutputStream(target);
  233. int foo;
  234. while (true) {
  235. if (buf.length < filesize) {
  236. foo = buf.length;
  237. } else {
  238. foo = (int) filesize;
  239. }
  240. foo = inputStream.read(buf, 0, foo);
  241. if (foo < 0) {
  242. break;
  243. }
  244. fileOutputStream.write(buf, 0, foo);
  245. filesize -= foo;
  246. if (filesize == 0L) {
  247. break;
  248. }
  249. }
  250. if (checkAck(inputStream) != 0) {
  251. return false;
  252. }
  253. // 发送 '0'
  254. buf[0] = 0;
  255. outputStream.write(buf, 0, 1);
  256. outputStream.flush();
  257. log.debug("scp from {}@{}:{}{} to {} 完成", targetServer.getUser(), targetServer.getHost(), targetServer.getPort(), sourceFilePath, target.getAbsolutePath());
  258. return true;
  259. } finally {
  260. disconnect();
  261. }
  262. }
  263. private Session getConnectSession() throws JSchException {
  264. jSch = new JSch();
  265. session = jSch.getSession(targetServer.getUser(), targetServer.getHost(), targetServer.getPort());
  266. session.setPassword(targetServer.getPassword());
  267. session.setUserInfo(new UserInfoImpl());
  268. // 不需要输入保存ssh安全密钥的yes或no
  269. Properties properties = new Properties();
  270. properties.put("StrictHostKeyChecking", "no");
  271. session.setConfig(properties);
  272. session.connect();
  273. log.debug("已连接到{}@{}:{}", targetServer.getUser(), targetServer.getHost(), targetServer.getPort());
  274. return session;
  275. }
  276. private void disconnect() throws IOException {
  277. if (fileOutputStream != null) {
  278. fileOutputStream.close();
  279. fileOutputStream = null;
  280. }
  281. if (fileInputStream != null) {
  282. fileInputStream.close();
  283. fileInputStream = null;
  284. }
  285. if (outputStream != null) {
  286. outputStream.close();
  287. outputStream = null;
  288. }
  289. if (channel != null) {
  290. channel.disconnect();
  291. channel = null;
  292. }
  293. if (session != null) {
  294. session.disconnect();
  295. session = null;
  296. }
  297. jSch = null;
  298. }
  299. /**
  300. * 来自源端的每条消息和每个传输完毕的文件都需要宿端的确认和响应.
  301. * 宿端会返回三种确认消息: 0(正常), 1(警告)或2(严重错误, 将中断连接).
  302. * 消息1和2可以跟一个字符串和一个换行符, 这个字符串将显示在scp的源端. 无论这个字符串是否为空, 换行符都是不可缺少的.
  303. */
  304. private static int checkAck(InputStream in) throws IOException, SSHUtilException {
  305. int b = in.read();
  306. // b 取值为0表示成功
  307. if (b == 0) {
  308. return b;
  309. }
  310. if (b == -1) {
  311. return b;
  312. }
  313. // 1表示警告 2表示严重错误,将中断连接
  314. // 1和2 后面会携带一条错误信息,以\n结尾
  315. if (b == 1 || b == 2) {
  316. // 打印消息后面跟的字符串
  317. StringBuilder sb = new StringBuilder();
  318. int c;
  319. do {
  320. // 读取字符串直到遇到换行符
  321. c = in.read();
  322. sb.append((char) c);
  323. } while (c != '\n');
  324. log.debug("checkAck发现错误消息: ack={}-msg={}", b, sb);
  325. if (b == 1 && sb.toString().endsWith("No such file or directory")) {
  326. throw new NoSuchFileException(sb.toString());
  327. } else {
  328. throw new ScpAckErrorException(sb.toString());
  329. }
  330. }
  331. return b;
  332. }
  333. }