private static String[] queryUserAndHost(String promptSuffix, String useThis) { if (useThis == null || !useThis.contains("@")) { useThis = JOptionPane.showInputDialog( "Enter username@hostname for " + promptSuffix, System.getProperty("user.name") + "@localhost"); } if (useThis == null) { throw new NoSuchElementException("User does not want!"); } return useThis.split("@"); }
public static void main(String[] arg) { String xhost = "127.0.0.1"; int xport = 0; try { JSch jsch = new JSch(); String host = null; if (arg.length > 0) { host = arg[0]; } else { host = JOptionPane.showInputDialog( "Enter username@hostname", System.getProperty("user.name") + "@localhost"); } String user = host.substring(0, host.indexOf('@')); host = host.substring(host.indexOf('@') + 1); Session session = jsch.getSession(user, host, 22); String display = JOptionPane.showInputDialog("Please enter display name", xhost + ":" + xport); xhost = display.substring(0, display.indexOf(':')); xport = Integer.parseInt(display.substring(display.indexOf(':') + 1)); session.setX11Host(xhost); session.setX11Port(xport + 6000); // username and password will be given via UserInfo interface. UserInfo ui = new MyUserInfo(); session.setUserInfo(ui); session.connect(); Channel channel = session.openChannel("shell"); channel.setXForwarding(true); channel.setInputStream(System.in); channel.setOutputStream(System.out); channel.connect(); } catch (Exception e) { System.out.println(e); } }
public static void main(String[] arg) { int lport; String rhost; int rport; try { JSch jsch = new JSch(); String host = null; if (arg.length > 0) { host = arg[0]; } else { host = JOptionPane.showInputDialog( "Enter username@hostname", System.getProperty("user.name") + "@localhost"); } String user = host.substring(0, host.indexOf('@')); host = host.substring(host.indexOf('@') + 1); Session session = jsch.getSession(user, host, 22); String foo = JOptionPane.showInputDialog("Enter -L port:host:hostport", "port:host:hostport"); lport = Integer.parseInt(foo.substring(0, foo.indexOf(':'))); foo = foo.substring(foo.indexOf(':') + 1); rhost = foo.substring(0, foo.indexOf(':')); rport = Integer.parseInt(foo.substring(foo.indexOf(':') + 1)); // username and password will be given via UserInfo interface. UserInfo ui = new MyUserInfo(); session.setUserInfo(ui); session.connect(); // Channel channel=session.openChannel("shell"); // channel.connect(); int assinged_port = session.setPortForwardingL(lport, rhost, rport); System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport); } catch (Exception e) { System.out.println(e); } }
/** * Creates a SSH Session with a remote machine and tries to login according to the details * specified by Contact An appropriate message is shown to the end user in case the login fails * * @param sshContact ID of SSH Contact * @throws JSchException if a JSch is unable to create a SSH Session with the remote machine * @throws InterruptedException if the thread is interrupted before session connected or is timed * out * @throws OperationFailedException if not of above reasons :-) */ public void createSSHSessionAndLogin(ContactSSH sshContact) throws JSchException, OperationFailedException, InterruptedException { logger.info("Creating a new SSH Session to " + sshContact.getHostName()); // creating a new JSch Stack identifier for contact JSch jsch = new JSch(); String knownHosts = (String) accountID.getAccountProperties().get("KNOWN_HOSTS_FILE"); if (!knownHosts.equals("Optional")) jsch.setKnownHosts(knownHosts); String identitiyKey = (String) accountID.getAccountProperties().get("IDENTITY_FILE"); String userName = sshContact.getUserName(); // use the name of system user if the contact has not supplied SSH // details if (userName.equals("")) userName = System.getProperty("user.name"); if (!identitiyKey.equals("Optional")) jsch.addIdentity(identitiyKey); // creating a new session for the contact Session session = jsch.getSession( userName, sshContact.getHostName(), sshContact.getSSHConfigurationForm().getPort()); /** * Creating and associating User Info with the session User Info passes authentication from * sshContact to SSH Stack */ SSHUserInfo sshUserInfo = new SSHUserInfo(sshContact); session.setUserInfo(sshUserInfo); /** initializing the session */ session.connect(connectionTimeout); int count = 0; // wait for session to get connected while (!session.isConnected() && count <= 30000) { Thread.sleep(1000); count += 1000; logger.trace("SSH:" + sshContact.getHostName() + ": Sleep zzz .. "); } // if timeout have exceeded if (count > 30000) { sshContact.setSSHSession(null); JOptionPane.showMessageDialog( null, "SSH Connection attempt to " + sshContact.getHostName() + " timed out"); // error codes are not defined yet throw new OperationFailedException( "SSH Connection attempt to " + sshContact.getHostName() + " timed out", 2); } sshContact.setJSch(jsch); sshContact.setSSHSession(session); logger.info("A new SSH Session to " + sshContact.getHostName() + " Created"); }
public class ScpRetrieveFileTransfer extends AbstractRetrieveFileTransfer implements IScpFileTransfer { private static final String SCP_COMMAND = System.getProperty( "org.eclipse.ecf.filetransfer.scp.retrieve.scpcommand", "scp -f "); // $NON-NLS-1$ private static final String SCP_EXEC = System.getProperty( "org.eclipse.ecf.filetransfer.scp.retrieve.scpcommand", "exec"); // $NON-NLS-1$ String username; Channel channel; OutputStream responseStream; private ScpUtil scpUtil; /* * (non-Javadoc) * * @see * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer * #doPause() */ protected boolean doPause() { return false; } /* * (non-Javadoc) * * @see * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer * #doResume() */ protected boolean doResume() { return false; } public URL getTargetURL() { return getRemoteFileURL(); } public Map getOptions() { return options; } /* * (non-Javadoc) * * @see * org.eclipse.ecf.provider.filetransfer.outgoing.AbstractOutgoingFileTransfer * #openStreams() */ protected void openStreams() throws IncomingFileTransferException { try { // Set input stream from local file final URL url = getRemoteFileURL(); this.username = url.getUserInfo(); scpUtil = new ScpUtil(this); final Session s = scpUtil.getSession(); s.connect(); final String command = SCP_COMMAND + scpUtil.trimTargetFile(url.getPath()); channel = s.openChannel(SCP_EXEC); ((ChannelExec) channel).setCommand(command); channel.connect(); final InputStream ins = channel.getInputStream(); responseStream = channel.getOutputStream(); scpUtil.sendZeroToStream(responseStream); final int c = checkAck(ins); if (c != 'C') throw new IOException(Messages.ScpRetrieveFileTransfer_EXCEPTION_SCP_PROTOCOL); // read '0644 ' final byte[] buf = new byte[1024]; ins.read(buf, 0, 5); setFileLength(readFileSize(ins, buf)); readFileName(ins, buf); // set input stream for reading rest of file remoteFileContents = ins; scpUtil.sendZeroToStream(responseStream); fireReceiveStartEvent(); } catch (final Exception e) { channel = null; username = null; throw new IncomingFileTransferException( NLS.bind( Messages.ScpRetrieveFileTransfer_EXCEPTION_CONNECTING, getRemoteFileURL().toString()), e); } } static int checkAck(InputStream in) throws IOException { int b = in.read(); // b may be 0 for success, // 1 for error, // 2 for fatal error, // -1 if (b == 0) return b; if (b == -1) return b; if (b == 1 || b == 2) { StringBuffer sb = new StringBuffer(); int c; do { c = in.read(); sb.append((char) c); } while (c != '\n'); if (b == 1 || b == 2) { // error throw new IOException( Messages.ScpRetrieveFileTransfer_EXCEPTION_SCP_PROTOCOL + ": " + sb.toString()); } } return b; } /* * (non-Javadoc) * * @see * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer * #handleReceivedData(byte[], int, double, * org.eclipse.core.runtime.IProgressMonitor) */ protected void handleReceivedData(byte[] buf, int bytes, double factor, IProgressMonitor monitor) throws IOException { if (bytes == -1) { done = true; } else { int fileBytes = bytes; if ((bytesReceived + bytes) > fileLength) { fileBytes = (int) (fileLength - bytesReceived); } bytesReceived += fileBytes; localFileContents.write(buf, 0, fileBytes); fireTransferReceiveDataEvent(); monitor.worked((int) Math.round(factor * fileBytes)); if (fileBytes != bytes) { scpUtil.checkAck(buf[fileBytes], remoteFileContents); done = true; } } } private long readFileSize(InputStream ins, byte[] buf) throws IOException { long filesize = 0L; while (true) { if (ins.read(buf, 0, 1) < 0) { throw new IOException(Messages.ScpRetrieveFileTransfer_EXCEPTION_ERROR_READING_FILE); } if (buf[0] == ' ') break; filesize = filesize * 10L + (buf[0] - '0'); } return filesize; } private String readFileName(InputStream ins, byte[] buf) throws IOException { String file = null; for (int i = 0; ; i++) { ins.read(buf, i, 1); if (buf[i] == (byte) 0x0a) { file = new String(buf, 0, i); break; } } return file; } /* * (non-Javadoc) * * @see * org.eclipse.ecf.provider.filetransfer.outgoing.AbstractOutgoingFileTransfer * #hardClose() */ protected void hardClose() { try { if (remoteFileContents != null && scpUtil != null) { scpUtil.sendZeroToStream(responseStream); scpUtil.dispose(); scpUtil = null; remoteFileContents = null; responseStream = null; } } catch (final IOException e) { exception = e; } finally { super.hardClose(); channel = null; username = null; } } /* * (non-Javadoc) * * @see * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer * #getAdapter(java.lang.Class) */ public Object getAdapter(Class adapter) { if (adapter == null) return null; if (adapter.equals(IFileTransferPausable.class)) return null; return super.getAdapter(adapter); } /* * (non-Javadoc) * * @see * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer * #setupProxy(org.eclipse.ecf.core.util.Proxy) */ protected void setupProxy(Proxy proxy) { this.proxy = proxy; } /* * (non-Javadoc) * * @see * org.eclipse.ecf.provider.filetransfer.scp.IScpFileTransfer#getConnectContext * () */ public IConnectContext getConnectContext() { return connectContext; } /* * (non-Javadoc) * * @see * org.eclipse.ecf.provider.filetransfer.scp.IScpFileTransfer#getUsername() */ public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } /* * (non-Javadoc) * * @see * org.eclipse.ecf.provider.filetransfer.scp.IScpFileTransfer#promptPassphrase * () */ public boolean promptPassphrase() { // XXX TODO // return (keyFile != null); return false; } public Proxy getProxy() { return this.proxy; } }