java怎么通过sftp连接linux服务器
时间: 2023-08-04 19:38:18 浏览: 56
要在 Java 中通过 SFTP 连接 Linux 服务器,可以使用 JSch 这个开源库。以下是连接和上传文件的示例代码:
```java
import com.jcraft.jsch.*;
public class SftpExample {
public static void main(String[] args) {
String host = "example.com";
String username = "myusername";
String password = "mypassword";
String localFilePath = "/path/to/local/file.txt";
String remoteFilePath = "/path/to/remote/file.txt";
JSch jsch = new JSch();
Session session = null;
ChannelSftp channel = null;
try {
session = jsch.getSession(username, host, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
channel.put(localFilePath, remoteFilePath);
System.out.println("File uploaded successfully");
} catch (JSchException | SftpException e) {
e.printStackTrace();
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
}
```
在这个示例中,我们使用 `JSch` 类创建一个 `Session` 并连接到远程服务器。接着,我们创建一个 `ChannelSftp` 通道并连接到服务器。最后,我们使用 `put` 方法将本地文件上传到远程服务器。
需要注意的是,这个示例中的密码是明文存储的。在实际应用中,为了安全起见,应该将密码存储在安全的地方,并且通过其他方式获取密码,比如从环境变量中读取。