Java使用Ganymed SSH远程登录服务器并读取文件
Java使用Ganymed SSH远程登录服务器并读取文件
导入jar包,或配置依赖
<-- ganymed-ssh2-build210.jar -->
<dependency><groupId>ch.ethz.ganymed</groupId><artifactId>ganymed-ssh2</artifactId><version>build210</version>
</dependency><!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.54</version>
</dependency>
常用方法
转自:Java远程连接操作linux服务器,scp获取文件https://www.cnblogs.com/swp520lmg/articles/8036022.html
//建立连接
Connection con = newConnection(IP, PORT);
//连接
con.connect();
//远程服务器的用户名密码
boolean isAuthed = con.authenticateWithPassword(remoteUser,remotePass);
//建立SCP客户端
SCPClient scpClient = con.createSCPClient();
//服务器端的文件下载到本地的目录下
scpClient.getFile("/home/oracle/RUNNING.txt", "C:/");
//将本地文件上传到服务器端的目录下
scp.putFile("C:/RUNNING.txt", "/home/oracle");//建立一个SFTP客户端
SFTPv3Client sftpClient = new SFTPv3Client(con);
//远程新建目录
sftpClient.mkdir("newRemoteDir", 6);
//远程删除目录
sftpClient.rmdir(RemoteDir);
//远程新建文件
sftpClient.createFile("newRemoteFile");
//远程打开文件,可进行读写
sftpClient.openFileRW("remoteFile");
//建立会话
Session session = null;
session = con.openSession();
//利用会话可以操作远程服务器
//例如:删除远程目录下的文件
session.execCommand("rm -f".concat(remotePath).concat(qrCodeFileMode));
//显示执行命令后的信息
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));while (true) {String line = br.readLine();
if (line == null) {log.info("远程服务器返回信息:空");
break;
}
log.info("远程服务器返回信息:" + line);
}
//获得推出状态
System.out.println("ExitCode: " + session.getExitStatus());
session.close();
con.close();
远程连接及SFTP的使用例子
简单远程读取文件,当时用于读取/proc/meminfo等信息,只需要前几行。只截取一小段。
Connection conn = new Connection(hostname,port);
try{conn.connect();boolean isConnected = conn.authenticateWithPassword(username,password);if (!isConnected) {SFTPv3Client sftPv3Client = new SFTPv3Client(conn);SFTPv3FileHandle fh = sftPv3Client.openFileRO(procStatPath);byte[] dst = new byte[1000];sftPv3Client.read(fh, 0, dst, 0, 200);//实际只需要读取足够的长度即可String strread = new String(dst);//直接将byte[]转换成String}
} catch (IOException e) {System.out.println(e.getMessage());e.printStackTrace();
} finally {if (conn != null) {conn.close();}
}
参考:SFTP的一个小例子(备忘用法) https://www.iteye.com/blog/nickkathy-1048483
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ConnectionMonitor;
import ch.ethz.ssh2.SFTPv3Client;
import ch.ethz.ssh2.SFTPv3DirectoryEntry;
import ch.ethz.ssh2.SFTPv3FileHandle; Connection conn = new Connection(sshHostname);
conn.addConnectionMonitor(new ConnectionMonitor() { public void connectionLost(Throwable reason) { reason.getStackTrace(); throw new RuntimeException(reason); }
});
conn.connect(); File keyfile = new File(privKeyPath);
boolean isAuthenticated = conn.authenticateWithPublicKey(sshUsername, keyfile, sshPassword);
if (isAuthenticated == false) { throw new IOException("Connect SSH Authentication failed.");
}
log.info("Connecting to " + sshHostname + "successful !"); SFTPv3Client client = new SFTPv3Client(conn);
client.setCharset("GBK");
Vector<SFTPv3DirectoryEntry> fileList = client.ls(sourceFile);
if (fileList.size() == 0) { log.info("No file existed in the sourceFolder ["+sourceFile+"]"); return;
} for (SFTPv3DirectoryEntry entry : fileList) { log.debug("Capture the file "+entry.filename+" in the sourceFolder ["+"]"); if (".".equals(entry.filename) || "..".equals(entry.filename)) { continue; } if (!entry.filename.startsWith("atcc")) { continue; } CaptureDataTrack captureDataTrack = captureDataTrackService.captureChecker(entry.filename); if (captureDataTrack != null) { continue; } log.info(entry.filename + " " + entry.longEntry); SFTPv3FileHandle fileHandle = client.openFileRO(sourceFile + entry.filename); File myFile = new File(targetFile + entry.filename); OutputStream out = new FileOutputStream(myFile); long numread = 0; int length = 0; Long len = entry.attributes.size; int readSize = len.compareTo(Long.valueOf(loadSize)) > 0 ? loadSize : len.intValue(); byte[] bytes = new byte[readSize]; while (readSize > 0 && (numread = client.read(fileHandle, length, bytes, 0, readSize)) != -1) { length += numread; out.write(bytes); readSize = len.compareTo(Long.valueOf(length + loadSize)) > 0 ? loadSize : (int) (len - length); bytes = new byte[readSize]; } out.close();
}
参考:Ganymed SSH-2 java实现远程连接服务器并执行命令的方法(Windows和Linux)https://my.oschina.net/liuyuanyuangogo/blog/186159
/** To change this license header, choose License Headers in Project Properties.* To change this template file, choose Tools | Templates* and open the template in the editor.*/
package test;import java.io.IOException;import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;/*@author: Liu Yuanyuanpurpose: test connecting remote computer and execute linux command
*/public class TestRemoteConnect
{public static void main(String[] args) {String hostname = "192.168.100.50";int port = 22;//22 usually the default portString username = "root";String password = "highgo";//指明连接主机的IP地址 Connection conn = new Connection(hostname,port);Session ssh = null;try{//连接到主机 conn.connect();//使用用户名和密码校验 boolean isconn = conn.authenticateWithPassword(username, password);if (!isconn) {System.out.println("用户名称或者是密码不正确");} else {System.out.println("已经连接OK");//以下是linux的示例//将本地conf/server_start.sh传输到远程主机的/opt/pg944/目录下SCPClient clt = conn.createSCPClient(); clt.put("conf/server_start.sh", "/opt/pg944/"); //执行命令ssh = conn.openSession(); ssh.execCommand("sh /root/hello.sh");//ssh.execCommand("perl /root/hello.pl"); //只允许使用一行命令,即ssh对象只能使用一次execCommand这个方法,多次使用则会出现异常. //使用多个命令用分号隔开 //ssh.execCommand("cd /root; sh hello.sh"); /* 执行windows系统命令的示例Session sess = conn.openSession();sess.execCommand("ipconfig");*///将Terminal屏幕上的文字全部打印出来 InputStream is = new StreamGobbler(ssh.getStdout());BufferedReader brs = new BufferedReader(new InputStreamReader(is));while (true) {String line = brs.readLine();if (line == null) {break;}System.out.println(line);}} } catch (IOException e) {System.out.println(e.getMessage());e.printStackTrace();} finally {//连接的Session和Connection对象都需要关闭 if(ssh!=null){ssh.close();}if(conn!=null){conn.close();}}}
}
下载文件到本地并读写文件、上传文件
参考:java远程访问服务器的读写文件操作,自动登录读写文件https://blog.csdn.net/qq_34158117/article/details/93200941
Java使用Ganymed SSH远程登录服务器并读取文件相关推荐
- XManager5 ssh远程登录服务器工具xshell ,服务器资源上传下载工具xftp
XManager5 网盘下载 链接:https://pan.baidu.com/s/1t1wL3xnsucoP6hDnP30INA 提取码:9cq3 安装后 打开 ssh 远程登录服务器工具 xshe ...
- ssh远程登录虚拟机并下载文件到本地
ssh远程登录虚拟机并下载文件到本地 上ICS课程时想把老师提供的框架代码下载下来,但用fileZilla不知为何ssh登录不上去,故改用了MobaXterm,不仅是一个优秀的终端,还能方便且直观地下 ...
- linux服务器之间调用反应慢,Linux使用ssh远程登录服务器反应慢的解决办法
机房里其它机器使用ssh远程都正常,新来一个服务器每次使用ssh远程登录的时候,"root@***.***.***.***'s password:"这行输入密码的提示都来的特别慢, ...
- Linux 用ssh远程登录及scp传输文件
#ssh ssh命令是openssh套件中的客户端连接工具,可以给予ssh加密协议实现安全的远程登录服务器. ####语法 ssh (选项) 远程主机 ####常用选项 -1:强制使用ssh协议版本1 ...
- 用ssh远程登录服务器时,怎么直接以root用户登录?(需要修改配置,如果不想修改,可以先用普通用户登录再su切换到root用户)
如题,我在windows上用ssh登录ubuntu虚拟机时,不能用root用户直接登录, C:\Users\Arnold>ssh root@192.168.1.38 root@192.168.1 ...
- 树莓派zero w ssh远程登录配置好各种文件后连接电脑没有反应
问题描述:已经在tf卡中写入树莓派系统,新建ssh空白文件修改config.txt等文件后用usb- microusb将树莓派与电脑连接,电脑不跳出安装驱动的提示,设备管理器也找不到rndis驱动或者 ...
- 怎么样用ssh远程登录阿里云ecs服务器不成功解决方案
买的一年的大学生优惠机,玩玩而已,学学配置服务器环境 购买之后重置一下实例密码,这个是云服务器的密码 注意,重置实例密码后需要重启服务器和控制台 如果在控制台远程连接服务器的话,还有一个远程连接的密码 ...
- 使用SSH远程登录阿里云ECS服务器
FinalShell使用SSH远程登录阿里云ECS服务器CentOS7然后配置安全组入,登陆宝塔,经过一个星期的对云服务器的学习,深感体验,在学习的过程中,遇到了很多的困难.首先从搭建java环境,第 ...
- 本地和ssh服务器传文件,SSH远程登录实现本地机和服务器的文件传输
SSH是一种以安全.加密方式连接远程主机或服务器的方法.SSH服务器接受从有SSH的客户机的连接,允许操作者象在本地一样地登录系统.如果已经搭建了SSH远程登录服务,如何实现本地机和远程服务器的文件交 ...
最新文章
- 剑桥大学国际学生事务部网站
- POJ 3974-Palindrome
- 浅析Facebook LibraBFT与比原链Bystack BBFT共识
- Java实现快速排序 Quick Sort
- Linux head和tail指令
- Python常用命令行(持续更新)
- 拷贝构造,操作符重载
- NPM useful library path: request.js
- 蜗杆参数法设计_齿轮几何尺寸设计,很实用的Excel表格(附自动计算表格)
- sap打勾选项记录_记录意外的开关选项
- aqlserver实用程序_sqlserver命令提示实用工具的介绍
- oracle行列互换sql,解决Oracle行列转换问题的一个方法
- clone oracle ebs
- 大前端(全栈)学习路线指南
- 什么是DDD(领域驱动设计)?
- 德保罗大学计算机科学专业,德保罗大学专业
- 朴素贝叶斯算法——拼写检查器
- ipa文件安装到ios系统
- python turtle forward_Python turtle.forward方法代碼示例
- 第一型曲线和曲面积分总结