⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sshinteractiveclient.java

📁 一个非常好的ssh客户端实现
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
  }  public void disconnected(SSHClient client, boolean graceful) {      sshStdIO.breakPromptLine("Login aborted by user");      updateMenus();      updateTitle();  }  public void report(String msg) {      if(msg != null && msg.length() > 0) {	  console.println(msg);      }      console.println("");  }  public SSH2Interactor getInteractor() {      return this;  }  public void alert(String msg) {      if(menus != null) {	  if(msg.length() < 50)	      menus.alertDialog(msg);	  else	      menus.textDialog("MindTerm - Alert", msg, 4, 38, true);      } else {	  report(msg);      }  }    public void forcedDisconnect() {	if(isSSH2) {	    transport.normalDisconnect("Closed by user");	} else {	    super.forcedDisconnect();	}    }    public void requestLocalPortForward(String localHost, int localPort,					String remoteHost, int remotePort,					String plugin)	throws IOException    {	if(isSSH2) {	    SSH2StreamFilterFactory filter = null;	    if("ftp".equals(plugin)) {		String serverLocalAddr = propsHandler.getProperty("real-server");		if(serverLocalAddr == null) {		    serverLocalAddr = propsHandler.getProperty("server");		}		filter = new SSH2FTPProxyFilter(localHost, serverLocalAddr);	    } else if("sniff".equals(plugin)) {		filter = SSH2StreamSniffer.getFilterFactory();	    }	    connection.newLocalForward(localHost, localPort,				       remoteHost, remotePort, filter);	} else {	    super.requestLocalPortForward(localHost, localPort,					  remoteHost, remotePort, plugin);	}    }    public void addRemotePortForward(String remoteHost, int remotePort,				     String localHost, int localPort,				     String plugin)    {	super.addRemotePortForward(remotePort, localHost, localPort, plugin);	if(isSSH2) {	    delRemotePortForward(remoteHost, remotePort);	    connection.newRemoteForward(remoteHost, remotePort,					localHost, localPort);	}    }    public void delLocalPortForward(String localHost, int port) {	boolean isop = isOpened;	if(isSSH2) {	    connection.deleteLocalForward(localHost, port);	    isOpened = false;	}	super.delLocalPortForward(localHost, port);	isOpened = isop;    }    public void delRemotePortForward(String remoteHost, int port) {	if(isSSH2) {	    connection.deleteRemoteForward(remoteHost, port);	}    }    void setAliveInterval(int i) {	if(isSSH2) {	    transport.enableKeepAlive(i);	} else {	    super.setAliveInterval(i);	}    }    void runSSH2Client() throws IOException {	try {	    SSH2Preferences prefs;	    isSSH2 = true;	    prefs  = new SSH2Preferences(propsHandler.getProperties());	    if(SSH.DEBUGMORE) {		prefs.setPreference(SSH2Preferences.LOG_LEVEL, "7");	    }	    transport = new SSH2Transport(sshSocket,					  prefs,					  null,					  secureRandom());	    transport.setEventHandler(new SSH2TransportEventAdapter() {		    public boolean kexAuthenticateHost(SSH2Transport tp,					       SSH2Signature serverHostKey) {			try {			    propsHandler.showFingerprint(serverHostKey.getPublicKeyBlob(),							 serverHostKey.getAlgorithmName());			    if(fingerprintMatch(serverHostKey)) {				return true;			    }			    return propsHandler.verifyKnownSSH2Hosts(						     SSHInteractiveClient.this,						     serverHostKey);			} catch (SSH2Exception e) {			    transport.getLog().error("SSHInteractiveClient",						     "verifyKnownSSH2Hosts",						     "Error " + e.getMessage());			} catch (IOException e) {			    transport.getLog().error("SSHInteractiveClient",						     "verifyKnownSSH2Hosts",						     "Error " + e.getMessage());			}			return false;		    }		    public void gotConnectInfoText(SSH2Transport tp,						   String text) {			alert(text);		    }		});	    transport.boot();	    srvVersionStr = transport.getServerVersion();	    connected(null);	    if(!transport.waitForKEXComplete()) {		throw new IOException("Key exchange failed: " +				      transport.getDisconnectMessage());	    }	    isConnected = true;	    SSH2Authenticator authenticator =		new SSH2Authenticator() {			public void peerMethods(String methods) {			    addAuthModules(this, methods);			}			public void displayBanner(String banner) {			    alert(banner);			}		    };	    authenticator.setUsername(propsHandler.getUsername(null));	    SSH2UserAuth userAuth = new SSH2UserAuth(transport, authenticator);	    if(!userAuth.authenticateUser("ssh-connection")) {		throw new AuthFailException("permission denied");	    }	    connection = new SSH2Connection(userAuth, transport, null);	    connection.setEventHandler(new SSH2ConnectionEventAdapter() {		    public void localSessionConnect(SSH2Connection connection,						    SSH2Channel channel) {			// !!! REMOVE		    }		    public void localDirectConnect(SSH2Connection connection,						   SSH2Listener listener,						   SSH2Channel channel) {			tunnels.addElement(channel);		    }		    public void remoteForwardConnect(SSH2Connection connection,						     String remoteAddr, int remotePort,						     SSH2Channel channel) {			tunnels.addElement(channel);		    }		    public void channelClosed(SSH2Connection connection,					      SSH2Channel channel) {			tunnels.removeElement(channel);		    }		});	    transport.setConnection(connection);	    authenticator.clearSensitiveData();	    if(console != null)		console.serverConnect(null, null);	    isOpened = true;	    open(null);	    if (menus != null) {		((SSHMenuHandlerFull)menus).modulesConnect();	    }	    // !!! Ouch	    // Activate tunnels at this point	    //	    propsHandler.passivateProperties();	    propsHandler.activateProperties();	    TerminalWin terminal = getTerminalWin();	    SSH2SessionChannel session;	    if(terminal != null) {		terminal.addInputListener(this);		termAdapter = new SSH2TerminalAdapterImpl(terminal);		session = connection.newTerminal(termAdapter);		// !!! OUCH must do this here since activateProperties is above		if(propsHandler.hasKeyTimingNoise()) {		    termAdapter.startChaff();		}		if(session.openStatus() != SSH2Channel.STATUS_OPEN) {		    throw new IOException("Failed to open ssh2 session channel");		}		if(user.wantX11Forward()) {		    session.requestX11Forward(false, 0);		}		if(user.wantPTY()) {		    session.requestPTY(terminal.terminalType(),				       terminal.rows(),				       terminal.cols(),				       null);		}		if(commandLine != null) {		    session.doSingleCommand(commandLine);		} else {		    session.doShell();		}	    } else {		session = connection.newSession();	    }	    int status = session.waitForExit(0);	    if(terminal != null) {		terminal.removeInputListener(this);	    }	    termAdapter.detach();	    transport.normalDisconnect("Disconnect by user");	    console.serverDisconnect(getServerAddr().getHostName() + " disconnected: " + status);	    disconnect(true);	    if(propsHandler.getCompressionLevel() != 0) {		SSH2Compressor comp;		for(int i = 0; i < 2; i++) {		    comp = (i == 0 ? transport.getTxCompressor() :			    transport.getRxCompressor());		    if(comp != null) {			String msg;			long compressed, uncompressed;			compressed   = comp.numOfCompressedBytes();			uncompressed = (comp.numOfUncompressedBytes() > 0 ?					comp.numOfUncompressedBytes() : 1);			msg = " raw data (bytes) = " + uncompressed +			    ", compressed = " + compressed + " (" +			    ((compressed * 100) / uncompressed) + "%)";			console.println((i == 0 ? "outgoing" : "incoming") +					msg);		    }		}	    }	    sshStdIO.setTerminal(terminal);	} catch (IOException e) {	    disconnect(false);	    throw e;	} catch (Exception e) {	    System.err.println("** Error in ssh2: ");	    e.printStackTrace();	    disconnect(false);	    throw new IOException("Error in ssh2: " + e.getMessage());	} finally {	    ((SSHMenuHandlerFull)menus).modulesDisconnect();	    connection = null;	    transport = null;	    isSSH2 = false;	}    }    public boolean fingerprintMatch(SSH2Signature serverHostKey) {	String fp = propsHandler.getProperty("fingerprint");	if(fp == null) {	    fp = propsHandler.getProperty("fingerprint." +					  propsHandler.getProperty("server") +					  "." +					  propsHandler.getProperty("port"));	}	if(fp != null) {	    if(SSH2HostKeyVerifier.compareFingerprints(fp, serverHostKey)) {		return true;	    }	    if(propsHandler.askChangeKeyConfirmation()) {		byte[] blob = null;		try {		    blob = serverHostKey.getPublicKeyBlob();		} catch (SSH2SignatureException e) {		    return false;		}		String fpMD5Hex = SSH2KeyFingerprint.md5Hex(blob);		propsHandler.setProperty("fingerprint", fpMD5Hex);	    }	}	return false;    }    public void typedChar(char c) {    }    public void sendBytes(byte[] b) {    }    public void signalWindowChanged(int rows, int cols,				    int vpixels, int hpixels) {	updateTitle();    }    public void addAuthModules(SSH2Authenticator authenticator, String methods)    {	try {	    int[] authTypes = propsHandler.getAuthTypes(null);	    for(int i = 0; i < authTypes.length; i++) {		int type = authTypes[i];		if(!SSH2ListUtil.isInList(methods, SSH.getAuthName(type)) &&		   !SSH2ListUtil.isInList(methods, SSH.getAltAuthName(type)) &&		   !((type == AUTH_SDI) &&		     SSH2ListUtil.isInList(methods, "securid-1@ssh.com"))) {		    report("Authentication method '" + SSH.getAuthName(type) +			   "' not supported by server.");		    continue;		}		switch(type) {		case AUTH_PUBLICKEY:		    String keyFile = propsHandler.getProperty("idfile");		    if(keyFile.indexOf(File.separator) == -1) {			keyFile = propsHandler.getSSHHomeDir() + keyFile;		    }		                        if (com.mindbright.util.Util.isNetscapeJava()) {                        try {                            netscape.security.PrivilegeManager.enablePrivilege("UniversalFileAccess");                        } catch (netscape.security.ForbiddenTargetException e) {                        }                    }                    		    SSH2KeyPairFile kpf = new SSH2KeyPairFile();		    try {			kpf.load(keyFile, "");		    } catch (SSH2FatalException e) {			throw new IOException(e.getMessage());		    } catch (SSH2AccessDeniedException e) {			String comment = kpf.getComment();			if(comment == null || comment.trim().length() == 0) {			    comment = keyFile;			}			String prompt = "Key '" + comment + "' password: ";			String passwd =			    propsHandler.getIdentityPassword(prompt);			kpf.load(keyFile, passwd);		    }		    String        alg  = kpf.getAlgorithmName();		    SSH2Signature sign = SSH2Signature.getInstance(alg);		    sign.initSign(kpf.getKeyPair().getPrivate());		    sign.setPublicKey(kpf.getKeyPair().getPublic());		    authenticator.addModule(new SSH2AuthPublicKey(sign));		    break;		case AUTH_PASSWORD:		    authenticator.addModule(new SSH2AuthPassword(propsHandler.getPassword(null)));		    break;		case AUTH_SDI:		case AUTH_TIS:		case AUTH_CRYPTOCARD:		case AUTH_KBDINTERACT:		    authenticator.addModule(new SSH2AuthKbdInteract(this));		    authenticator.addModule(new SSH2AuthSSHComSecurID(this,		      "Enter Passcode: ",		      "Wait for token to change and enter Passcode: ",		      "New PIN:",		      "Confirm new PIN: ",		      "Do you want to create your own new PIN (yes/no)? ",		      "Accept the server assigned PIN: "));		    break;		default:		    throw new IOException("Authentication type " +					  authTypeDesc[authTypes[i]] +					  " is not supported in SSH2");		}	    }	} catch (Exception e) {	    if(SSH.DEBUGMORE) {		System.out.println("Error when setting up authentication: ");		int[] t = propsHandler.getAuthTypes(null);		for(int i = 0; i < t.length; i++) {		    System.out.print(t[i] + ", ");		}		System.out.println("");		e.printStackTrace();	    }	    alert("Error when setting up authentication: " + e.getMessage());	}    }    public void newShell() {	// Ouch, this is kludgy because the MindTerm class handles the thread	ModuleTerminalImpl terminal = new ModuleTerminalImpl();	terminal.init(this);	terminal.run();    }    public String getVersionId(boolean client) {	String idStr = "SSH-" + SSH_VER_MAJOR + "." + SSH_VER_MINOR + "-";	idStr += propsHandler.getProperty("package-version");	return idStr;    }    public void closeTunnelFromList(int listIdx) {	if(isSSH2) {	    SSH2Channel c = (SSH2Channel)tunnels.elementAt(listIdx);	    c.close();	} else {	    controller.closeTunnelFromList(listIdx);	}    }    private Vector tunnels = new Vector();    public String[] listTunnels() {	if(isSSH2) {	    String[] list   = new String[tunnels.size()];	    Enumeration e   = tunnels.elements();	    int         cnt = 0;	    while(e.hasMoreElements()) {		SSH2TCPChannel c = (SSH2TCPChannel)e.nextElement();		list[cnt++] = c.toString();	    }	    return list;	} else {	    return controller.listTunnels();	}    }    //    // MindTermApp interface implementation    //    public String getHost() {	return getServerAddr().getHostName();    }    public int getPort() {	return propsHandler.getSrvPort();    }    public Properties getProperties() {	Properties  props     = new Properties(propsHandler.getProperties());	TerminalWin term      = getTerminalWin();	Properties  termProps = (term != null ? term.getProperties() : null);	if(termProps != null) {	    Enumeration e = termProps.keys();	    while(e.hasMoreElements()) {		String key = (String)e.nextElement();		String val = termProps.getProperty(key);		props.put(key, val);	    }	}	return props;    }    public String getProperty(String name) {	String value = propsHandler.getProperty(name);	if(value == null) {	    TerminalWin term = getTerminalWin();	    if(term != null) {		value = term.getProperty(name);	    }	}	return value;    }    public void setProperty(String name, String value) {	propsHandler.setProperty(name, value);    }    public String getUserName() {	return propsHandler.getProperty("username");    }    public Frame getParentFrame() {	return ((SSHMenuHandlerFull)menus).parent;    }    public String getAppName() {	return "MindTerm";    }    public RandomSeed getRandomSeed() {	return SSH.randomSeed();    }    public boolean isApplet() {	return ((SSHMenuHandlerFull)menus).mindterm.weAreAnApplet;    }    public AppletContext getAppletContext() {	return ((SSHMenuHandlerFull)menus).mindterm.getAppletContext();    }    public SSH2Transport getTransport() {	return transport;    }    public SSH2Connection getConnection() {	return connection;    }    public SSHConsoleRemote getConsoleRemote() {	SSHConsoleRemote remote = null;	if(isSSH2) {	    remote = new SSH2ConsoleRemote(getConnection());	} else {	    quiet = true;	    try {		remote  = new SSHConsoleClient(propsHandler.getSrvHost(),					       propsHandler.getSrvPort(),					       propsHandler, null);		((SSHConsoleClient)remote).setClientUser(propsHandler);	    } catch (IOException e) {		alert("Error creating remote console: " + e.getMessage());	    }	}	return remote;    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -