服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - Java远程连接Linux服务器并执行命令及上传文件功能

Java远程连接Linux服务器并执行命令及上传文件功能

2021-05-05 11:44StaticKing Java教程

这篇文章主要介绍了Java远程连接Linux服务器并执行命令及上传文件功能,本文是小编整理的代码笔记,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下

 最近再开发中遇到需要将文件上传到linux服务器上,至此整理代码笔记。

此种连接方法中有考虑到并发问题,在进行创建ftp连接的时候将每一个连接对象存放至

threadlocal<ftp> 中以确保每个线程之间对ftp的打开与关闭互不影响。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package com.test.utils;
import java.io.bufferedinputstream;
import java.io.file;
import java.io.filefilter;
import java.io.fileinputstream;
import java.io.inputstream;
import java.util.arraylist;
import java.util.date;
import java.util.list;
import org.apache.commons.logging.log;
import org.apache.commons.logging.logfactory;
import com.jcraft.jsch.channelsftp;
import com.jcraft.jsch.jsch;
import com.jcraft.jsch.session;
public class ftp {
  //打印log日志
  private static final log logger = logfactory.getlog(ftp.class);
  private static date last_push_date = null;
  private session sshsession;
  private channelsftp channel;
  private static threadlocal<ftp> sftplocal = new threadlocal<ftp>();
  private ftp(string host, int port, string username, string password) throws exception {
    jsch jsch = new jsch();
    jsch.getsession(username, host, port);
    //根据用户名,密码,端口号获取session
    sshsession = jsch.getsession(username, host, port);
    sshsession.setpassword(password);
    //修改服务器/etc/ssh/sshd_config 中 gssapiauthentication的值yes为no,解决用户不能远程登录
    sshsession.setconfig("userauth.gssapi-with-mic", "no");
    //为session对象设置properties,第一次访问服务器时不用输入yes
    sshsession.setconfig("stricthostkeychecking", "no");
    sshsession.connect();
    //获取sftp通道
    channel = (channelsftp)sshsession.openchannel("sftp");
    channel.connect();
    logger.info("连接ftp成功!" + sshsession);
  }
  /**
   * 是否已连接
   *
   * @return
   */
  private boolean isconnected() {
    return null != channel && channel.isconnected();
  }
  /**
   * 获取本地线程存储的sftp客户端
   *
   * @return
   * @throws exception
   */
  public static ftp getsftputil(string host, int port, string username, string password) throws exception {
    //获取本地线程
    ftp sftputil = sftplocal.get();
    if (null == sftputil || !sftputil.isconnected()) {
      //将新连接防止本地线程,实现并发处理
      sftplocal.set(new ftp(host, port, username, password));
    }
    return sftplocal.get();
  }
  /**
   * 释放本地线程存储的sftp客户端
   */
  public static void release() {
    if (null != sftplocal.get()) {
      sftplocal.get().closechannel();
      logger.info("关闭连接" + sftplocal.get().sshsession);
      sftplocal.set(null);
    }
  }
  /**
   * 关闭通道
   *
   * @throws exception
   */
  public void closechannel() {
    if (null != channel) {
      try {
        channel.disconnect();
      } catch (exception e) {
        logger.error("关闭sftp通道发生异常:", e);
      }
    }
    if (null != sshsession) {
      try {
        sshsession.disconnect();
      } catch (exception e) {
        logger.error("sftp关闭 session异常:", e);
      }
    }
  }
  /**
   * @param directory 上传ftp的目录
   * @param uploadfile 本地文件目录
   *
   */
  public void upload(string directory, string uploadfile) throws exception {
    try {<br>    //执行列表展示ls 命令
    channel.ls(directory);<br>    //执行盘符切换cd 命令
    channel.cd(directory);
    list<file> files = getfiles(uploadfile, new arraylist<file>());
    for (int i = 0; i < files.size(); i++) {
      file file = files.get(i);
      inputstream input = new bufferedinputstream(new fileinputstream(file));
      channel.put(input, file.getname());
      try {
        if (input != null) input.close();
      } catch (exception e) {
        e.printstacktrace();
        logger.error(file.getname() + "关闭文件时.....异常!" + e.getmessage());
      }
      if (file.exists()) {
        boolean b = file.delete();
        logger.info(file.getname() + "文件上传完毕!删除标识:" + b);
      }
    }
    }catch (exception e) {
      logger.error("【子目录创建中】:",e);
            //创建子目录
      channel.mkdir(directory);
    }
  }
  //获取文件
  public list<file> getfiles(string realpath, list<file> files) {
    file realfile = new file(realpath);
    if (realfile.isdirectory()) {
      file[] subfiles = realfile.listfiles(new filefilter() {
        @override
        public boolean accept(file file) {
          if (null == last_push_date ) {
            return true;
          } else {
            long modifydate = file.lastmodified();
            return modifydate > last_push_date.gettime();
          }
        }
      });
      for (file file : subfiles) {
        if (file.isdirectory()) {
          getfiles(file.getabsolutepath(), files);
        } else {
          files.add(file);
        }
        if (null == last_push_date) {
          last_push_date = new date(file.lastmodified());
        } else {
          long modifydate = file.lastmodified();
          if (modifydate > last_push_date.gettime()) {
            last_push_date = new date(modifydate);
          }
        }
      }
    }
    return files;
  }
}

总结

以上所述是小编给大家介绍的java远程连接linux服务器并执行命令及上传文件,希望对大家有所帮助如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

原文链接:https://www.cnblogs.com/staticking/p/9082648.html

延伸 · 阅读

精彩推荐