• 搭建免登录sftp和java代码调试获取数据


    一、SFTP免登录搭建

    sftp使用的端口是22端口,一般默认开启,如果没有开启,需要手动开启22端口和ssh服务,可以使用 netstat -tnlp | grep 22 查看端口是否正常启用了

     获取使用 systemctl status sshd 查看ssh运行状态,running就是正常运行了

    使用root用户进行sftp登录的话,可以直接在root用户下直接使用 ssh-keygen -t rsa 命令,然后直接回车,就会生成两个文件 id_rsa和id_rsa.pub文件

    可以将 id_rsa.pub的内容复制到authorized_keys文件里面,如果没有这个文件,就手动创建这个文件,这里只是将root本地免登录复制到里面而已

    如果想要其他服务器免登录到这台机器上,就需要吧其他服务器的 id_rsa.pub文件的内容添加到 authorized_keys 里面,如下图:

    至于创建非root用户免登录的,可以自行百度下,道理很简单,也就是创建个用户,然后登录所创建的用户,再按照以上步骤进行,就可以实现其他用户免登录,当然了,用其他用户所存取的文件属组都是属于其他用户的了

    二、java免登录调用:

    这里使用的jcraft的包进行操作,具体的maven如下:

    1. <dependency>
    2. <groupId>com.jcraftgroupId>
    3. <artifactId>jschartifactId>
    4. <version>0.1.55version>
    5. dependency>

    实现思路:使用已配置好的 私钥内容、服务器ip、用户名进行认证登录

    私钥对应的公钥需要提现配置在服务器的authorized_keys里面,如何配置请看上面搭建免登录sftp操作

    具体代码示例:

    1. import com.jcraft.jsch.*;
    2. import org.apache.commons.lang3.StringUtils;
    3. import java.io.*;
    4. import java.nio.charset.StandardCharsets;
    5. import java.util.*;
    6. /**
    7. * @Author yyxie
    8. */
    9. public class LSTTutils {
    10. private static ChannelSftp sftp = null;
    11. private static Session session = null;
    12. /**
    13. * 连接sftp服务器
    14. *
    15. * @param username
    16. * @param password
    17. * @param host
    18. * @param port
    19. * @param privateKey
    20. * @return
    21. */
    22. public static ChannelSftp sftpConnect(String username, String password, String host, int port, String privateKey, byte[] privateKeyStr) throws Exception {
    23. JSch jsch = new JSch();
    24. if (privateKey != null && !"".equals(privateKey)) {
    25. //jsch.addIdentity(privateKey);// 设置私钥,如果使用文件读取的话,就直接使用这个就可以,吧下面的注释掉
    26. jsch.addIdentity("", privateKeyStr, null, null);//如果直接使用读取后的内容,那么就把上面注释掉,
    27. //为了方便后面服务器迁移,推荐直接使用存在数据库中,然后读取私钥的方式
    28. }
    29. //用户名,主机,端口号
    30. session = jsch.getSession(username, host, port);
    31. //密码
    32. //session.setPassword(password);//因用了私钥登录,所以就不需要密码了,如果想要密码登录的,就把上面那个添加私钥的去掉就可以
    33. session.setConfig("StrictHostKeyChecking", "no");
    34. // 设置timeout时间
    35. session.setTimeout(30000);
    36. session.connect();
    37. Channel channel = session.openChannel("sftp");
    38. channel.connect();
    39. sftp = (ChannelSftp) channel;
    40. return sftp;
    41. }
    42. /**
    43. * 列出目录下的文件
    44. *
    45. * @param directory 要列出的目录
    46. */
    47. public static Vector listFiles(String directory) throws SftpException {
    48. return sftp.ls(directory);
    49. }
    50. /**
    51. * 判断是否是.txt 和 .csv 文件
    52. *
    53. * @param fileName 文件名称
    54. * @return
    55. */
    56. public static boolean getFileStatus(String fileName) {
    57. boolean resutl = false;
    58. if (StringUtils.isNotBlank(fileName)) {
    59. int index = fileName.lastIndexOf(".");
    60. if (index > 0) {
    61. String fileFormat = fileName.substring(index);
    62. if (".txt".equalsIgnoreCase(fileFormat) || ".csv".equalsIgnoreCase(fileFormat)) {
    63. resutl = true;
    64. }
    65. }
    66. }
    67. return resutl;
    68. }
    69. /**
    70. * 获取sftp 文件内容
    71. *
    72. * @param fileName
    73. * @param ftpPath
    74. * @return
    75. * @throws SftpException
    76. * @throws IOException
    77. */
    78. public static String getFtpData(String fileName, String ftpPath) throws SftpException, IOException {
    79. try {
    80. if (null == sftp) {
    81. return null;
    82. }
    83. sftp.cd(ftpPath);
    84. } catch (Exception e) {
    85. e.printStackTrace();
    86. }
    87. InputStream in = sftp.get(fileName);
    88. BufferedReader br = new BufferedReader(new InputStreamReader(in));
    89. String line;
    90. StringBuilder sb = new StringBuilder();
    91. while ((line = br.readLine()) != null) {
    92. sb.append(line + "\n");
    93. }
    94. return sb.toString();
    95. }
    96. /**
    97. * 关闭ftp连接
    98. */
    99. public static void closeChannel() {
    100. if (sftp != null) {
    101. sftp.disconnect();
    102. }
    103. if (session != null) {
    104. if (session.isConnected()) {
    105. session.disconnect();
    106. }
    107. }
    108. }
    109. public static void main(String[] args) throws Exception {
    110. String host = "172.16.3.110";//要登录的服务器ip
    111. int port = 22;
    112. String username = "root";//用户
    113. String passwords = "123456";//用户登录密码
    114. String ftpPath = "/home/sftp_upload";//文件读取路径
    115. //下面 privateKey和testkeys实际上是同个数据,只是一个是文件路径,一个是直接读取出来的内容
    116. String privateKey = "C:\\Users\\admin\\Desktop\\新建文件夹\\id_rsa";
    117. String testkeys = "-----BEGIN RSA ***Y-----\n" +
    118. "MIIEowIBAAKCAQEA11cIMWXaa3AW7Rkht62H+zZSFKiTHyCaNtXTLkuIeO8SQarw\n" +
    119. .....
    120. "jmrxj4DbwDnk4iNSD1NCBczqjuBmoX+SmUktdcmAIItFtSLuPp6S\n" +
    121. "-----END RSA P****Y-----";
    122. byte[] keybyte = testkeys.getBytes(StandardCharsets.UTF_8);
    123. try {
    124. //创建连接
    125. sftpConnect(username, passwords, host, port, privateKey, keybyte);
    126. } catch (Exception e) {
    127. e.printStackTrace();
    128. }
    129. try {
    130. //获取文件列表
    131. Vector vector = listFiles(ftpPath);
    132. Iterator iterator = vector.iterator();
    133. System.out.println("文件列表:");
    134. while (iterator.hasNext()) {
    135. ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) iterator.next();
    136. //文件名称
    137. if (getFileStatus(file.getFilename())) {
    138. System.out.println(file.getFilename());
    139. }
    140. }
    141. System.out.println();
    142. String fileName = "123.txt";
    143. //提取文件内容
    144. String data = getFtpData(fileName, ftpPath);
    145. System.out.println("如下文件内容:");
    146. System.out.println(data);
    147. } catch (SftpException e) {
    148. e.printStackTrace();
    149. } catch (IOException e) {
    150. e.printStackTrace();
    151. } finally {
    152. LSTTutils.closeChannel();
    153. }
    154. }
    155. }

     

  • 相关阅读:
    7.3 服务端漏洞:密码找回逻辑漏洞检测和重现
    念一句咒语 AI 就帮我写一个应用,我人麻了...
    Kotlin笔记(二):标准函数,静态方法,延迟初始化,密封类
    shell中算术运算小结
    C++求最大公因数(gcd)的六重境界
    我开源了团队内部基于SpringBoot Web快速开发的API脚手架stater
    第5章 总体设计【软件设计一般分为总体设计和详细设计,它们之间的关系是全局与局部】
    人工智能考证初步探索
    Canonical标签在SEO中重要作用
    解决HBuilderX无法登录的问题
  • 原文地址:https://blog.csdn.net/qq_32003379/article/details/127429968