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

📄 ssh2simplesftpshell.java

📁 一个非常好的ssh客户端实现
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/****************************************************************************** * * Copyright (c) 1999-2003 AppGate Network Security AB. All Rights Reserved. *  * This file contains Original Code and/or Modifications of Original Code as * defined in and that are subject to the MindTerm Public Source License, * Version 2.0, (the 'License'). You may not use this file except in compliance * with the License. *  * You should have received a copy of the MindTerm Public Source License * along with this software; see the file LICENSE.  If not, write to * AppGate Network Security AB, Otterhallegatan 2, SE-41118 Goteborg, SWEDEN * *****************************************************************************/package com.mindbright.ssh2;import java.awt.Frame;import java.awt.BorderLayout;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.File;import java.io.FileInputStream;import com.mindbright.terminal.TerminalWin;import com.mindbright.terminal.TerminalXTerm;import com.mindbright.terminal.LineReaderTerminal;/** * This class implements a basic interactive sftp session. It opens a * terminal window in which the user may interact with sftp using * typed commands. */public final class SSH2SimpleSFTPShell implements Runnable {    Frame              frame;    TerminalWin        terminal;    LineReaderTerminal linereader;    SSH2Connection     connection;    SSH2SFTPClient     sftp;    String localDir;    String remoteDir;    /**     * Class implementing a progress bar which gets printed in a     * terminal window.     */    public static final class ProgressBar implements SSH2SFTP.AsyncListener {	LineReaderTerminal linereader;	long               totalSize;	long               curSize;	long               start;	static final String[] prefix = { "", "k", "M", "G", "T" };	public ProgressBar(LineReaderTerminal linereader) {	    this.linereader = linereader;	}	public void start(long totalSize) {	    this.totalSize = totalSize;	    this.curSize   = 0;	    start = System.currentTimeMillis();	}	public void progress(long size) {	    long now = System.currentTimeMillis();	    curSize += size;	    int perc = (int)(totalSize > 0 ?			     ((100 * curSize) / totalSize) : 100);	    int i;	    StringBuffer buf = new StringBuffer();	    buf.append("\r " + perc + "%\t|");	    int len = (int)((double)32 * ((double)perc / 100));	    for(i = 0; i < len; i++) {		buf.append('*');	    }	    for(i = len; i < 32; i++) {		buf.append(' ');	    }	    long printSize = curSize;	    i = 0;	    while(printSize >= 100000) {		i++;		printSize >>>= 10;	    }	    buf.append("|  " + printSize + " " + prefix[i] + "bytes");	    long elapsed = (now - start);	    if(elapsed == 0) {		elapsed = 1;	    }	    int curSpeed = (int)((double)curSize / ((double)elapsed / 1000));	    i = 0;	    while(curSpeed >= 100000) {		i++;		curSpeed >>>= 10;	    }	    buf.append(" (" + curSpeed + " " + prefix[i] + "B/sec)   ");	    linereader.print(buf.toString());	}    }    /**     * This constructor needs an open connection to the server and a     * window name. It will create an sftp session on the connection     * and popup a new terminal window with the given title. It will     * also spawn a thread to run the sftp session.     *     * @param connection The connection to use.     * @param title Title of window.     */    public SSH2SimpleSFTPShell(SSH2Connection connection, String title) {	this.connection = connection;	this.frame      = new Frame();	this.terminal   = new TerminalWin(frame, new TerminalXTerm());	linereader      = new LineReaderTerminal(terminal);	frame.setLayout(new BorderLayout());	frame.add(terminal.getPanelWithScrollbar(),		  BorderLayout.CENTER);	frame.setTitle(title);	frame.addWindowListener(new WindowAdapter() {	    public void windowClosing(WindowEvent e) {		linereader.breakPromptLine("Exit");		sftp.terminate();	    }	});	frame.pack();	frame.show();	Thread shell = new Thread(this);	shell.setDaemon(true);	shell.start();    }    /**     * The thread running this gets created in the constructor. So     * there is no need to call this function explicitely.     */    public void run() {	linereader.println("Starting sftp...");        if (com.mindbright.util.Util.isNetscapeJava()) {            try {                netscape.security.PrivilegeManager.enablePrivilege("UniversalFileAccess");            } catch (netscape.security.ForbiddenTargetException e) {            }        }        	doHelp();	try {	    sftp = new SSH2SFTPClient(connection, false);	    File f = new File(".");	    localDir = f.getCanonicalPath();	    SSH2SFTP.FileAttributes attrs = sftp.realpath(".");	    remoteDir = attrs.lname;	    linereader.println("local dir:\t" + localDir);	    linereader.println("remote dir:\t" + remoteDir);	    boolean keepRunning = true;	    while(keepRunning) {		try {		    SSH2SFTP.FileHandle handle = null;		    String   cmdLine = linereader.promptLine("sftp> ", null,							     false);		    String[] argv;		    String   cmd;		    cmdLine = cmdLine.trim();		    if(cmdLine.equals("")) {			doHelp();			continue;		    }		    argv = makeArgv(cmdLine);		    cmd  = argv[0];		    if(cmd.equals("ls")) {			try {			    handle = sftp.opendir(remoteDir);			    SSH2SFTP.FileAttributes[] list = sftp.readdir(handle);			    for(int i = 0; i < list.length; i++) {				linereader.println(list[i].lname);			    }			} finally {			    try { sftp.close(handle); }			    catch (Exception e) { /* don't care */ }			}		    } else if(cmd.equals("cd")) {			if(argv.length < 2) {			    doHelp();			    continue;			}			String newDir = expandRemote(argv[1]);			try {			    attrs = sftp.realpath(newDir);			} catch (SSH2SFTP.SFTPException e) {			    linereader.println(newDir +					       ": No such remote directory.");			    continue;			}			newDir = attrs.lname;			try {			    handle = sftp.opendir(newDir);			    sftp.close(handle);			    remoteDir = newDir;			    linereader.println("remote: " + remoteDir);			} catch (SSH2SFTP.SFTPException e) {			    linereader.println(newDir + ": Not a remote directory.");			}		    } else if(cmd.equals("lls")) {			f = new File(localDir);			String[] list = f.list();			if(list == null) {			    linereader.print(localDir +					     " is empty or not accessible");			    continue;			}			for(int i = 0; i < list.length; i++) {			    f = new File(localDir + File.separator + list[i]);			    linereader.print((f.isDirectory() ? "d" : "-") +					     (f.canRead() ? "r" : "-") +					     (f.canWrite() ? "w" : "-") + "\t");			    linereader.print(f.length() + "\t");			    java.util.Date d = new java.util.Date(f.lastModified());			    java.text.DateFormat df =				java.text.DateFormat.getDateInstance();			    linereader.print(df.format(d) + "\t");			    linereader.println(list[i]);			}		    } else if(cmd.equals("lcd")) {			if(argv.length < 2) {			    doHelp();			    continue;			}			String newDir;			newDir = expandLocal(argv[1]);			f = new File(newDir);			if(f.exists() && f.isDirectory() && f.canRead()) {			    localDir = f.getCanonicalPath();			    linereader.println("local: " + localDir);			} else {			    linereader.println(newDir + ": No such local directory");			}		    } else if(cmd.equals("get")) {			if(argv.length < 2) {			    doHelp();			    continue;			}			String localFile  = argv[1]; // Default to same name			String remoteFile = expandRemote(localFile);			localFile = localFile.replace('/', File.separatorChar);			if(argv.length > 2) {			    localFile = argv[2];			}			localFile = expandLocal(localFile);			handle = sftp.open(remoteFile,					   SSH2SFTP.SSH_FXF_READ,					   new SSH2SFTP.FileAttributes());			attrs = sftp.fstat(handle);			linereader.println("download from remote '" +					   remoteFile + "',");			linereader.println("         to local '" +					   localFile + "', " + attrs.size +					   " bytes");			java.io.RandomAccessFile file =			    new java.io.RandomAccessFile(localFile, "rw");			int len   = (int)attrs.size;			int foffs = 0;			int cnt   = 0;			ProgressBar bar = new ProgressBar(linereader);			handle.addAsyncListener(bar);			bar.start(len);			while(foffs < len) {			    int n = (32768 < (len - foffs) ? 32768 :				     (int)(len - foffs));			    sftp.read(handle, foffs, file, n);			    foffs += n;			    if(++cnt == 24) {				cnt = 0;				handle.asyncWait(12);			    }			    if(linereader.ctrlCPressed()) {				handle.asyncClose();

⌨️ 快捷键说明

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