首页 > 解决方案 > 需要使用 Java 自动连接到 ssh

问题描述

我在java中使用Jsch与unix主机建立连接。我能够连接到unix主机。问题仍然是控制台,提示再次询问密码。

附上代码。

package newcon;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.channels.Channel;
import java.util.Scanner;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.UserInfo;

public class Conn {

            public static void main(String args[]) {
                String user = "XXXXXX";
                String password = "xxxxxxx";
                String host = "xxxxx";
                int port = 22;
                String command1="ls -ltr";
              try {


                java.util.Properties config = new java.util.Properties(); 
                    //config.put("StrictHostKeyChecking", "no");
                config.put("StrictHostKeyChecking", "no");
                JSch jsch = new JSch();
                    Session session=jsch.getSession(user,host, 22);
                    session.setPassword(password);
                    session.setConfig(config);
                    System.out.println("config:"+config);
                    session.connect();
                    System.out.println("Connected");

                    com.jcraft.jsch.Channel channel=session.openChannel("exec");
                    ((ChannelExec)channel).setCommand(command1);
                    channel.setInputStream(null);
                    ((ChannelExec)channel).setErrStream(System.err);

                    InputStream in=channel.getInputStream();
                    channel.connect();
                    byte[] tmp=new byte[1024];
                    while(true){
                      while(in.available()>0){
                        int i=in.read(tmp, 0, 1024);
                        if(i<0)break;
                        System.out.print(new String(tmp, 0, i));
                      }
                      if(channel.isClosed()){
                        System.out.println("exit-status: "+channel.getExitStatus());
                        break;
                      }
                      try{Thread.sleep(1000);}catch(Exception ee){}
                    }
                    channel.disconnect();
                    session.disconnect();
                    System.out.println("DONE");
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            }

任何人都可以帮助我解决公共密钥和键盘交互式密码。

这样在我的提示中没有给出任何信息,它将连接到主机。感谢一些人对上述问题的帮助,

谢谢,尼基尔

标签: javaunix

解决方案


我不能说它是一个错误日志,

仍然附上我可以从控制台看到的那个。

Kerberos 用户名 [nudayaku]:nuadayaku nuadayaku 的 Kerberos 密码:


推荐阅读