如何在Java中连接到SSH服务器?我不需要/想要一个贝壳。我只想连接到SSH服务器并获取file.txt的内容。我该怎么做呢?
发布于 2012-01-26 21:51:24
使用JSch
import com.jcraft.jsch.*;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
/**
* @author World
*/
public class SSHReadFile {
public static void main(String args[]) {
String user = "john";
String password = "mypassword";
String host = "192.168.100.23";
int port = 22;
String remoteFile = "/home/john/test.txt";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");
System.out.println("Crating SFTP Channel.");
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
System.out.println("SFTP Channel created.");
InputStream inputStream = sftpChannel.get(remoteFile);
try (Scanner scanner = new Scanner(new InputStreamReader(inputStream))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
}
} catch (JSchException | SftpException e) {
e.printStackTrace();
}
}
}输出:
Establishing Connection...
Connection established.
Crating SFTP Channel.
SFTP Channel created.
This is content from file /home/john/test.txt发布于 2010-06-19 01:21:43
Java本身并不支持这个功能,但是您可以使用像JSch这样的库来实现这个功能
发布于 2010-06-19 01:21:47
看看Jaramiko吧。
https://stackoverflow.com/questions/3071760
复制相似问题