有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JSCH无效私钥

我正在运行JDK1.7&;使用netbeans 7.2的Windows 7 我已经生成了一个SSH私有&;使用putty keygen的公钥对(SSH2-2048位)。我没有任何私钥密码。 我现在正在尝试使用SFTP连接到一台主机。但当我传递私钥(ppk)以设置标识时,代码返回无效私钥错误。我在WinSCP中使用相同的私钥连接到相同的主机&;它工作得很好。请帮我解决这个错误。 这是我的密码:

JSch jsch = new JSch();

Session session = null;

try {

    jsch.addIdentity("D:\\TEMP\\key.ppk");

    session = jsch.getSession("tiabscp", "ssiw.support.qvalent.com", 22);
    session.setConfig("StrictHostKeyChecking", "no");
    //session.setPassword("");
    session.connect();
    Channel channel = session.openChannel("sftp");
    System.out.println("Getting connected");
    channel.connect();
    System.out.println("connected successfully");
    ChannelSftp sftpChannel = (ChannelSftp) channel;
    sftpChannel.get("remotefile.txt", "localfile.txt");
    sftpChannel.exit();
    session.disconnect();
}catch (JSchException e) {

    e.printStackTrace();

}catch (SftpException e) {

    e.printStackTrace();
}

共 (5) 个答案

  1. # 1 楼答案

    下面的示例代码可能会对您有所帮助

    package ssh.control;
    
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Properties;
    
    import android.util.Log;
    
    import com.jcraft.jsch.ChannelExec;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    
    
    public class SSHConnections {
        static String user="";
        static String pass="";
        static String ip="";
    
    
        static Session session;
    
        public static ChannelExec getChannelExec() throws Exception{
            //System.out.println("connected");
            //This class serves as a central configuration point, and as a factory for Session objects configured with these settings.
            JSch jsch = new JSch();
            //A Session represents a connection to a SSH server.
            session = jsch.getSession(user, ip, 22);
            //getSession()   :-  the session to which this channel belongs. 
            session.setPassword(pass);
    
            // Avoid asking for key confirmation
            //http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Properties.html
            Properties prop = new Properties();
            prop.put("StrictHostKeyChecking", "no");
    
    
            //Sets multiple default configuration options at once. 
            session.setConfig(prop);
    
            session.connect();
            if(session.isConnected()) {
                System.out.println("connected");
            }
    
            // SSH Channel 
            //Opens a new channel of some type over this connection. 
            ChannelExec channelssh = (ChannelExec) session.openChannel("exec");
    
            return channelssh;
        }
    
        public static  String[] executeRemoteCommand(String command) throws Exception {
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ChannelExec channelssh = SSHConnections.getChannelExec();
            channelssh.setOutputStream(baos);
    
            // Execute command
            channelssh.setCommand(command);//gedit tt
            InputStreamReader isr = new InputStreamReader(channelssh.getInputStream());
    
            BufferedReader bufred = new BufferedReader(isr);
    
            channelssh.connect();
            String s = bufred.readLine();
    
            List<String> lines = new ArrayList<String>();
    
            int count = 0;
            while( s!=null ) {
                //System.out.println(s);
                lines.add(count,s);
                //      filesandfolders[count]=s;
                //      System.out.println(filesandfolders[count]);
                s = bufred.readLine();  
                count++;
            }
    
            String filesandfolders[] = new String[count];
    
            for(int i = 0; i<count;i++) {
                filesandfolders[i] = lines.get(i);
                Log.d("filesandfolders[i]", filesandfolders[i]);
            }
            //for(int j=0;j<filesandfolders.length;j++) {
            //System.out.println(filesandfolders[j]);
            //}
            //System.out.println("lines is "+lines.get(0));
            //int a;
            //while((a = isr.read()) != -1)
            //System.out.print((char)a);
            //channelssh.disconnect();
            //return baos.toString();
            return filesandfolders;
        }
    
        public static  List<String> executeRemoteCommand1(String command) throws Exception {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ChannelExec channelssh=SSHConnections.getChannelExec();
            channelssh.setOutputStream(baos);
    
            // Execute command
            channelssh.setCommand(command);//gedit tt
            InputStreamReader isr = new InputStreamReader(channelssh.getInputStream());
    
            BufferedReader bufred = new BufferedReader(isr);
    
            channelssh.connect();
            String s = bufred.readLine();
    
            List<String> lines = new ArrayList<String>();
    
            int count=0;
            while(s != null) {
                //System.out.println(s);
                lines.add(count, s);
                //      filesandfolders[count] = s;
                //      System.out.println(filesandfolders[count]);
                s = bufred.readLine();  
                count++;
            }
    
            String filesandfolders[] = new String[count];
    
            for(int i=0; i<count;i++) {
                filesandfolders[i]=lines.get(i);
            }
            //for(int j=0;j<filesandfolders.length;j++) {
            //System.out.println(filesandfolders[j]);
            //}
            //System.out.println("lines is "+lines.get(0));
            //int a;
            //while((a = isr.read()) != -1)
            //System.out.print((char)a);
            //channelssh.disconnect();
            //return baos.toString();
            return lines;
        }
    }
    

    要创建目录,请执行以下操作:

    SSHConnections.user = "username";
    SSHConnections.ip = "192.168.1.102";
    SSHConnections.pass = "mypassword";
    ChannelExec channelssh = SSHConnections.getChannelExec();
    
    String dirname = "sampledirectory";
    try {
        String[] str = SSHConnections.executeRemoteCommand("mkdir "+dirname);
    } catch (Exception e) {
        e.printStackTrace();
    }
    
  2. # 2 楼答案

    也许不是你的解决方案,但我在寻找我的问题时发现了这个问题

    当JSCH需要私钥文件时,我意外地给出了公钥文件的路径

  3. # 3 楼答案

    我在使用JSch使用ppk到ssh时遇到了同样的问题。这可能对某人有用

    当使用Putty的ppk文件时,它曾经工作过。但是在JSch中使用相同的方法,它会抛出这个异常

    我尝试了几种解决方案。最后,我只是将ppk文件加载到PuTTYgen并保存私钥,该私钥生成了外观类似的(在文本编辑器中)文件,但效果不错

    1. 按“加载”并选择ppk文件
    2. 输入密码短语
    3. 单击加载选项下方的“保存私钥”按钮并保存私钥
  4. # 4 楼答案

    我猜您的密钥不是OpenSSH密钥文件格式。JSch希望私钥采用OpenSSH格式

    您可以使用PuTTYgen转换私钥以使用OpenSSH,方法是执行here中描述的步骤:

    1. 按Load并选择使用创建的私钥 普蒂根
    2. 输入密码短语以加载密钥
    3. 从转换中 菜单选择导出OpenSSH密钥
    4. 保存私钥
  5. # 5 楼答案

    您可以使用PEMWriter将私钥转换为JSch将接受的PEM格式

    下面的示例转换从Java密钥库(JKS)返回的密钥

    Key privateKey = KeyStore.getKey(privateKeyAlias, keyStorePassword);//get key from JKS
    StringWriter stringWriter = new StringWriter();
    PEMWriter pemWriter = new PEMWriter(stringWriter);
    pemWriter.writeObject(privateKey);
    pemWriter.close();
    
    byte[] privateKeyPEM = stringWriter.toString().getBytes();