环境准备
远程机器A:Windows 10 专业版 22H2
本地环境:jdk8
安装OpenSSH 服务
1、安装
设置 --> 应用 --> 应用和功能 --> 可选功能 --> 添加功能
由于我已经安装,在以安装功能里面即可找到。未安装的用户选择添加功能添加即可
2、开启服务
win + r 输入 services.msc
启动 OpenSSH SSH Server 服务
3、验证是否安装成功
输入ssh 出现如下提示即安装成功
C:\Users\SERVER>ssh
usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]
[-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
[-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]
[-i identity_file] [-J [user@]host[:port]] [-L address]
[-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
[-Q query_option] [-R address] [-S ctl_path] [-W host:port]
[-w local_tun[:remote_tun]] destination [command]
代码开发
1、pom文件引入
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
2、OpenSshClient 工具类
package com.ncst;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.Objects;
/**
* @Author: Lisy
* @Date: 2023/05/30/14:44
* @Description: ssh2工具类
*/
@Slf4j
public class OpenSshClient {
private final String ip;
private final int port;
private final String username;
private final String password;
public OpenSshClient(String ip, int port, String username, String password) {
this.ip = ip;
this.port = port;
this.username = username;
this.password = password;
}
public OpenSshClient(String ip, String username, String password) {
this.ip = ip;
this.port = 22;
this.username = username;
this.password = password;
}
public void execCommand(String command) {
Connection conn = new Connection(ip, port);
Session sess = null;
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated) {
log.info("【远程执行命令】:{} 连接成功,---执行命令:{}", ip, command);
} else {
log.info("【远程执行命令】:{} 连接失败,请检查用户密码是否正确", ip);
}
sess = conn.openSession();
sess.execCommand(command);
//回显信息
InputStream is = new StreamGobbler(sess.getStdout());
BufferedReader brs = new BufferedReader(new InputStreamReader(is));
while (true) {
String line = brs.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
} finally {
if (Objects.nonNull(sess)) {
sess.close();
}
conn.close();
}
}
public void getFile(String remoteFile, String localTargetDirectory) {
Connection conn = new Connection(ip, port);
try {
SCPClient client = getScpClient(conn);
client.get(remoteFile, localTargetDirectory);
conn.close();
log.info("【获取文件成功】{}:{}", ip, remoteFile);
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
}
}
/**
* 上传文件
* @param localFile 本地文件位置
* @param remoteTargetDirectory 远程机器接收文件目录
*/
public void putFile(String localFile, String remoteTargetDirectory) {
Connection conn = new Connection(ip, port);
try {
SCPClient client = getScpClient(conn);
client.put(localFile, remoteTargetDirectory);
log.info("【文件远程上传】{} 上传成功", ip);
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
} finally {
conn.close();
}
}
/**
* 上传文件并对远程机器上的文件重命名
* @param localFile
* @param remoteFileName
* @param remoteTargetDirectory
* @param mode
*/
public void putFileRename(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
Connection conn = new Connection(ip, port);
try {
SCPClient client = getScpClient(conn);
if ((mode == null) || (mode.length() == 0)) {
mode = "0600";
}
client.put(localFile, remoteFileName, remoteTargetDirectory, mode);
//重命名
Session sess = conn.openSession();
String tmpPathName = remoteTargetDirectory + File.separator + remoteFileName;
String newPathName = tmpPathName.substring(0, tmpPathName.lastIndexOf("."));
sess.execCommand("mv " + remoteFileName + " " + newPathName);
log.info("【文件远程上传】{} 上传成功", ip);
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
} finally {
conn.close();
}
}
public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) {
Connection conn = new Connection(ip, port);
try {
SCPClient client = getScpClient(conn);
client.put(getBytes(localFile), remoteFileName, remoteTargetDirectory);
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
} finally {
conn.close();
}
}
/**
* 将文件输入到字节数组
*
* @param filePath 文件路径
* @return 字节数组
*/
private byte[] getBytes(String filePath) {
byte[] buffer = null;
File file = new File(filePath);
try (FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024 * 1024)) {
byte[] b = new byte[1024 * 1024];
int i;
while ((i = fis.read(b)) != -1) {
bos.write(b, 0, i);
}
buffer = bos.toByteArray();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return buffer;
}
private SCPClient getScpClient(Connection conn) throws IOException {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated) {
log.info("【文件远程上传】{} 连接成功", ip);
} else {
log.error("【文件远程上传】{} 验证失败", ip);
}
return new SCPClient(conn);
}
}
3、安装7z
编写 bat 脚本,在远程机器上面静默安装,命名为 install7z.bat文章来源:https://www.toymoban.com/news/detail-627764.html
start /wait E:\\7z.exe /S
4、准备7z.exe 安装包
在官网下载文章来源地址https://www.toymoban.com/news/detail-627764.html
4、测试类
/**
* 传输压缩包和7z并在远程机器上面解压并执行命令
*/
public static void main(String[] args) {
OpenSshClient winClient = new OpenSshClient("192.168.22.40", 22, "Admin", "123456");
String remoteDir = "E:\\";
String fileName = "a.zip";
// 传输7z.exe 和安装7z.exe脚本
winClient.putFile("E:\\testTmp\\7z.exe", "7z.exe", remoteDir);
winClient.putFile("E:\\testTmp\\install7z.bat", "install7z.bat", remoteDir);
// 安装7z.exe
winClient.execCommand(remoteDir + "install7z.bat");
// 传输客户端
winClient.putFile("E:\\testTmp\\" + fileName, fileName, remoteDir);
// 解压脚本
winClient.execCommand("C:\\\"Program Files\"\\7-Zip\\7z x E:\\a.zip -oE:\\");
// 删除安装包
winClient.execCommand("del E:\\a.zip");
winClient.execCommand("del E:\\7z.exe");
}
到了这里,关于Java通过OpenSSH(ssh2/ScpClient)远程连接Windows10实现传输文件、解压缩包、执行命令等操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!