SSH 连接 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3303122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:12:25  来源:igfitidea点击:

SSH Connection Java

javanetworkingsshconnection

提问by Benni

Is it possible to make a ssh connection to a server with java?

是否可以使用 java 与服务器建立 ssh 连接?

回答by theomodsim

Yes, I used http://sourceforge.net/projects/sshtools/in a Java application to connect to a UNIX server over SSH, it worked quite well.

是的,我在 Java 应用程序中使用了http://sourceforge.net/projects/sshtools/通过 SSH 连接到 UNIX 服务器,它运行良好。

回答by ClutchDude

jschand sshJare both good clients. I'd personally use sshJ as the code is documented much more thoroughly.

jschsshJ都是很好的客户端。我个人会使用 sshJ,因为代码记录得更彻底。

jsch has widespread use, including in eclipse and apache ant. I've also had issues with jsch and AES encrypted private keys, which required re-encrypting in 3DES, but that could just be me.

jsch 有广泛的用途,包括在 eclipse 和 apache ant 中。我也遇到了 jsch 和 AES 加密私钥的问题,这需要在 3DES 中重新加密,但这可能只是我。

回答by Ripon Al Wasim

Yes, it is possible. You can try the following code:

对的,这是可能的。您可以尝试以下代码:

package mypackage;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.*;

public class SSHReadFile
    {
    public static void main(String args[])
    {
    String user = "user";
    String password = "password";
    String host = "yourhostname";
    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.");
        }
    catch(Exception e){System.err.print(e);}
    }
    }

回答by ZZ Coder

To make connection to Java servers, you need an implementation of SSHD (ssh client is not enough). You can try Apache SSHD,

要连接到 Java 服务器,您需要一个 SSHD 的实现(ssh 客户端是不够的)。你可以试试 Apache SSHD,

http://mina.apache.org/sshd/

http://mina.apache.org/sshd/

Because sshd is already running on most systems, an easier alternative is to connect to the server through a SSH tunnel.

由于 sshd 已在大多数系统上运行,因此更简单的替代方法是通过 SSH 隧道连接到服务器。