Java的SSH库

197

有人有使用Java进行SSH库连接的示例吗?


我曾经使用 Trilead SSH,但今天查看该网站时发现他们似乎已放弃了它。:( 这是我绝对最喜欢的一个。 - Peter D
1
顺便提一下,Trilead SSH2 似乎正在积极维护中(截至2013年10月):[https://github.com/jenkinsci/trilead-ssh2] - Mike Godin
Trilead SSH2在https://github.com/connectbot/sshlib上有一个分支。 - user7610
7个回答

130

Java Secure Channel(JSCH)是一款非常流行的库,被Maven、Ant和Eclipse等广泛使用。它是一个开源的软件,采用BSD样式的许可证。


2
你需要从https://sourceforge.net/projects/jsch/files/jsch/jsch-0.1.42.zip/download下载源代码,并运行“ant javadoc”。 - David Rabinowitz
77
我曾尝试过使用JSch,但不明白它为什么这么受欢迎。它几乎没有文档(甚至源码中也没有),API设计也很糟糕(http://techtavern.wordpress.com/2008/09/30/about-jsch-open-source-project/ 对此进行了很好的总结)。 - rluba
15
是的,Jsch很糟糕,这个更好:https://github.com/shikhar/sshj。 - anio
3
JSch的一个变体,包含公共方法的JavaDoc文档:https://github.com/ePaul/jsch-documentation - user423430
4
这个网页包含了一个使用JSCH运行命令并获取输出的示例。 - Charity Leschinski
显示剩余7条评论

69

更新:GSOC项目和那里的代码不再活跃,但这是:https://github.com/hierynomus/sshj

自2015年初以来,hierynomus成为了维护者。以下是旧的、不再维护的Github链接:https://github.com/shikhar/sshj


有一个GSOC项目:

http://code.google.com/p/commons-net-ssh/

代码质量似乎比JSch更好,JSch虽然是完整且可运行的实现,但缺乏文档。项目页面标注一个即将推出的Beta版本,最后一次提交到存储库的时间是八月中旬。

比较API:

http://code.google.com/p/commons-net-ssh/

    SSHClient ssh = new SSHClient();
    //ssh.useCompression(); 
    ssh.loadKnownHosts();
    ssh.connect("localhost");
    try {
        ssh.authPublickey(System.getProperty("user.name"));
        new SCPDownloadClient(ssh).copy("ten", "/tmp");
    } finally {
        ssh.disconnect();
    }

http://www.jcraft.com/jsch/

Session session = null;
Channel channel = null;

try {

JSch jsch = new JSch();
session = jsch.getSession(username, host, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect();

// exec 'scp -f rfile' remotely
String command = "scp -f " + remoteFilename;
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);

// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();

channel.connect();

byte[] buf = new byte[1024];

// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();

while (true) {
    int c = checkAck(in);
    if (c != 'C') {
        break;
    }

    // read '0644 '
    in.read(buf, 0, 5);

    long filesize = 0L;
    while (true) {
        if (in.read(buf, 0, 1) < 0) {
            // error
            break;
        }
        if (buf[0] == ' ') {
            break;
        }
        filesize = filesize * 10L + (long) (buf[0] - '0');
    }

    String file = null;
    for (int i = 0;; i++) {
        in.read(buf, i, 1);
        if (buf[i] == (byte) 0x0a) {
            file = new String(buf, 0, i);
            break;
        }
    }

    // send '\0'
    buf[0] = 0;
    out.write(buf, 0, 1);
    out.flush();

    // read a content of lfile
    FileOutputStream fos = null;

    fos = new FileOutputStream(localFilename);
    int foo;
    while (true) {
        if (buf.length < filesize) {
            foo = buf.length;
        } else {
            foo = (int) filesize;
        }
        foo = in.read(buf, 0, foo);
        if (foo < 0) {
            // error
            break;
        }
        fos.write(buf, 0, foo);
        filesize -= foo;
        if (filesize == 0L) {
            break;
        }
    }
    fos.close();
    fos = null;

    if (checkAck(in) != 0) {
        System.exit(0);
    }

    // send '\0'
    buf[0] = 0;
    out.write(buf, 0, 1);
    out.flush();

    channel.disconnect();
    session.disconnect();
}

} catch (JSchException jsche) {
    System.err.println(jsche.getLocalizedMessage());
} catch (IOException ioe) {
    System.err.println(ioe.getLocalizedMessage());
} finally {
    channel.disconnect();
    session.disconnect();
}

}

2
谢谢!我使用了Apache SSHD代码(提供异步API)作为种子,为项目提供了一个良好的开端。 - shikhar
1
太好了。我已经开始使用JSch项目,但如果我听到更多关于commons-net-ssh的积极反馈,我真的很想切换。 - miku
6
我应该提到,我是GSOC的学生 :) - shikhar
2
很高兴宣布 http://github.com/shikhar/sshj - 你可以在那里找到jar文件,正在想办法将其放入maven仓库。 - shikhar
1
jsch的SFTP比这里给出的要简单得多。也许这是旧代码,但它肯定不是现代API的示例。 - Charles Duffy
此外,据我所知,jsch是Java中唯一具有任何类型SSH代理支持的SSH实现。 - Charles Duffy

28

我刚刚发现了sshj,它的API比JSCH更加简洁(但需要Java 6)。目前,文档主要是通过示例在存储库中提供的,通常这对我来说不够用,但对于我刚开始的一个项目来说,它似乎足够好。


4
SSHJ 实际上可以被外界的人使用。JSCH 的文档和 API 设计混乱不堪,有许多隐含且难以解读的依赖关系。除非你想花费大量时间来研究代码并试图弄清楚问题所在,否则请使用 SSHJ。(我希望我对 JSCH 不是太苛刻或过分玩笑。我真心这么认为。) - Robert Fischer
2
是的,sshj。我尝试过的所有功能都可以正常工作:SCP、远程进程执行、本地和远程端口转发,以及使用jsch-agent-proxy的代理。而JSCH则比较混乱。 - Laurent Caillette
1
SSHJ的问题在于执行多个命令非常困难。SSHJ可能非常适合一次性执行命令,但如果您想编写更复杂的交互程序,则会很麻烦。(我刚刚浪费了半天时间) - bvdb

19

看一下最近发布的SSHD,它基于Apache MINA项目。


2
然而,使用它时缺乏文档和示例。 - Andreas Mattisson
看起来文档不足只是轻描淡写的说法:/ - Alkanshel

5

在github上发布了全新的Jsch版本:https://github.com/vngx/vngx-jsch 一些改进包括:全面的javadoc文档,提高性能,改善异常处理和更好的RFC规范遵循。如果您希望以任何方式做出贡献,请打开问题或发送拉取请求。


4
很遗憾,现在已经有超过三年没有新的提交了。 - Mike Lowery
@Scott,我在哪里可以找到一些开始工作的例子?请帮帮我。 - Touya Akira

0
我采用了Miku的答案和jsch示例代码。然后在会话期间,我需要下载多个文件保留原始时间戳。这是我的示例代码,说明如何做到这一点,可能很多人会发现它有用。请忽略filenameHack()函数,它只是我的特定用例。
package examples;

import com.jcraft.jsch.*;
import java.io.*;
import java.util.*;

public class ScpFrom2 {

    public static void main(String[] args) throws Exception {
        Map<String,String> params = parseParams(args);
        if (params.isEmpty()) {
            System.err.println("usage: java ScpFrom2 "
                    + " user=myid password=mypwd"
                    + " host=myhost.com port=22"
                    + " encoding=<ISO-8859-1,UTF-8,...>"
                    + " \"remotefile1=/some/file.png\""
                    + " \"localfile1=file.png\""
                    + " \"remotefile2=/other/file.txt\""
                    + " \"localfile2=file.txt\""

            );
            return;
        }

        // default values
        if (params.get("port") == null)
            params.put("port", "22");
        if (params.get("encoding") == null)
            params.put("encoding", "ISO-8859-1"); //"UTF-8"

        Session session = null;
        try {
            JSch jsch=new JSch();
            session=jsch.getSession(
                    params.get("user"),  // myuserid
                    params.get("host"),  // my.server.com
                    Integer.parseInt(params.get("port")) // 22
            );
            session.setPassword( params.get("password") );
            session.setConfig("StrictHostKeyChecking", "no"); // do not prompt for server signature

            session.connect();

            // this is exec command and string reply encoding
            String encoding = params.get("encoding");

            int fileIdx=0;
            while(true) {
                fileIdx++;

                String remoteFile = params.get("remotefile"+fileIdx);
                String localFile = params.get("localfile"+fileIdx);
                if (remoteFile == null || remoteFile.equals("")
                        || localFile == null || localFile.equals("") )
                    break;

                remoteFile = filenameHack(remoteFile);
                localFile  = filenameHack(localFile);

                try {
                    downloadFile(session, remoteFile, localFile, encoding);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        } catch(Exception ex) {
            ex.printStackTrace();
        } finally {
            try{ session.disconnect(); } catch(Exception ex){}
        }
    }

    private static void downloadFile(Session session, 
            String remoteFile, String localFile, String encoding) throws Exception {
        // send exec command: scp -p -f "/some/file.png"
        // -p = read file timestamps
        // -f = From remote to local
        String command = String.format("scp -p -f \"%s\"", remoteFile); 
        System.console().printf("send command: %s%n", command);
        Channel channel=session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command.getBytes(encoding));

        // get I/O streams for remote scp
        byte[] buf=new byte[32*1024];
        OutputStream out=channel.getOutputStream();
        InputStream in=channel.getInputStream();

        channel.connect();

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'

        // reply: T<mtime> 0 <atime> 0\n
        // times are in seconds, since 1970-01-01 00:00:00 UTC 
        int c=checkAck(in);
        if(c!='T')
            throw new IOException("Invalid timestamp reply from server");

        long tsModified = -1; // millis
        for(int idx=0; ; idx++){
            in.read(buf, idx, 1);
            if(tsModified < 0 && buf[idx]==' ') {
                tsModified = Long.parseLong(new String(buf, 0, idx))*1000;
            } else if(buf[idx]=='\n') {
                break;
            }
        }

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'

        // reply: C0644 <binary length> <filename>\n
        // length is given as a text "621873" bytes
        c=checkAck(in);
        if(c!='C')
            throw new IOException("Invalid filename reply from server");

        in.read(buf, 0, 5); // read '0644 ' bytes

        long filesize=-1;
        for(int idx=0; ; idx++){
            in.read(buf, idx, 1);
            if(buf[idx]==' ') {
                filesize = Long.parseLong(new String(buf, 0, idx));
                break;
            }
        }

        // read remote filename
        String origFilename=null;
        for(int idx=0; ; idx++){
            in.read(buf, idx, 1);
            if(buf[idx]=='\n') {
                origFilename=new String(buf, 0, idx, encoding); // UTF-8, ISO-8859-1
                break;
            }
        }

        System.console().printf("size=%d, modified=%d, filename=%s%n"
                , filesize, tsModified, origFilename);

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'

        // read binary data, write to local file
        FileOutputStream fos = null;
        try {
            File file = new File(localFile);
            fos = new FileOutputStream(file);
            while(filesize > 0) {
                int read = Math.min(buf.length, (int)filesize);
                read=in.read(buf, 0, read);
                if(read < 0)
                    throw new IOException("Reading data failed");

                fos.write(buf, 0, read);
                filesize -= read;
            }
            fos.close(); // we must close file before updating timestamp
            fos = null;
            if (tsModified > 0)
                file.setLastModified(tsModified);               
        } finally {
            try{ if (fos!=null) fos.close(); } catch(Exception ex){}
        }

        if(checkAck(in) != 0)
            return;

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'
        System.out.println("Binary data read");     
    }

    private static int checkAck(InputStream in) throws IOException {
        // b may be 0 for success
        //          1 for error,
        //          2 for fatal error,
        //          -1
        int b=in.read();
        if(b==0) return b;
        else if(b==-1) return b;
        if(b==1 || b==2) {
            StringBuilder sb=new StringBuilder();
            int c;
            do {
                c=in.read();
                sb.append((char)c);
            } while(c!='\n');
            throw new IOException(sb.toString());
        }
        return b;
    }


    /**
     * Parse key=value pairs to hashmap.
     * @param args
     * @return
     */
    private static Map<String,String> parseParams(String[] args) throws Exception {
        Map<String,String> params = new HashMap<String,String>();
        for(String keyval : args) {
            int idx = keyval.indexOf('=');
            params.put(
                    keyval.substring(0, idx),
                    keyval.substring(idx+1)
            );
        }
        return params;
    }

    private static String filenameHack(String filename) {
        // It's difficult reliably pass unicode input parameters 
        // from Java dos command line.
        // This dirty hack is my very own test use case. 
        if (filename.contains("${filename1}"))
            filename = filename.replace("${filename1}", "Korilla ABC ÅÄÖ.txt");
        else if (filename.contains("${filename2}"))
            filename = filename.replace("${filename2}", "test2 ABC ÅÄÖ.txt");           
        return filename;
    }

}

1
你能够重复使用会话并避免连接/断开的开销吗? - Sridhar Sarnobat

0

http://code.google.com/p/connectbot/, 在 Windows、Linux 或 Android 上编译 src\com\trilead\ssh2,它可以创建本地端口转发器、创建动态端口转发器或其他内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接