SSHUtil.java 13 KB

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