续上一文章:
通过pscp.exe文件+小工具复制密码实现文件从windows上传到linux
发现还是有点不实用,每次都需要输入Linux服务器密码。
所以,我就网上找Java相关的代码解决方案。
java 实现文件上传到linux
解决方案如下:
添加sshj库到你的项目中,如果你使用的是Maven,可以添加以下依赖:
<dependency>
<groupId>net.schmizz</groupId>
<artifactId>sshj</artifactId>
<version>0.11.0</version>
</dependency>
然后样例代码:
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import java.io.File;
import java.io.FileInputStream;
public class FileUploader {
public static void uploadFile(String host, int port, String username, String password,
String localFilePath, String remoteDir) {
try (SSHClient ssh = new SSHClient()) {
ssh.connect(host, port);
ssh.authPassword(username, password);
try (SFTPClient sftp = ssh.newSFTPClient()) {
File file = new File(localFilePath);
sftp.put(new FileInputStream(file), file.length(), remoteDir + "/" + file.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "your_linux_server_ip";
int port = 22;
String username = "your_username";
String password = "your_password";
String localFilePath = "path_to_local_file";
String remoteDir = "remote_directory";
uploadFile(host, port, username, password, localFilePath, remoteDir);
}
}
但依赖的样例有问题:
<version>0.11.0</version>
我添加依赖后,maven一直没有正确下载
看到Maven 会自动从中央仓库(默认是 Maven 中央仓库https://repo.maven.apache.org/maven2/ )下载所需的库及其依赖项。
然后访问:https://repo.maven.apache.org/maven2
根据packet点击进去
看到仓库最新才0.10.0
然后改依赖的版本号,正确下载依赖
不过呢,看到仓库上面的上传日期是2014年,jar包很老了,后续考虑网上找最新版的下载。