远程删除文件 java_java使用Jsch实现远程操作linux服务器进行文件上传、下载,删除和显示目录信息...

1 package com.fline.aic.utils;2

3 import java.io.BufferedReader;4 import java.io.File;5 import java.io.FileInputStream;6 import java.io.FileNotFoundException;7 import java.io.IOException;8 import java.io.InputStream;9 import java.io.InputStreamReader;10 import java.util.Properties;11 import java.util.Vector;12

13 import com.jcraft.jsch.Channel;14 import com.jcraft.jsch.ChannelExec;15 import com.jcraft.jsch.ChannelSftp;16 import com.jcraft.jsch.JSch;17 import com.jcraft.jsch.JSchException;18 import com.jcraft.jsch.Session;19 import com.jcraft.jsch.SftpException;20

21 /**22 *23 * @Description TODO24 * @author biehl25 * @Date 2018年10月11日 上午10:20:1126 *27 * 说明:exec用于执行命令;sftp用于文件处理28 */

29 public classSSHRemoteCall {30

31 //私有的对象

32 private staticSSHRemoteCall sshRemoteCall;33

34 /**35 * 私有的构造方法36 */

37 privateSSHRemoteCall() {38 }39

40 //懒汉式,线程不安全,适合单线程

41 public staticSSHRemoteCall getInstance() {42 if (sshRemoteCall == null) {43 sshRemoteCall = newSSHRemoteCall();44 }45 returnsshRemoteCall;46 }47

48 //懒汉式,线程安全,适合多线程

49 public staticsynchronized SSHRemoteCall getInstance2() {50 if (sshRemoteCall == null) {51 sshRemoteCall = newSSHRemoteCall();52 }53 returnsshRemoteCall;54 }55

56 private static final int DEFAULT_PORT = 22;//默认端口号

57 private int port;//端口号

58

59 private static String ipAddress = "192.168.110.130";//ip地址

60 private static String userName = "root";//账号

61 private static String password = "hadoop";//密码

62

63 private Session session;//JSCH session

64 private boolean logined = false;//是否登陆

65

66 /**67 * 构造方法,可以直接使用DEFAULT_PORT68 *69 * @param ipAddress70 * @param userName71 * @param password72 */

73 publicSSHRemoteCall(String ipAddress, String userName, String password) {74 this(ipAddress, DEFAULT_PORT, userName, password);75 }76

77 /**78 * 构造方法,方便直接传入ipAddress,userName,password进行调用79 *80 * @param ipAddress81 * @param port82 * @param userName83 * @param password84 */

85 public SSHRemoteCall(String ipAddress, intport, String userName, String password) {86 super();87 this.ipAddress =ipAddress;88 this.userName =userName;89 this.password =password;90 this.port =port;91 }92

93 /**94 * 远程登陆95 *96 * @throws Exception97 */

98 public voidsshRemoteCallLogin(String ipAddress, String userName, String password) throws Exception {99 //如果登陆就直接返回

100 if(logined) {101 return;102 }103 //创建jSch对象

104 JSch jSch = newJSch();105 try{106 //获取到jSch的session, 根据用户名、主机ip、端口号获取一个Session对象

107 session =jSch.getSession(userName, ipAddress, DEFAULT_PORT);108 //设置密码

109 session.setPassword(password);110

111 //方式一,通过Session建立连接112 //session.setConfig("StrictHostKeyChecking", "no");113 //session.connect();114

115 //方式二,通过Session建立连接116 //java.util.Properties;

117 Properties config = newProperties();118 config.put("StrictHostKeyChecking", "no");119 session.setConfig(config);//为Session对象设置properties120 //session.setTimeout(3000);//设置超时

121 session.connect(); 通过Session建立连接

122

123 //设置登陆状态

124 logined = true;125 } catch(JSchException e) {126 //设置登陆状态为false

127 logined = false;128 throw newException(129 "主机登录失败, IP =" + ipAddress + ", USERNAME =" + userName + ", Exception:" +e.getMessage());130 }131 }132

133 /**134 * 关闭连接135 */

136 public voidcloseSession() {137 //调用session的关闭连接的方法

138 if (session != null) {139 //如果session不为空,调用session的关闭连接的方法

140 session.disconnect();141 }142

143 }144

145 /**146 * 执行相关的命令147 *148 * @param command149 * @throws IOException150 */

151 public voidexecCommand(String command) throws IOException {152 InputStream in = null;//输入流(读)

153 Channel channel = null;//定义channel变量

154 try{155 //如果命令command不等于null

156 if (command != null) {157 //打开channel158 //说明:exec用于执行命令;sftp用于文件处理

159 channel = session.openChannel("exec");160 //设置command

161 ((ChannelExec) channel).setCommand(command);162 //channel进行连接

163 channel.connect();164 //获取到输入流

165 in =channel.getInputStream();166 //执行相关的命令

167 String processDataStream = processDataStream(in);168 //打印相关的命令

169 System.out.println("1、打印相关返回的命令:" +processDataStream);170 }171 } catch(JSchException e) {172 e.printStackTrace();173 } catch(IOException e) {174 e.printStackTrace();175 } catch(Exception e) {176 e.printStackTrace();177 } finally{178 if (in != null) {179 in.close();180 }181 if (channel != null) {182 channel.disconnect();183 }184 }185

186 }187

188 /**189 * 对将要执行的linux的命令进行遍历190 *191 * @param in192 * @return193 * @throws Exception194 */

195 public String processDataStream(InputStream in) throws Exception {196 StringBuffer sb = newStringBuffer();197 BufferedReader br = new BufferedReader(new InputStreamReader(in));198 String result = "";199 try{200 while ((result = br.readLine()) != null) {201 sb.append(result);202 //System.out.println(sb.toString());

203 }204 } catch(Exception e) {205 throw new Exception("获取数据流失败:" +e);206 } finally{207 br.close();208 }209 returnsb.toString();210 }211

212 /**213 * 上传文件 可参考:https://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html

214 *215 * @param directory216 * 上传文件的目录217 * @param uploadFile218 * 将要上传的文件219 */

220 public voiduploadFile(String directory, String uploadFile) {221 try{222 //打开channelSftp

223 ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");224 //远程连接

225 channelSftp.connect();226 //创建一个文件名称问uploadFile的文件

227 File file = newFile(uploadFile);228 //将文件进行上传(sftp协议)229 //将本地文件名为src的文件上传到目标服务器,目标文件名为dst,若dst为目录,则目标文件名将与src文件名相同.230 //采用默认的传输模式:OVERWRITE

231 channelSftp.put(newFileInputStream(file), directory, ChannelSftp.OVERWRITE);232 //切断远程连接

233 channelSftp.exit();234 System.out.println("2、" + file.getName() + "文件上传成功.....");235 } catch(JSchException e) {236 e.printStackTrace();237 } catch(SftpException e) {238 e.printStackTrace();239 } catch(FileNotFoundException e) {240 e.printStackTrace();241 }242

243 }244

245 /**246 * 下载文件 采用默认的传输模式:OVERWRITE247 *248 * @param src249 * linux服务器文件地址250 * @param dst251 * 本地存放地址252 * @throws JSchException253 * @throws SftpException254 */

255 public voidfileDownload(String src, String dst) throws JSchException, SftpException {256 //src 是linux服务器文件地址,dst 本地存放地址

257 ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");258 //远程连接

259 channelSftp.connect();260 //下载文件,多个重载方法

261 channelSftp.get(src, dst);262 //切断远程连接,quit()等同于exit(),都是调用disconnect()

263 channelSftp.quit();264 //channelSftp.disconnect();

265 System.out.println("3、" + src + ",下载文件成功.....");266 }267

268 /**269 * 删除文件270 *271 * @param directory272 * 要删除文件所在目录273 * @param deleteFile274 * 要删除的文件275 * @param sftp276 * @throws SftpException277 * @throws JSchException278 */

279 public voiddeleteFile(String directoryFile) throws SftpException, JSchException {280 //打开openChannel的sftp

281 ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");282 //远程连接

283 channelSftp.connect();284 //删除文件

285 channelSftp.rm(directoryFile);286 //切断远程连接

287 channelSftp.exit();288 System.out.println("4、" + directoryFile + "删除的文件.....");289 }290

291 /**292 * 列出目录下的文件293 *294 * @param directory295 * 要列出的目录296 * @param sftp297 * @return298 * @throws SftpException299 * @throws JSchException300 */

301 publicVector listFiles(String directory) throws JSchException, SftpException {302 ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");303 //远程连接

304 channelSftp.connect();305 //显示目录信息

306 Vector ls =channelSftp.ls(directory);307 System.out.println("5、" +ls);308 //切断连接

309 channelSftp.exit();310 returnls;311 }312

313 public static voidmain(String[] args) {314 //连接到指定的服务器

315 try{316 //1、首先远程连接ssh

317 SSHRemoteCall.getInstance().sshRemoteCallLogin(ipAddress, userName, password);318 //打印信息

319 System.out.println("0、连接192.168.110.130,ip地址:" + ipAddress + ",账号:" + userName + ",连接成功.....");320

321 //2、执行相关的命令322 //查看目录信息323 //String command = "ls /home/hadoop/package ";324 //查看文件信息325 //String command = "cat /home/hadoop/package/test ";326 //查看磁盘空间大小327 //String command = "df -lh ";328 //查看cpu的使用情况329 //String command = "top -bn 1 -i -c ";330 //查看内存的使用情况

331 String command = "free";332 SSHRemoteCall.getInstance().execCommand(command);333

334 //3、上传文件

335 String directory = "/home/hadoop/package/poi.xlsx";//目标文件名

336 String uploadFile = "E:\\poi.xlsx";//本地文件名

337 SSHRemoteCall.getInstance().uploadFile(directory, uploadFile);338

339 //4、下载文件340 //src 是linux服务器文件地址,dst 本地存放地址,采用默认的传输模式:OVERWRITE341 //test为文件名称哈

342 String src = "/home/hadoop/package/test";343 String dst = "E:\\";344 SSHRemoteCall.getInstance().fileDownload(src, dst);345

346 //5、刪除文件

347 String deleteDirectoryFile = "/home/hadoop/package/test";348 SSHRemoteCall.getInstance().deleteFile(deleteDirectoryFile);349

350 //6、展示目录下的文件信息

351 String lsDirectory = "/home/hadoop/package";352 SSHRemoteCall.getInstance().listFiles(lsDirectory);353

354 //7、关闭连接

355 SSHRemoteCall.getInstance().closeSession();356 } catch(Exception e) {357 //打印错误信息

358 System.err.println("远程连接失败......");359 e.printStackTrace();360 }361 }362

363 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Java JSch库逐行读取远程文件的步骤如下: 1. 创建一个JSch对象,用于连接到远程服务器。 2. 使用JSch对象创建一个Session对象,指定连接的用户名、密码和远程服务器的IP地址。 3. 打开Session连接。 4. 使用Session对象创建一个Channel对象,指定通道类型为“exec”。 5. 设置Channel对象的输入流和输出流,用于执行命令和读取命令的输出结果。 6. 使用Channel对象执行要读取的文件的命令。 7. 循环读取输出流中的每一行数据,直到读取完整个文件。 8. 关闭Channel对象和Session对象。 下面是示例代码: ```java import com.jcraft.jsch.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class ReadRemoteFile { public static void main(String[] args) { String host = "remote-server-ip-address"; String user = "username"; String password = "password"; String remoteFile = "/path/to/remote/file"; JSch jsch = new JSch(); Session session = null; Channel channel = null; BufferedReader reader = null; try { session = jsch.getSession(user, host, 22); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand("cat " + remoteFile); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (JSchException | IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } if (channel != null) { channel.disconnect(); } if (session != null) { session.disconnect(); } } } } ``` 在这个示例中,我们使用JSch库连接到远程服务器,然后执行了一个命令来读取指定的远程文件。最终,我们循环读取输出流中的每一行数据,并打印到控制台上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值