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

📄 sftpconnection.java

📁 一个JAVA做的FTP软件,带源码的,可以很好的进行二次开发,,并带有详细说明文件的
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. */package net.sf.jftp.net;import com.sshtools.j2ssh.*;import com.sshtools.j2ssh.authentication.*;import com.sshtools.j2ssh.io.*;import com.sshtools.j2ssh.session.*;import com.sshtools.j2ssh.sftp.*;import com.sshtools.j2ssh.subsystem.*;import com.sshtools.j2ssh.transport.*;import net.sf.jftp.config.Settings;import net.sf.jftp.util.Log;import net.sf.jftp.util.StringUtils;import org.apache.log4j.*;import java.io.*;import java.net.*;import java.util.*;public class SftpConnection implements BasicConnection{    public static int smbBuffer = 32000;    private String path = "";    private String pwd = "/";    private Vector listeners = new Vector();    private String[] files;    private String[] size = new String[0];    private int[] perms = null;    private String user;    private String pass;    private String host;    private String baseFile;    private int fileCount;    private boolean isDirUpload = false;    private boolean shortProgress = false;    private int RW = SftpSubsystemClient.OPEN_CREATE |                     SftpSubsystemClient.OPEN_WRITE;    private int W = SftpSubsystemClient.OPEN_CREATE;    private int R = SftpSubsystemClient.OPEN_READ;    private SftpSubsystemClient sftp = null;    private int port = 22;    private boolean connected = false;    private SshClient ssh = null;    private SessionChannelClient session = null;    public SftpConnection()    {    }    public SftpConnection(String host)    {        this.host = host;    }    public SftpConnection(String host, int port)    {        this.host = host;        this.port = port;    }    private boolean login()    {        try        {            ssh = new SshClient();            ssh.connect(host, port,                        new SftpVerification(Settings.sshHostKeyVerificationFile));            //ssh.connect(host);            PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();            pwd.setUsername(user);            pwd.setPassword(pass);            int result = ssh.authenticate(pwd);            if(result == AuthenticationProtocolState.COMPLETE)            {                session = ssh.openSessionChannel();                sftp = new SftpSubsystemClient();                session.startSubsystem(sftp);                // newer api                //SftpClient sftp = ssh.openSftpClient();                connected = true;                return true;            }            else            {                return false;            }        }        catch(Exception ex)        {            ex.printStackTrace();            Log.debug("Error: " + ex);            return false;        }    }    public int removeFileOrDir(String file)    {        file = toSFTP(file);        try        {            SftpFile f;            if(!file.endsWith("/"))            {                Log.out(">>>>>>>> remove file: " + file);                f = sftp.openFile(file, RW);                f.delete();            }            else            {                Log.out(">>>>>>>> remove dir: " + file);                f = sftp.openDirectory(file);                cleanSftpDir(file, f);                sftp.closeFile(f);                sftp.removeDirectory(file);            }        }        catch(Exception ex)        {            ex.printStackTrace();            Log.debug("Removal failed (" + ex + ").");            ex.printStackTrace();            return -1;        }        return 1;    }    private void cleanSftpDir(String dir, SftpFile f2)                       throws Exception    {        Log.out(">>>>>>>> cleanSftpDir: " + dir);        Vector v = new Vector();        while(sftp.listChildren(f2, v) > 0)        {            ;        }        String[] tmp = new String[v.size()];        SftpFile[] f = new SftpFile[v.size()];        Enumeration e = v.elements();        int x = 0;        while(e.hasMoreElements())        {            f[x] = ((SftpFile) e.nextElement());            tmp[x] = f[x].getFilename();            //Log.out("sftp delete: " + tmp[x]);            //Log.out(">>>>>>>> remove file/dir: " + tmp[x]);            if(f[x].isDirectory() && !tmp[x].endsWith("/"))            {                tmp[x] = tmp[x] + "/";            }            //sftp.closeFile(f[x]);            x++;        }        if(tmp == null)        {            return;        }        for(int i = 0; i < tmp.length; i++)        {            if(tmp[i].equals("./") || tmp[i].equals("../"))            {                continue;            }            SftpFile f3;            //System.out.println(dir+tmp[i]);            if(tmp[i].endsWith("/"))            {                f3 = sftp.openDirectory(dir + tmp[i]);            }            else            {                f3 = sftp.openFile(dir + tmp[i], RW);            }            Log.out(">>>>>>>> remove file/dir: " + dir + tmp[i]);            if(f3.isDirectory())            {                cleanSftpDir(dir + tmp[i], f3);                //sftp.closeFile(f3);                sftp.removeDirectory(dir + tmp[i]);            }            else            {                f3.delete();            }        }    }    public void sendRawCommand(String cmd)    {    }    public void disconnect()    {        try 	{          sftp.stop();          session.close();          ssh.disconnect();        } 	catch (IOException e) 	{	  e.printStackTrace();          Log.debug("SftpSshClient.disconnect()" + e);        }		connected = false;    }    public boolean isConnected()    {        return connected;    }    public String getPWD()    {        //Log.debug("PWD: " + pwd);        return toSFTPDir(pwd);    }    public boolean mkdir(String dirName)    {        try        {            if(!dirName.endsWith("/"))            {                dirName = dirName + "/";            }            dirName = toSFTP(dirName);            sftp.makeDirectory(dirName);            fireDirectoryUpdate();            return true;        }        catch(Exception ex)        {            Log.debug("Failed to create directory (" + ex + ").");            return false;        }    }    public void list(String outfile) throws IOException    {    }    public boolean chdir(String p)    {        return chdir(p, true);    }    public boolean chdir(String p, boolean refresh)    {        String tmp = toSFTP(p);        try        {            if(!tmp.endsWith("/"))            {                tmp = tmp + "/";            }            if(tmp.endsWith("../"))            {                return cdup();            }            SftpFile f = sftp.openDirectory(tmp);            //if(!f.isDirectory()) return false;            sftp.closeFile(f);            pwd = toSFTP(f.getAbsolutePath());            //Log.debug("chdir: " + getPWD());            if(refresh)            {                fireDirectoryUpdate();            }            //System.out.println("chdir2: " + getPWD());            //Log.debug("Changed path to: " + tmp);            return true;        }        catch(Exception ex)        {            ex.printStackTrace();            //System.out.println(tmp);            Log.debug("Could not change directory (" + ex + ").");            return false;        }    }    public boolean cdup()    {        String tmp = pwd;        if(pwd.endsWith("/"))        {            tmp = pwd.substring(0, pwd.lastIndexOf("/"));        }        return chdir(tmp.substring(0, tmp.lastIndexOf("/") + 1));    }    public boolean chdirNoRefresh(String p)    {        return chdir(p, false);    }    public String getLocalPath()    {        return path;    }    public boolean setLocalPath(String p)    {        if(StringUtils.isRelative(p))        {            p = path + p;        }        p = p.replace('\\', '/');        //System.out.println(", local 2:" + p);        File f = new File(p);        if(f.exists())        {            try            {                path = f.getCanonicalPath();                path = path.replace('\\', '/');                if(!path.endsWith("/"))                {                    path = path + "/";                }                //System.out.println("localPath: "+path);            }            catch(IOException ex)            {                Log.debug("Error: can not get pathname (local)!");                return false;            }        }        else        {            Log.debug("(local) No such path: \"" + p + "\"");            return false;        }        return true;    }    public String[] sortLs(String file)    {        try        {            String t = getPWD();            SftpFile fx = sftp.openDirectory(t);            //if(fx == null) System.out.println("Sftp: fx null");            Vector v = new Vector();            while(sftp.listChildren(fx, v) > 0)            {                ;            }            String[] tmp = new String[v.size()];            SftpFile[] f = new SftpFile[v.size()];            files = new String[tmp.length];            size = new String[tmp.length];            perms = new int[tmp.length];            Enumeration e = v.elements();            int x = 0;            while(e.hasMoreElements())            {                f[x] = ((SftpFile) e.nextElement());                tmp[x] = f[x].getFilename();                size[x] = f[x].getAttributes().getSize().toString();                //if(f[x].canWrite()) Log.debug(tmp[x]);                //if(f[x].canWrite()) perms[x] = FtpConnection.W;                //else                if(!f[x].canRead())                {                    perms[x] = FtpConnection.DENIED;                }                else                {                    perms[x] = FtpConnection.R;                }                //Log.debugRaw(".");                if(f[x].isDirectory() && !tmp[x].endsWith("/"))                {                    tmp[x] = tmp[x] + "/";                }                x++;            }            sftp.closeFile(fx);            for(int i = 0; i < tmp.length; i++)            {                files[i] = tmp[i];            }            //Log.debug(" done.");            return files;        }        catch(Exception ex)        {            //ex.printStackTrace();            //Log.debug(" Error while listing directory: " + ex);            return new String[0];        }    }    public String[] sortSize(String file)    {        return size;    }    public int[] getPermissions(String file)    {        return perms;    }    public int handleUpload(String f)    {        if(Settings.getEnableSftpMultiThreading())        {            SftpTransfer t = new SftpTransfer(host, getLocalPath(), getPWD(),                                              f, user, pass, listeners,                                              Transfer.UPLOAD);        }        else        {            upload(f);        }        return 0;    }    public int handleDownload(String f)    {        if(Settings.getEnableSftpMultiThreading())        {            SftpTransfer t = new SftpTransfer(host, getLocalPath(), getPWD(),                                              f, user, pass, listeners,                                              Transfer.DOWNLOAD);        }        else        {            download(f);        }        return 0;    }    public int upload(String f)    {        String file = toSFTP(f);        if(file.endsWith("/"))        {            String out = StringUtils.getDir(file);            uploadDir(file, getLocalPath() + out);            fireActionFinished(this);        }        else        {            String outfile = StringUtils.getFile(file);            //System.out.println("transfer: " + file + ", " + getLocalPath() + outfile);            work(getLocalPath() + outfile, file, true);            fireActionFinished(this);        }        return 0;    }    public int download(String f)    {

⌨️ 快捷键说明

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