java sftp 执行linux语句
时间: 2023-05-14 12:07:29 浏览: 60
Java SFTP 可以通过 JSch 库来实现,以下是一个示例代码:
```
import com.jcraft.jsch.*;
public class SftpExample {
public static void main(String[] args) {
String host = "your_host";
String username = "your_username";
String password = "your_password";
int port = 22;
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.cd("/path/to/remote/directory");
sftpChannel.put("/path/to/local/file", "remote_filename");
sftpChannel.exit();
session.disconnect();
} catch (JSchException | SftpException e) {
e.printStackTrace();
}
}
}
```
这段代码可以连接到远程主机,上传本地文件到远程主机的指定目录。如果需要执行 Linux 命令,可以使用 `ChannelExec` 类来实现。