SSHUtil.java 13 KB

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