精华内容
下载资源
问答
  • qt sftp
    千次阅读 热门讨论
    2020-10-29 15:11:34

    需求描述

    公司的产品基本都是基于arm-Linux系统的,sshd服务肯定都是标配了,目前需要实现一个通过上位机与仪器相连,完成仪器的升级。各种方案使用下来,发现最简单以及有效的方案还是采用如下步骤:

    • 将应用软件压缩打包成tar包;
    • 开机启动脚本启动的时候,去检测是否存在需要升级的tar包。如果存在升级包,则解压覆盖升级包;
    • 启动主程序;

    所以需要做的工作有两个部分,第一步是将升级包下载到仪器指定位置,第二步是重启仪器,等待升级完成。考虑过ftp服务、私有协议等,发现用sftp是最方便的,因为系统本身都带了这个服务,又可以做到与应用无关,这样升级起来,就非常方便。

    解决方案

    应用都是基于Qt开发,肯定优先考虑QSsh,通过测试发现,这位博主提供的库最好用,直接编译就行,而且没有乱七八糟的的告警什么的,示例还是可以看官方的。下面记录一下该库的基本用法,本项目用到了使用sftp上传以及下载文件,shell实现指令下发。咋一看示例,觉得挺复杂的,梳理一下,还是挺方便好用的。

        QSsh::SshConnectionParameters m_parameters;           //连接用的参数,包括用户名、密码、主机地址、端口、认证方式
        {
        	m_parameters.host = text;
        	m_parameters.port = 22;
        	m_parameters.userName = "root";
        	m_parameters.password = "root";
        	m_parameters.timeout = 60;
        	m_parameters.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePassword;
       }
            
        QSsh::SshConnection *m_connection;             //建立ssh socket连接
        QSsh::SftpChannel::Ptr m_channel;              //sftp上传、下载文件用的通道
        QSsh::SshRemoteProcess::Ptr m_shell;           //执行shell命令的通道
    
    1. 建立连接,这里最好是在响应连槽函数中,new出一个新的连接,连接中断以后,直接deleteLater释放连接
            m_parameters.host = text;
            m_parameters.port = 22;
            m_parameters.userName = "root";
            m_parameters.password = "root";
            m_parameters.timeout = 60;
            m_parameters.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePassword;
    
            m_connection = new QSsh::SshConnection(m_parameters);
            connect(m_connection, SIGNAL(connected()), SLOT(handleConnected()));             
            connect(m_connection, SIGNAL(disconnected()), SLOT(handleDisconnected()));
    
    1. 在连接成功的槽函数中,建立sftp以及shell的通道
    void MainWindow::handleConnected()
    {
        ui->textEdit->append("Connected. Initializing SFTP channel...");
        m_channel = m_connection->createSftpChannel();
        connect(m_channel.data(), SIGNAL(initialized()), this, SLOT(handleChannelInitialized()));
        connect(m_channel.data(), SIGNAL(channelError(QString)), this,SLOT(handleChannelInitializationFailure(QString)));
        connect(m_channel.data(), SIGNAL(finished(QSsh::SftpJobId,QString)), this, SLOT(handleJobFinished(QSsh::SftpJobId,QString)));
        connect(m_channel.data(), SIGNAL(closed()), this, SLOT(handleChannelClosed()));
        m_channel->initialize();
    
        m_shell = m_connection->createRemoteShell();
        connect(m_shell.data(), SIGNAL(started()), SLOT(handleShellStarted()));
        m_shell->start();
    }
    
    1. 在通道初始化成功的槽函数中,就可以正式使用sftp以及shell指令了。调用uploadFile donwloadFile上传下载文件,调用write函数写入shell命令
        const QSsh::SftpJobId uploadJob = m_channel->uploadFile(localFilePath,remoteFilePath, QSsh::SftpOverwriteExisting);
        if (uploadJob == QSsh::SftpInvalidJob)
        {
            ui->textEdit->append("Error uploading local file ");
            earlyDisconnectFromHost();
        }
    
    1. 执行结果通过槽函数来获取,执行是否成功
    void MainWindow::handleJobFinished(QSsh::SftpJobId job, const QString &error)
    {
    }
    
    1. Shell指令执行的时候记得,要加"\r\n"
    m_shell->write("reboot now\r\n");
    
    更多相关内容
  • 压缩包里面包括sftp的库文件,vs版本:vc9.0(vs2008),qt:4.8.6,qt sftp下载文件。编译好程序 可以传参调用。
  • QT实现SFTP

    2018-10-31 17:37:50
    sftpchannel.cpp,sshinit.cpp,sshlogging.cpp,sshconnection.cpp,sshpacket.cpp,sshlogging_p.h,sshsendfacility_p.h,sftpfilesystemmodel.cpp,sshpacket_p.h,sshchannelmanager_p.h,sshinit_p.h,sftpchannel.h,...
  • 基于qt5、sftp下载文件

    2020-04-21 17:19:31
    基于qt5+mingw+win7,里面包括有封装好的sftp库。参考原作者https://download.csdn.net/download/qq_26360165/10576625并修改。最简单的一个小demo
  • (https://github.com/helllyf/Qt-SFTP)功能实现了指定文件后缀名定时上传功能。 sftp实现通过密码和秘钥方式上传。 有完善的xml配置功能。 程序开启默认读取配置文件实现上传功能。若配置文件读取失败或者连接服务器...
  • 功能实现了指定文件后缀名定时上传功能。...sftp实现通过密码和秘钥方式上传。 有完善的xml配置功能。 程序开启默认读取配置文件实现上传功能。若配置文件读取失败或者连接服务器失败,则弹出配置窗口来配置。
  • QT实现SSH,sftp

    2020-10-20 16:19:28
    sftp.pro,parameters.h,sftptest.h,sftptest.cpp,sftp.pro.user,main.cpp,argumentscollector.cpp,build-sftp-Desktop_Qt_5_9_0_MinGW_32bit-Debug,Makefile.Debug,.qmake.stash,Makefile.Release,debug,moc_...
  • 基于qt5、sftp上传文件

    2018-12-05 09:54:00
    基于qt5+mingw+win7,里面包括有封装好的sftp库。参考原作者https://download.csdn.net/download/qq_26360165/10576625并修改。最简单的一个小demo
  • QT中实现SFTP

    千次阅读 热门讨论 2018-10-31 17:35:30
    最近由于项目需要,使用QSsh库实现SFTP功能,之前由于从来没有折腾过SFTP,所以有点费劲,网上的资料要求要下载libssh2和openssl,由于挺急的,所以直接从网上直接找了QT去和实现SFTP,整了大概有几天,总算把这个功能实现了...

    最近由于项目需要,使用QSsh库实现SFTP功能,之前由于从来没有折腾过SFTP,所以有点费劲,网上的资料要求要下载libssh2和openssl,由于挺急的,所以直接从网上直接找了QT去和实现SFTP,整了大概有几天,总算把这个功能实现了,这里将代码给那些有这些需求的朋友,同时将具体步骤告知
    1.打开pro文件
    2.首先构建src目录,然后在构建SercureUpLoad目录

    这个项目文件是在https://github.com/dushibaiyu/QSsh提供的项目之上理解,并进行改动,在此感谢提供此例子的朋友
    由于本人之前对这方面也没有太多涉及,不足之处多多包涵,本人例子项目下载地址:https://download.csdn.net/download/qq_37602761/10756168

    首先在SercureUpLoad目录下我封装了一个SZRSFtpTools类,这个类中包含SFTP的上传下载功能,懒得看代码,想直接使用的朋友直接更改pro文件,然后添加main.cpp文件可以直接测试函数是否可用
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    如果有朋友想将这个SFTP功能制作为一个动态库,那么上面的操作你可以不用进行,直接构建项目就行,这里要注意,因为我没有改动pro文件中动态库的生成路径,以本例子项目为例,生成的动态库存在于可执行程序下的目录,如下图
    在这里插入图片描述
    这里还要注意,这个功能必须要依赖QT提供的QSsh库,这个动态库在你执行构建SRC操作时,动态库就已经被制作成功,他生成在此例子下的lib目录
    在这里插入图片描述
    此例子,相对来说代码比较简单,我就简单讲一下上传文件代码实现步骤
    1.设置SFTP服务器主机ip和用户名以及密码

    void SZRSFtpTools::setSftpInfo(const QString &host, const QString &userName, const QString &pwd)
    {
        m_sftp->setInfo(host,userName,pwd);
        m_host = host;
        m_userName = userName;
        m_pwd = pwd;
    }
    

    2.初始化QSsh::SshConnection类,并通过设置的信息连接服务器

    if(m_connection)
            m_connection->disconnectFromHost();
        QSsh::SshConnectionParameters params;
        params.host = m_host;
        params.userName = m_userName;
        params.password = m_pwd;
        params.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePassword;
        params.timeout = 300;
        params.port = 22;
        m_connection = new QSsh::SshConnection(params, this); // TODO free this pointer!
        connect(m_connection, SIGNAL(connected()), SLOT(onConnected()));
        connect(m_connection, SIGNAL(error(QSsh::SshError)), SLOT(onConnectionError(QSsh::SshError)));
    
        qDebug() << "SecureUploader: Connecting to host" << m_host;
    
        m_connection->connectToHost();
    

    3.在连接成功响应的槽函数中初始化通道

    qDebug() << "SecureUploader: Connected";
        qDebug() << "SecureUploader: Creating SFTP channel...";
    
        m_channel = m_connection->createSftpChannel();
    
        if (m_channel) {
            connect(m_channel.data(), SIGNAL(initialized()),
                    SLOT(downLoadFile()));
            connect(m_channel.data(), SIGNAL(initializationFailed(QString)),
                    SLOT(onChannelError(QString)));
            connect(m_channel.data(), SIGNAL(finished(QSsh::SftpJobId, QString)),
                    SLOT(onDownLoadfinished(QSsh::SftpJobId, QString)));
            m_channel->initialize();
        } else {
            qDebug() << "SecureUploader: Error null channel";
        }
    

    4.通过响应通道创建成功的槽函数创建上传文件任务

    QFileInfo fileInfo(DownFileName);
        QString SftpSavePath  = DownSavePath;
        SftpSavePath += "/";
        SftpSavePath += fileInfo.fileName();
        QSsh::SftpJobId job = m_channel->downloadFile(DownFileName,SftpSavePath,QSsh::SftpOverwriteExisting);
        if (job != QSsh::SftpInvalidJob) {
            qDebug() << "SecureUploader: Starting job #" << job;
        } else {
            emit loadError();
            qDebug() << "SecureUploader: Invalid Job";
        }
    
    展开全文
  • NullFXP是基于Qt技术的具有GUI的跨平台SFTP / FTP /安全FTP客户端。 它同时支持多主机连接和多传输彼此支持的协议。
  • 最近涉及到sftp通信编码。上传测试代码记录一下。 头文件: #ifndef SFTPMANAGER_H #define SFTPMANAGER_H #ifdef WIN32 #include "libssh2/win32/libssh2_config.h" #endif #include <mutex> #include &...

      最近涉及到sftp通信编码。上传测试代码记录一下。

      头文件:

    #ifndef SFTPMANAGER_H
    #define SFTPMANAGER_H
    
    #ifdef WIN32
    #include "libssh2/win32/libssh2_config.h"
    #endif
    #include <mutex>
    #include <memory>
    #include <QThread>
    #include <iostream>
    #include <vector>
    #include <libssh2/libssh2.h>
    #ifdef WIN32
    #include <windows.h>
    #include <winsock2.h>
    #pragma comment(lib, "Ws2_32.lib")
    #else
    #include <sys/socket.h>
    #include <unistd.h>
    #include <arpa/inet.h>
    #endif
    
    
    
    class SftpManager
    {
    public:
    
        SftpManager();
        virtual ~SftpManager();
    
        bool connect(std::string szIp, int nPort = 22);
    
        bool createSession();
    
        bool login(std::string szUserName, std::string szPassword);
    
        bool read();
    
        bool mkdir();
    
        bool readAndWrite();
    
    private:
        SOCKET m_socket;
        LIBSSH2_SESSION *m_session = nullptr;
    
        std::vector<LIBSSH2_CHANNEL*> m_channels;
        //std::vector<std::mutex *> m_channel_mutexs;
        std::vector<std::shared_ptr<std::mutex>> m_channel_mutexs;
        static std::string m_ipAddress;
        static int m_port;
        static std::string m_username;
        static std::string m_password;
    
        static void initConnectionInfo();
        static int waitsocket(int socket_fd, LIBSSH2_SESSION *session);
         void shutDown();
        static std::string ipAddress();
        static std::string username();
        static std::string password();
        static int port();
    };
    
    #endif // SFTPMANAGER_H
    

    源文件:

    #include "SftpManager.h"
    #include <QtXml>
    #include <libssh2/libssh2_sftp.h>
    #define STORAGE "d:\\src\\test.txt"
    
    std::string SftpManager::m_password;
    std::string SftpManager::m_username;
    std::string SftpManager::m_ipAddress;
    int SftpManager::m_port;
    const char *sftppath = "/home/loohos-01/abc/test";
    const char *m_sftppath = "/home/loohos-01/abc/test_mkdir";
    const char *m_dest = "/home/loohos-01/abc/test_dest";
    
    
    
    
    SftpManager::SftpManager()
    {
    
    }
    SftpManager::~SftpManager()
    {
        if (!m_channels.empty()){
            for (auto channel : m_channels) if (nullptr != channel) libssh2_channel_free(channel);
            m_channels.clear();
        }
        /*
        if (!m_channel_mutexs.empty()){
            for (auto mtx : m_channel_mutexs) delete mtx;
            m_channel_mutexs.clear();
        }
        */
    
        if (nullptr != m_session){
            libssh2_session_disconnect(m_session, "Bye bye, Thank you");
            libssh2_session_free(m_session);
            m_session = nullptr;
        }
    
        libssh2_exit();
    
        if (INVALID_SOCKET != m_socket) closesocket(m_socket);
    
    #ifdef WIN32
            WSACleanup();
    #endif
    
    }
    
    int SftpManager::waitsocket(int socket_fd, LIBSSH2_SESSION *session )
    {
        struct timeval timeout;
        int rc;
        fd_set fd;
        fd_set *writefd = NULL;
        fd_set *readfd = NULL;
        int dir;
    
        timeout.tv_sec = 10;
        timeout.tv_usec = 0;
    
        FD_ZERO(&fd);
        FD_SET(socket_fd, &fd);
    
        dir = libssh2_session_block_directions(session);
    
        if(dir & LIBSSH2_SESSION_BLOCK_INBOUND)
            readfd = &fd;
    
        if(dir & LIBSSH2_SESSION_BLOCK_OUTBOUND)
            writefd = &fd;
    
        rc = select(socket_fd + 1, readfd, writefd, NULL, &timeout);
    
        return rc;
    }
    
    bool SftpManager::connect(std::string szIp, int nPort)
    {
        unsigned long hostaddr;
        int sock, i, auth_pw = 1;
        struct sockaddr_in sin;
        const char *fingerprint;
        LIBSSH2_SESSION *session;
        const char *username = "loohos-01";
        const char *password = "liuhe1688";
    
    
    #ifdef HAVE_GETTIMEOFDAY
        struct timeval start;
        struct timeval end;
        long time_ms;
    #endif
        int rc;
        int total = 0;
        int spin = 0;
        LIBSSH2_SFTP *sftp_session;
        LIBSSH2_SFTP_HANDLE *sftp_handle;
    
    #ifdef WIN32
        WSADATA wsadata;
        int err;
    
        err = WSAStartup(MAKEWORD(2,0), &wsadata);
        if(err != 0)
        {
            qDebug() << "WSAStartup failed with error:" << err;
            return false;
        }
    #endif
        if(szIp == ""){
            szIp = ipAddress();
        }
        if(nPort < 1){
            nPort = port();
        }
        rc = libssh2_init(0);
        if(rc != 0){
           qDebug() << "libssh2 initialization failed." << rc;
           return false;
        }
        hostaddr = inet_addr(szIp.c_str());
        m_socket = socket(AF_INET, SOCK_STREAM, 0);
    
        sin.sin_family = AF_INET;
        sin.sin_port = htons(22);
        sin.sin_addr.s_addr = hostaddr;
        rc = ::connect(m_socket, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in));
        if ( rc != 0) {
            qDebug() << "Failed to connect!" << rc;
            return false;
        }
        return true;
    }
    
    bool SftpManager::createSession()
    {
        int rc = 0;
        LIBSSH2_KNOWNHOSTS *nh = nullptr;
        size_t len;
        int type;
        const char *fingerprint;
    
        m_session = libssh2_session_init();
        if(!m_session){
            qDebug() << "Create session instance failed.";
            return false;
        }
    
        /* Since we have set non-blocking, tell libssh2 we are non-blocking */
        libssh2_session_set_blocking(m_session, 1);
    
        while ((rc = libssh2_session_handshake(m_session, m_socket)) == LIBSSH2_ERROR_EAGAIN);
        if(rc){
            qDebug() << "Failure establishing SSH session." << rc;
            return false;
        }
    
        fingerprint = libssh2_hostkey_hash(m_session, LIBSSH2_HOSTKEY_HASH_SHA1);
        qDebug() << "Fingerprint: ";
        for (int i =0; i < 20; i++) {
            qDebug() << "%02X " << (unsigned char)fingerprint[i];
        }
        qDebug() << "\n";
        return true;
    }
    
    bool SftpManager::login(std::string szUserName, std::string szPassword)
    {
        int rc = 0;
        int auth_pw = 1;
        if(szUserName == ""){
            szUserName = username();
        }
        if(szPassword == ""){
            szPassword = password();
        }
    
        if(szPassword.size() > 0){
            /* We could authenticate via password */
            while ((rc = libssh2_userauth_password(m_session, "loohos-01", "liuhe1688")) ==
                   LIBSSH2_ERROR_EAGAIN);
            if (rc) {
                qDebug() << "Authentication by password failed.";
                shutDown();
                return false;
            }
        }else{
            /* Or by public key */
            while ((rc = libssh2_userauth_publickey_fromfile(m_session, m_username.c_str(),
                                                             "/home/user/"
                                                             ".ssh/id_rsa.pub",
                                                             "/home/user/"
                                                             ".ssh/id_rsa",
                                                             m_password.c_str())) ==
                   LIBSSH2_ERROR_EAGAIN);
            if (rc) {
                qDebug() << "Authentication by public key failed.";
                shutDown();
            }
        }
        return true;
    }
    
    bool SftpManager::read()
    {
        LIBSSH2_SFTP *m_sftp_session;
        LIBSSH2_SFTP_HANDLE *m_sftp_handle;
        int rc,total,spin = 0;
        m_sftp_session = libssh2_sftp_init(m_session);
        if(!m_sftp_session)
        {
            qDebug() << "Unable to init SFTP session\n";
            shutDown();
        }
        qDebug() << "libssh2_sftp_open()!\n";
        /* Request a file via SFTP */
        do{
           m_sftp_handle =
               libssh2_sftp_open(m_sftp_session, sftppath, LIBSSH2_FXF_READ, 0);
           if(!m_sftp_handle)
           {
               if(libssh2_session_last_errno(m_session) != LIBSSH2_ERROR_EAGAIN){}
               qDebug() << "Unable to open file with SFTP\n";
               shutDown();
           }else {
                qDebug() << "non-blocking open\n";
                /*waitsocket(m_socket, m_session); *//* now we wait */
            }
           }while(!m_sftp_handle);
        qDebug() << "libssh2_sftp_open() is done, now receive data!\n";
        do {
                char mem[1024*24];
    
                /* loop until we fail */
                while ((rc = libssh2_sftp_read(m_sftp_handle, mem,
                                               sizeof(mem))) == LIBSSH2_ERROR_EAGAIN) {
                    spin++;
                    waitsocket(m_socket, m_session); /* now we wait */
                }
                if (rc > 0) {
                    total += rc;
                    write(1, mem, rc);
                } else {
                    qDebug() << "the messages with sftp are : " <<mem;
                    break;
                }
            } while (1);
    
        libssh2_sftp_close(m_sftp_handle);
        libssh2_sftp_shutdown(m_sftp_session);
        return true;
        }
    
    bool SftpManager::mkdir()
    {
    
        LIBSSH2_SFTP *m_sftp_session;
        m_sftp_session = libssh2_sftp_init(m_session);
        if(!m_sftp_session)
        {
            qDebug() << "Unable to init SFTP session\n";
            shutDown();
        }
        qDebug() << "libssh2_sftp_open()!\n";
        while(libssh2_sftp_mkdir(m_sftp_session,m_sftppath,LIBSSH2_SFTP_S_IRWXU|
                                 LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IXGRP|
                                 LIBSSH2_SFTP_S_IROTH|LIBSSH2_SFTP_S_IXOTH)
              == LIBSSH2_ERROR_EAGAIN);
    
        libssh2_sftp_shutdown(m_sftp_session);
    }
    
    bool SftpManager::readAndWrite()
    {
        char mem[1000];
        LIBSSH2_SFTP *m_sftp_session;
        LIBSSH2_SFTP_HANDLE *m_sftp_handle;
        int rc;
        int total,spin = 0;
        struct timeval timeout;
        fd_set fd;
        FILE *tempstorage = NULL;
    
    
        tempstorage = fopen(STORAGE, "wb");
        if(!tempstorage){
            qDebug() << "can't open temp storage file\n" << STORAGE;
            shutDown();
        }
    
        m_sftp_session = libssh2_sftp_init(m_session);
        if(!m_sftp_session)
        {
            qDebug() << "Unable to init SFTP session\n";
            shutDown();
        }
        qDebug() << "libssh2_sftp_open()!\n";
        /* Request a file via SFTP */
        do{
           m_sftp_handle =
               libssh2_sftp_open(m_sftp_session, sftppath, LIBSSH2_FXF_READ, 0);
           if(!m_sftp_handle)
           {
               if(libssh2_session_last_errno(m_session) != LIBSSH2_ERROR_EAGAIN){}
               qDebug() << "Unable to open file with SFTP\n";
               shutDown();
           }else {
                qDebug() << "non-blocking open\n";
                /*waitsocket(m_socket, m_session); *//* now we wait */
            }
           }while(!m_sftp_handle);
        qDebug() << "libssh2_sftp_open() is done, now receive data!\n";
    
        do{
            do {
                rc = libssh2_sftp_read(m_sftp_handle,mem,sizeof (mem));
                qDebug() << "libssh2_sftp_read returned %d/n" << rc;
                if(rc > 0){
                    write(2,mem,rc);
                    fwrite(mem,rc,1,tempstorage);
                }
            } while (rc>0);
            if (rc != LIBSSH2_ERROR_EAGAIN){
                break;
            }
    
            timeout.tv_sec = 10;
            timeout.tv_usec = 0;
    
            FD_ZERO(&fd);
            FD_SET(m_socket,&fd);
    
            rc = select(m_socket + 1, &fd, &fd, NULL, &timeout);
            if(rc <= 0){
                qDebug() << "SFTP download timed out: %d\n" << rc;
                break;
            }
        }while(1);
        libssh2_sftp_close(m_sftp_handle);
        fclose(tempstorage);
    
        tempstorage = fopen(STORAGE, "rb+");
        if(!tempstorage){
            qDebug() << "can't open %s for reading\n" << STORAGE;
            shutDown();
        }
    
    
        m_sftp_handle =
                libssh2_sftp_open(m_sftp_session, m_dest,
                                  LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT,
                                  LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR|
                                  LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH);
        if(m_sftp_handle){
            size_t nread;
            char *ptr;
            do{
                nread = fread(mem, 1, sizeof (mem), tempstorage);
                if(nread <= 0){
                    break;
                }
                ptr = mem;
    
                do{
                    rc = libssh2_sftp_write(m_sftp_handle, ptr, nread);
    
                    ptr += rc;
                    nread -= nread;
                }while(rc >= 0);
                if(rc != LIBSSH2_ERROR_EAGAIN){
                    break;
                }
    
                timeout.tv_sec = 10;
                timeout.tv_usec = 0;
    
                FD_ZERO(&fd);
                FD_SET(m_socket,&fd);
    
                rc = select(m_socket+1,&fd,&fd,NULL,&timeout);
                if(rc <= 0){
                    qDebug() << "SFTP up;oad timed out: %d\n" << rc ;
                    break;
                }
            }while(1);
            qDebug() << "SFTP upload done!\n";
        }
        else {
            qDebug() << "SFTP failed to open destination path: %s\n";
        }
        libssh2_sftp_shutdown(m_sftp_session);
        shutDown();
        libssh2_session_disconnect(m_session, "Normal Shutdown, Thank you for playing");
        libssh2_session_free(m_session);
    }
    
    
    
    void SftpManager::initConnectionInfo()
    
    {
        QDomDocument doc;
        QFile file("config/sftp.xml");
        if(!file.open(QIODevice::ReadOnly)){
            return;
        }
        //read file in doc
        if(!doc.setContent(&file)){
            file.close();
            return;
        }
        //close file
        file.close();
        //root element
        QDomElement docElement = doc.documentElement();
        QDomNodeList nodeList = docElement.elementsByTagName("server");
        for(int i = 0; i != nodeList.size(); ++i){
            QDomNode node = nodeList.at(i);
            if(!node.isNull()){
                if(node.isElement()){
                    QDomElement e = node.toElement();
                    QDomNodeList ipList = e.elementsByTagName("ipAddress");
                    QString ipAddress = ipList.at(0).toElement().text();
                    m_ipAddress = ipAddress.toStdString();
                    QDomNodeList portList = e.elementsByTagName("port");
                    int port = portList.at(0).toElement().text().toInt();
                    m_port = port;
                    QDomNodeList usernameList = e.elementsByTagName("username");
                    QString username = usernameList.at(0).toElement().text();
                    m_username = username.toStdString();
                    QDomNodeList passwordList = e.elementsByTagName("password");
                    QString password = passwordList.at(0).toElement().text();
                    m_password = password.toStdString();
                }
            }
        }
    }
    
    void SftpManager::shutDown()
    {
        libssh2_session_disconnect(m_session, "Normal Shutdown, Thank you for playing");
        libssh2_session_free(m_session);
    
    #ifdef WIN32
        closesocket(m_socket);
    #else
        close(m_socket);
    #endif
        fprintf(stderr, "all done\n");
    
        libssh2_exit();
    
    }
    std::string SftpManager::ipAddress()
    {
        if(m_ipAddress == ""){
            //initConnectionInfo();
            m_ipAddress = "192.168.0.124";
        }
        return m_ipAddress;
    }
    
    int SftpManager::port()
    {
        if(m_port < 1){
            //initConnectionInfo();
            m_port = 22;
        }
        return m_port;
    }
    
    std::string SftpManager::username()
    {
        if(m_username == ""){
            //initConnectionInfo();
            m_username = "loohos-01";
        }
        return m_username;
    }
    
    std::string SftpManager::password()
    {
        if(m_password == ""){
            //initConnectionInfo();
            m_password = "liuhe1688";
        }
        return m_password;
    }
    
    

    使用部分:

    void TestDialogForm::on_pushButton_5_clicked()
    {
        SftpManager sftp;
        std::string ip = "192.168.0.124";
        std::string username = "loohos-01";
        std::string password = "liuhe1688";
        int port = 22;
        /*  */
        if (!sftp.connect("")){
            qDebug() << QString("连接失败"); return;
        }
    
        if(!sftp.createSession()){
            qDebug() << QString("Create session failed.");
            return;
        }
    
        if (!sftp.login(username, password)){
            qDebug() << QString("登录失败"); return;
        }
    
        if (!sftp.mkdir())
        {
             qDebug() << QString("创建文件夹失败"); return;
        }
    }
    
    void TestDialogForm::on_pushButton_6_clicked()
    {
        SftpManager sftp;
        std::string ip = "192.168.0.124";
        std::string username = "loohos-01";
        std::string password = "liuhe1688";
        int port = 22;
        /*  */
        if (!sftp.connect("")){
            qDebug() << QString("连接失败"); return;
        }
    
        if(!sftp.createSession()){
            qDebug() << QString("Create session failed.");
            return;
        }
    
        if (!sftp.login(username, password)){
            qDebug() << QString("登录失败"); return;
        }
    
        if(!sftp.readAndWrite())
        {
             qDebug() << QString("读写失败"); return;
        }
    }
    

    总结:积极使用断点,分步了解协议架构,完成开发。

    展开全文
  • 基于SFTP下载指定文件

    2022-08-09 09:48:20
    python下载sftp文件

    Python实现SFTP的文件下载

    一、界面

    1、数据文件下载界面
    (1)GUI显示
    在这里插入图片描述
    (2)代码

    from PyQt5 import QtCore, QtGui, QtWidgets
    class Ui_Form(object):
        def setupUi(self, Form):
            Form.setObjectName("Form")
            Form.resize(600, 600)
            sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth())
            Form.setSizePolicy(sizePolicy)
            Form.setMouseTracking(True)
            icon = QtGui.QIcon()
            icon.addPixmap(QtGui.QPixmap(":/re/icon.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.On)
            Form.setWindowIcon(icon)
            Form.setAutoFillBackground(False)
            Form.setStyleSheet("background-image: url(:/back/2.jpeg);")
            self.label_4 = QtWidgets.QLabel(Form)
            self.label_4.setGeometry(QtCore.QRect(337, 450, 75, 24))
            self.label_4.setStyleSheet("font: 10pt \"黑体\";\n"
    "color: rgb(85, 0, 0);")
            self.label_4.setObjectName("label_4")
            self.label_7 = QtWidgets.QLabel(Form)
            self.label_7.setGeometry(QtCore.QRect(50, 450, 75, 24))
            self.label_7.setStyleSheet("font: 10pt \"黑体\";\n"
    "color: rgb(85, 0, 0);")
            self.label_7.setObjectName("label_7")
            self.label_3 = QtWidgets.QLabel(Form)
            self.label_3.setGeometry(QtCore.QRect(140, 90, 331, 61))
            sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.label_3.sizePolicy().hasHeightForWidth())
            self.label_3.setSizePolicy(sizePolicy)
            self.label_3.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.label_3.setStyleSheet("background-image: url(:/text/1.jpeg);")
            self.label_3.setTextFormat(QtCore.Qt.AutoText)
            self.label_3.setObjectName("label_3")
            self.pushButton = QtWidgets.QPushButton(Form)
            self.pushButton.setGeometry(QtCore.QRect(100, 200, 171, 41))
            self.pushButton.setMouseTracking(False)
            self.pushButton.setFocusPolicy(QtCore.Qt.WheelFocus)
            self.pushButton.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.pushButton.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.pushButton.setAutoFillBackground(False)
            self.pushButton.setStyleSheet("color: rgb(85, 0, 0);\n"
    "font: 14pt \"黑体\";\n"
    "background-image: url(:/text/1.jpeg);")
            icon1 = QtGui.QIcon()
            icon1.addPixmap(QtGui.QPixmap(":/down/IST_18279_33769.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
            self.pushButton.setIcon(icon1)
            self.pushButton.setIconSize(QtCore.QSize(65, 65))
            self.pushButton.setCheckable(False)
            self.pushButton.setAutoRepeatDelay(300)
            self.pushButton.setObjectName("pushButton")
            self.toolButton_2 = QtWidgets.QToolButton(Form)
            self.toolButton_2.setGeometry(QtCore.QRect(70, 0, 71, 21))
            self.toolButton_2.setStyleSheet("background-image: url(:/text/1.jpeg);")
            self.toolButton_2.setObjectName("toolButton_2")
            self.toolButton = QtWidgets.QToolButton(Form)
            self.toolButton.setGeometry(QtCore.QRect(0, 0, 71, 21))
            self.toolButton.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
            self.toolButton.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.toolButton.setStyleSheet("background-image: url(:/text/1.jpeg);")
            self.toolButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)
            self.toolButton.setObjectName("toolButton")
            self.pushButton_2 = QtWidgets.QPushButton(Form)
            self.pushButton_2.setGeometry(QtCore.QRect(370, 200, 171, 41))
            self.pushButton_2.setMouseTracking(False)
            self.pushButton_2.setFocusPolicy(QtCore.Qt.WheelFocus)
            self.pushButton_2.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.pushButton_2.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.pushButton_2.setAutoFillBackground(False)
            self.pushButton_2.setStyleSheet("color: rgb(85, 0, 0);\n"
    "font: 14pt \"黑体\";\n"
    "background-image: url(:/text/1.jpeg);")
            self.pushButton_2.setIcon(icon1)
            self.pushButton_2.setIconSize(QtCore.QSize(65, 65))
            self.pushButton_2.setCheckable(False)
            self.pushButton_2.setAutoRepeatDelay(300)
            self.pushButton_2.setObjectName("pushButton_2")
            self.pushButton_3 = QtWidgets.QPushButton(Form)
            self.pushButton_3.setGeometry(QtCore.QRect(220, 280, 171, 41))
            self.pushButton_3.setMouseTracking(False)
            self.pushButton_3.setFocusPolicy(QtCore.Qt.WheelFocus)
            self.pushButton_3.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.pushButton_3.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.pushButton_3.setAutoFillBackground(False)
            self.pushButton_3.setStyleSheet("color: rgb(85, 0, 0);\n"
    "font: 14pt \"黑体\";\n"
    "background-image: url(:/text/1.jpeg);")
            self.pushButton_3.setIcon(icon1)
            self.pushButton_3.setIconSize(QtCore.QSize(65, 65))
            self.pushButton_3.setCheckable(False)
            self.pushButton_3.setAutoRepeatDelay(300)
            self.pushButton_3.setObjectName("pushButton_3")
            self.dateEdit = QtWidgets.QDateEdit(Form)
            self.dateEdit.setGeometry(QtCore.QRect(134, 440, 110, 41))
            self.dateEdit.setCalendarPopup(True)
            self.dateEdit.setObjectName("dateEdit")
            self.dateEdit_2 = QtWidgets.QDateEdit(Form)
            self.dateEdit_2.setGeometry(QtCore.QRect(424, 440, 110, 41))
            self.dateEdit_2.setCalendarPopup(True)
            self.dateEdit_2.setObjectName("dateEdit_2")
            self.toolButton_3 = QtWidgets.QToolButton(Form)
            self.toolButton_3.setGeometry(QtCore.QRect(140, 0, 111, 21))
            self.toolButton_3.setStyleSheet("background-image: url(:/text/1.jpeg);")
            self.toolButton_3.setObjectName("toolButton_3")
            self.pushButton_4 = QtWidgets.QPushButton(Form)
            self.pushButton_4.setGeometry(QtCore.QRect(100, 360, 171, 41))
            self.pushButton_4.setMouseTracking(False)
            self.pushButton_4.setFocusPolicy(QtCore.Qt.WheelFocus)
            self.pushButton_4.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.pushButton_4.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.pushButton_4.setAutoFillBackground(False)
            self.pushButton_4.setStyleSheet("color: rgb(85, 0, 0);\n"
    "font: 14pt \"黑体\";\n"
    "background-image: url(:/text/1.jpeg);")
            self.pushButton_4.setIcon(icon1)
            self.pushButton_4.setIconSize(QtCore.QSize(65, 65))
            self.pushButton_4.setCheckable(False)
            self.pushButton_4.setAutoRepeatDelay(300)
            self.pushButton_4.setObjectName("pushButton_4")
            self.pushButton_5 = QtWidgets.QPushButton(Form)
            self.pushButton_5.setGeometry(QtCore.QRect(370, 360, 171, 41))
            self.pushButton_5.setMouseTracking(False)
            self.pushButton_5.setFocusPolicy(QtCore.Qt.WheelFocus)
            self.pushButton_5.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.pushButton_5.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.pushButton_5.setAutoFillBackground(False)
            self.pushButton_5.setStyleSheet("color: rgb(85, 0, 0);\n"
    "font: 14pt \"黑体\";\n"
    "background-image: url(:/text/1.jpeg);")
            self.pushButton_5.setIcon(icon1)
            self.pushButton_5.setIconSize(QtCore.QSize(65, 65))
            self.pushButton_5.setCheckable(False)
            self.pushButton_5.setAutoRepeatDelay(300)
            self.pushButton_5.setObjectName("pushButton_5")
    
            self.retranslateUi(Form)
            QtCore.QMetaObject.connectSlotsByName(Form)
    
        def retranslateUi(self, Form):
            _translate = QtCore.QCoreApplication.translate
            Form.setWindowTitle(_translate("Form", "文件下载系统"))
            self.label_4.setText(_translate("Form", "结束时间"))
            self.label_7.setText(_translate("Form", "开始时间"))
            self.label_3.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:14pt; font-weight:600; color:#550000;\">欢迎进入数据下载界面</span></p></body></html>"))
            self.pushButton.setText(_translate("Form", "月报一批"))
            self.toolButton_2.setText(_translate("Form", "注意事项"))
            self.toolButton.setText(_translate("Form", "功能介绍"))
            self.pushButton_2.setText(_translate("Form", "月报二批"))
            self.pushButton_3.setText(_translate("Form", "日报下载"))
            self.dateEdit.setDisplayFormat(_translate("Form", "yyyy-MM-dd"))
            self.dateEdit_2.setDisplayFormat(_translate("Form", "yyyy-MM-dd"))
            self.toolButton_3.setText(_translate("Form", "异动说明下载"))
            self.pushButton_4.setText(_translate("Form", "季报一批"))
            self.pushButton_5.setText(_translate("Form", "季报二批"))
    import back_rc
    import download_rc
    import pwd_rc
    import re_rc
    import text_rc
    import unzip_rc
    

    2、异动说明下载界面
    (1)GUI显示
    在这里插入图片描述
    (2)代码

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    
    class Ui_Form(object):
        def setupUi(self, Form):
            Form.setObjectName("Form")
            Form.resize(600, 600)
            sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth())
            Form.setSizePolicy(sizePolicy)
            Form.setMouseTracking(True)
            icon = QtGui.QIcon()
            icon.addPixmap(QtGui.QPixmap(":/re/icon.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.On)
            Form.setWindowIcon(icon)
            Form.setAutoFillBackground(False)
            Form.setStyleSheet("background-image: url(:/back/2.jpeg);")
            self.label_4 = QtWidgets.QLabel(Form)
            self.label_4.setGeometry(QtCore.QRect(303, 400, 75, 24))
            self.label_4.setStyleSheet("font: 10pt \"黑体\";\n"
    "color: rgb(85, 0, 0);")
            self.label_4.setObjectName("label_4")
            self.label_7 = QtWidgets.QLabel(Form)
            self.label_7.setGeometry(QtCore.QRect(16, 400, 75, 24))
            self.label_7.setStyleSheet("font: 10pt \"黑体\";\n"
    "color: rgb(85, 0, 0);")
            self.label_7.setObjectName("label_7")
            self.label_3 = QtWidgets.QLabel(Form)
            self.label_3.setGeometry(QtCore.QRect(140, 90, 331, 61))
            sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.label_3.sizePolicy().hasHeightForWidth())
            self.label_3.setSizePolicy(sizePolicy)
            self.label_3.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.label_3.setStyleSheet("background-image: url(:/text/1.jpeg);")
            self.label_3.setTextFormat(QtCore.Qt.AutoText)
            self.label_3.setObjectName("label_3")
            self.pushButton = QtWidgets.QPushButton(Form)
            self.pushButton.setGeometry(QtCore.QRect(100, 220, 171, 41))
            self.pushButton.setMouseTracking(False)
            self.pushButton.setFocusPolicy(QtCore.Qt.WheelFocus)
            self.pushButton.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.pushButton.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.pushButton.setAutoFillBackground(False)
            self.pushButton.setStyleSheet("color: rgb(85, 0, 0);\n"
    "font: 14pt \"黑体\";\n"
    "background-image: url(:/text/1.jpeg);")
            icon1 = QtGui.QIcon()
            icon1.addPixmap(QtGui.QPixmap(":/down/IST_18279_33769.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
            self.pushButton.setIcon(icon1)
            self.pushButton.setIconSize(QtCore.QSize(65, 65))
            self.pushButton.setCheckable(False)
            self.pushButton.setAutoRepeatDelay(300)
            self.pushButton.setObjectName("pushButton")
            self.toolButton = QtWidgets.QToolButton(Form)
            self.toolButton.setGeometry(QtCore.QRect(0, 0, 71, 21))
            self.toolButton.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
            self.toolButton.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.toolButton.setStyleSheet("background-image: url(:/text/1.jpeg);")
            self.toolButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)
            self.toolButton.setObjectName("toolButton")
            self.pushButton_2 = QtWidgets.QPushButton(Form)
            self.pushButton_2.setGeometry(QtCore.QRect(370, 220, 171, 41))
            self.pushButton_2.setMouseTracking(False)
            self.pushButton_2.setFocusPolicy(QtCore.Qt.WheelFocus)
            self.pushButton_2.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.pushButton_2.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.pushButton_2.setAutoFillBackground(False)
            self.pushButton_2.setStyleSheet("color: rgb(85, 0, 0);\n"
    "font: 14pt \"黑体\";\n"
    "background-image: url(:/text/1.jpeg);")
            self.pushButton_2.setIcon(icon1)
            self.pushButton_2.setIconSize(QtCore.QSize(65, 65))
            self.pushButton_2.setCheckable(False)
            self.pushButton_2.setAutoRepeatDelay(300)
            self.pushButton_2.setObjectName("pushButton_2")
            self.pushButton_3 = QtWidgets.QPushButton(Form)
            self.pushButton_3.setGeometry(QtCore.QRect(100, 300, 171, 41))
            self.pushButton_3.setMouseTracking(False)
            self.pushButton_3.setFocusPolicy(QtCore.Qt.WheelFocus)
            self.pushButton_3.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.pushButton_3.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.pushButton_3.setAutoFillBackground(False)
            self.pushButton_3.setStyleSheet("color: rgb(85, 0, 0);\n"
    "font: 14pt \"黑体\";\n"
    "background-image: url(:/text/1.jpeg);")
            self.pushButton_3.setIcon(icon1)
            self.pushButton_3.setIconSize(QtCore.QSize(65, 65))
            self.pushButton_3.setCheckable(False)
            self.pushButton_3.setAutoRepeatDelay(300)
            self.pushButton_3.setObjectName("pushButton_3")
            self.dateEdit = QtWidgets.QDateEdit(Form)
            self.dateEdit.setGeometry(QtCore.QRect(100, 390, 110, 41))
            self.dateEdit.setCalendarPopup(True)
            self.dateEdit.setObjectName("dateEdit")
            self.dateEdit_2 = QtWidgets.QDateEdit(Form)
            self.dateEdit_2.setGeometry(QtCore.QRect(390, 390, 110, 41))
            self.dateEdit_2.setCalendarPopup(True)
            self.dateEdit_2.setObjectName("dateEdit_2")
            self.pushButton_4 = QtWidgets.QPushButton(Form)
            self.pushButton_4.setGeometry(QtCore.QRect(370, 300, 171, 41))
            self.pushButton_4.setMouseTracking(False)
            self.pushButton_4.setFocusPolicy(QtCore.Qt.WheelFocus)
            self.pushButton_4.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.pushButton_4.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.pushButton_4.setAutoFillBackground(False)
            self.pushButton_4.setStyleSheet("color: rgb(85, 0, 0);\n"
    "font: 14pt \"黑体\";\n"
    "background-image: url(:/text/1.jpeg);")
            self.pushButton_4.setIcon(icon1)
            self.pushButton_4.setIconSize(QtCore.QSize(65, 65))
            self.pushButton_4.setCheckable(False)
            self.pushButton_4.setAutoRepeatDelay(300)
            self.pushButton_4.setObjectName("pushButton_4")
    
            self.retranslateUi(Form)
            QtCore.QMetaObject.connectSlotsByName(Form)
    
        def retranslateUi(self, Form):
            _translate = QtCore.QCoreApplication.translate
            Form.setWindowTitle(_translate("Form", "文件下载系统"))
            self.label_4.setText(_translate("Form", "结束时间"))
            self.label_7.setText(_translate("Form", "开始时间"))
            self.label_3.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:14pt; font-weight:600; color:#550000;\">欢迎进入异动说明下载界面</span></p></body></html>"))
            self.pushButton.setText(_translate("Form", "月报一批"))
            self.toolButton.setText(_translate("Form", "返回"))
            self.pushButton_2.setText(_translate("Form", "月报二批"))
            self.pushButton_3.setText(_translate("Form", "季报一批"))
            self.dateEdit.setDisplayFormat(_translate("Form", "yyyy-MM-dd"))
            self.dateEdit_2.setDisplayFormat(_translate("Form", "yyyy-MM-dd"))
            self.pushButton_4.setText(_translate("Form", "季报二批"))
    import back_rc
    import download_rc
    import pwd_rc
    import re_rc
    import text_rc
    import unzip_rc
    

    2、界面入口及跳转实现
    数据文件下载界面与异动说明下载界面,通过按钮可以互相跳转

    from PyQt5.QtCore import QDate
    from Sftp_Load import Sftp_Load
    import ftp as fw
    import sys
    from PyQt5 import QtWidgets as qw, QtGui
    from System_Instruction import SystemInstruction
    import explain as ex
    # 数据下载界面窗口
    class FtpUi(qw.QMainWindow):
        def __init__(self):
            super(FtpUi, self).__init__()
            self.ui = fw.Ui_Form()
            self.setWindowTitle("SFTP文件下载系统")
            self.setWindowIcon(QtGui.QIcon(':/re/icon.jpg'))
            self.ftpdownload_functions = Sftp_Load(self.ui, self)
            self.systemInstruction = SystemInstruction(self.ui, self)
            # 调用Ui_setup方法动态创建控件
            self.ui.setupUi(self)
            self.ui.dateEdit.setDate(QDate.currentDate())
            self.ui.dateEdit_2.setDate(QDate.currentDate())
            # 注意事项  self.ui.toolButton_2.clicked.connect(self.systemInstruction.notice)
            # 系统介绍
    self.ui.toolButton.clicked.connect(self.systemInstruction.system_instruct)
            # 月报一批次
    self.ui.pushButton.clicked.connect(self.ftpdownload_functions.download1)
            # 月报二批次
    self.ui.pushButton_2.clicked.connect(self.ftpdownload_functions.download2)
            # 日报     self.ui.pushButton_3.clicked.connect(self.ftpdownload_functions.download)
            # 季报一批次     self.ui.pushButton_4.clicked.connect(self.ftpdownload_functions.quater_entrance)
            # 季报二批次  self.ui.pushButton_5.clicked.connect(self.ftpdownload_functions.quater1_entrance)
    # 异动说明下载界面窗口
    class ExplainUi(qw.QMainWindow):
        def __init__(self):
            super(ExplainUi, self).__init__()
            self.ui = ex.Ui_Form()
            # self.setWindowTitle("SFTP文件下载系统")
            self.setWindowIcon(QtGui.QIcon(':/re/icon.jpg'))
            # 调用Ui_setup方法动态创建控件
            self.ui.setupUi(self)
            self.ui.dateEdit.setDate(QDate.currentDate())
            self.ui.dateEdit_2.setDate(QDate.currentDate())
            self.ftpdownload_functions = Sftp_Load(self.ui, self)
            # 月报一批次异动说明      self.ui.pushButton.clicked.connect(self.ftpdownload_functions.monex_entrance)
            # 月报二批次异动说明 self.ui.pushButton_2.clicked.connect(self.ftpdownload_functions.monex1_download)
            # 季报一批次异动说明      self.ui.pushButton_3.clicked.connect(self.ftpdownload_functions.qtrex_download)
            # 季报二批次异动说明 self.ui.pushButton_4.clicked.connect(self.ftpdownload_functions.qtrex1_download)
        def back(self):
            self.close()
    if __name__ == '__main__':
        app = qw.QApplication(sys.argv)
        a = FtpUi()
        b = ExplainUi()
        a.show()
        a.ui.toolButton_3.clicked.connect(b.show)
        a.ui.toolButton_3.clicked.connect(a.close)
        b.ui.toolButton.clicked.connect(a.show)
        b.ui.toolButton.clicked.connect(b.close)
        sys.exit(app.exec_())
    

    二、下载功能

    1、SFTP服务器搭建
    参考上篇文章Centos7搭建sftp服务,window上filezilla连接
    2、连接服务器
    在这里插入图片描述
    3、下载功能代码

    # 从sftp服务器批量下载指定的文件
    import re
    import shutil
    import logging
    import traceback
    import easygui
    import paramiko
    import os
    from PyQt5.QtCore import Qt
    import datetime
    from datetime import timedelta
    
    dic = {}
    dic1 = {}
    dic2 = {}
    dic_month1 = {}
    dic_month2 = {}
    rule = re.compile('^[A-Z]{1}.*$')
    now = datetime.datetime.now().date()
    # 获取上月的最后一天
    last_month_end = datetime.date(now.year, now.month, 1) - timedelta(days=1)
    last_month_end1 = str(last_month_end).replace('-', '')
    # 获取上季的最后一天
    month = (now.month - 1) - (now.month - 1) % 3 + 1
    last_quarter_end = datetime.date(now.year, month, 1) - timedelta(days=1)
    last_quarter_end1 = str(last_quarter_end).replace('-', '')
    if int((last_quarter_end.month - 1) / 3) == 0:
        quater = '一'
    # 456月
    elif int((last_quarter_end.month - 1) / 3) == 1:
        quater = '二'
    # 789月
    elif int((last_quarter_end.month - 1) / 3) == 2:
        quater = '三'
    # 10 11 12月
    elif int((last_quarter_end.month - 1) / 3) == 3:
        quater = '四'
    # 将服务器的IP地址,端口号,用户和密码存储在文本中,便于更改,只允许更改冒号后面的内容
    with open('ftp_info.txt', 'r', encoding='utf-8') as f:
        for line in f:
            key, value = line.strip().split(':')
            dic[key] = value
    # 将本地存储路径与远程下载路径存储在文本中,便于更改,只允许更改逗号后面的内容
    with open('download_location.txt', 'r', encoding='utf-8') as f:
        for line in f:
            key1, value1 = line.strip().split(',')
            dic1[key1] = value1
    # 日报机构信息
    with open('日报机构信息.txt', 'r', encoding='utf-8') as f:
        for line in f:
            key2, value2 = line.strip().split(':')
            dic2[key2] = value2
    # 月报一批次机构信息
    with open('季报、月报一批次机构信息.txt', 'r', encoding='utf-8') as f:
        for line in f:
            key2, value2 = line.strip().split(':')
            dic_month1[key2] = value2
    
    # 月报二批次机构信息
    
    with open('季报、月报二批次机构信息.txt', 'r', encoding='utf-8') as f:
        for line in f:
            key2, value2 = line.strip().split(':')
            dic_month2[key2] = value2
    
    sftp_ip = dic['IP地址']  # sftp ip
    port = int(dic['port端口号'])  # sftp端口
    username = dic['user']  # sftp用户名
    password = dic['password']  # sftp密码
    local = dic1['本地存储路径']  # 存储路径
    remote = dic1['远程ftp下载路径']  # 目标文件所在路径
    
    
    # 创建本地目录功能
    def mkdir(path):
        location = os.path.join(local + path)
        if os.path.exists(location):
            shutil.rmtree(location)
            os.makedirs(location)
        else:
            os.makedirs(location)
        location = location + '/'
        return location
    
    
    # 连接服务器!
    sf = paramiko.Transport((sftp_ip, port))
    sf.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(sf)
    easygui.msgbox("------------已经与服务器建立连接!------------!", title="提示")
    # print('------------已经与服务器建立连接!------------')
    logging.basicConfig(filename='log_record.txt', level=logging.DEBUG, filemode='w',
                        format='[日志时间:%(asctime)s] [日志级别数值:%(levelname)s] [当前执行函数:%(funcName)s] [日志的当前行号:%('
                               'lineno)s] >>> 日志信息:%(message)s',
                        datefmt='%Y-%m-%d %I:%M:%S')
    
    
    class Sftp_Load():
        def __init__(self, ui, MainWindow):
            self.ui = ui
            self.MainWindow = MainWindow
    
        # -------------------------------------------------日报数据文件下载开始---------------------------------
        # 日报下载的入口函数
        def download(self):
            # 创建日报目录
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            path = '日报' + '711' + '-' + begin_time
            location_day = mkdir(path)
            self.day_download(location_day, sftp, remote)
            easygui.msgbox("------------日报下载完成!------------!", title="提示")
            # print('---日报下载完成!---')
            self.file_count(location_day)
    
        # 日报下载功能
        def day_download(self, location_day, sftp, remote):
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            time_s = self.ui.dateEdit_2.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            end_time = re.sub('[-]', '', time_s)
            try:
                for file in sftp.listdir(remote):
                    if file.find('.') == -1:
                        remotes = os.path.join(remote, file) + '/'
                        self.day_download(location_day, sftp, remotes)
                    else:
                        if rule.match(file) and file.endswith('zip') and file[-7:-4] == '711' and int(begin_time) <= int(
                                file[-15:-7]) <= int(
                            end_time):
                            sftp.get(os.path.join(remote + file), os.path.join(location_day + file))
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
                easygui.msgbox("日报下载错误,请查看日志详细错误信息!", title="提示")
    
        # 日报是否全部下载的判断
        def file_count(self, path):
            lst = []
            lst1 = []
            count = 0
            for exist_file in os.listdir(path):
                count = count + 1
                lst1.append(exist_file[2:6])
            if count == len(dic2):
                easygui.msgbox("九家机构日报全部下载!!", title="提示")
            elif count == 0:
                easygui.msgbox("机构都未上传文件!", title="提示")
            else:
                for keys in dic2.keys():
                    if keys not in lst1:
                        lst.append(dic2[keys])
                for file_value in lst:
                    print('{}家没有下载,{}未上传文件,请检查!'.format(len(dic2) - count, file_value))
                    # easygui.msgbox("下载了{}家,{}未上传文件,请检查!".format(count,file_value), title="提示")
    
            # 季报、月报一批次是否全部下载的判断
    
        def month1_file_count(self, path):
            lst = []
            lst1 = []
            count = 0
            for exist_file in os.listdir(path):
                count = count + 1
                lst1.append(exist_file[2:6])
            if count == len(dic_month1):
                easygui.msgbox("十四家机构全部下载!", title="提示")
            elif count == 0:
                easygui.msgbox("机构都未上传文件!", title="提示")
            else:
                for keys in dic_month1.keys():
                    if keys not in lst1:
                        lst.append(dic_month1[keys])
                for file_value in lst:
                    print('{}家没有下载,{}未上传文件,请检查!'.format(len(dic_month1) - count, file_value))
    
            # 季报、月报二批次是否全部下载的判断
    
        def month2_file_count(self, path):
            lst = []
            lst1 = []
            count = 0
            for exist_file in os.listdir(path):
                count = count + 1
                lst1.append(exist_file[2:6])
            if count == len(dic_month2):
                easygui.msgbox("十二家机构全部下载!", title="提示")
            elif count == 0:
                easygui.msgbox("机构都未上传文件!", title="提示")
            else:
                for keys in dic_month2.keys():
                    if keys not in lst1:
                        lst.append(dic_month2[keys])
                for file_value in lst:
                    print('{}家没有下载,{}未上传文件,请检查!'.format(len(dic_month2) - count, file_value))
    
        # 月报一批次数据文件入口函数
        def download1(self):
            # 创建月报一批次目录
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            path = '月报一批次' + '411' + '-' + begin_time[4:6] + '数据文件'
            location_month = mkdir(path)
            self.month1_download(location_month, sftp, remote)
            # sf.close()
            easygui.msgbox("---月报一批次下载完成!---", title="提示")
            self.month1_file_count(location_month)
    
        # 月报一批次数据文件下载
        def month1_download(self, location_month, sftp, remote):
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            time_s = self.ui.dateEdit_2.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            end_time = re.sub('[-]', '', time_s)
            try:
                for file in sftp.listdir(remote):
                    if file.find('.') == -1:
                        remotes = os.path.join(remote, file) + '/'
                        self.month1_download(location_month, sftp, remotes)
                    else:
                        if rule.match(file) and file.endswith('zip') and file[-7:-4] == '411' and int(begin_time) <= int(
                                file[-15:-7]) <= int(end_time):
                            sftp.get(os.path.join(remote + file), os.path.join(location_month + file))
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
                easygui.msgbox("月报一批次下载错误,请查看日志详细错误信息!", title="提示")
    
        # 月报二批次数据文件函数入口
        def download2(self):
            # 创建月报二批次目录
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            path = '月报二批次' + '421' + '-' + begin_time[4:6] + '数据文件'
            location_month1 = mkdir(path)
            self.month2_download(location_month1, sftp, remote)
            easygui.msgbox("---月报二批次下载完成!---", title="提示")
            self.month2_file_count(location_month1)
    
        # 月报二批次数据文件下载
        def month2_download(self, location_month1, sftp, remote):
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            time_s = self.ui.dateEdit_2.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            end_time = re.sub('[-]', '', time_s)
            try:
                for file in sftp.listdir(remote):
                    if file.find('.') == -1:
                        remotes = os.path.join(remote, file) + '/'
                        self.month2_download(location_month1, sftp, remotes)
                    else:
                        if rule.match(file) and file.endswith('zip') and file[-7:-4] == '421' and int(begin_time) <= int(
                                file[-15:-7]) <= int(end_time):
                            sftp.get(os.path.join(remote + file), os.path.join(location_month1 + file))
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
                easygui.msgbox("月报二批次下载错误,请查看日志详细错误信息!", title="提示")
    
        # ------------------------------------------------季报一批次数据文件下载开始-----------------------------------------
        # 季报一批次数据文件入口函数
        def quater_entrance(self):
            # 创建季报一批次目录
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            path = '季报一批次' + '311' + '-' + begin_time[4:6] + '数据文件'
            location_quater = mkdir(path)
            self.quater1_download(location_quater, sftp, remote)
            # sf.close()
            easygui.msgbox("---季报一批次下载完成!---", title="提示")
            self.month1_file_count(location_quater)
    
        # 季报一批次数据文件下载
        def quater1_download(self, location_auqter, sftp, remote):
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            time_s = self.ui.dateEdit_2.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            end_time = re.sub('[-]', '', time_s)
            try:
                for file in sftp.listdir(remote):
                    if file.find('.') == -1:
                        remotes = os.path.join(remote, file) + '/'
                        self.quater1_download(location_auqter, sftp, remotes)
                    else:
                        if rule.match(file) and file.endswith('zip') and file[-7:-4] == '311' and int(begin_time) <= int(
                                file[-15:-7]) <= int(end_time):
                            sftp.get(os.path.join(remote + file), os.path.join(location_auqter + file))
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
                easygui.msgbox("季报一批次下载错误,请查看日志详细错误信息!", title="提示")
    
        # ------------------------------------------------季报一批次数据文件下载结束-----------------------------------------
    
        # ------------------------------------------------季报二批次数据文件下载开始-----------------------------------------
        # 季报二批次数据文件入口函数
        def quater1_entrance(self):
            # 创建季报二批次目录
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            path = '季报二批次' + '321' + '-' + begin_time[4:6] + '数据文件'
            location_quater = mkdir(path)
            self.quater2_download(location_quater, sftp, remote)
            # sf.close()
            easygui.msgbox("---季报二批次下载完成!---", title="提示")
            self.month2_file_count(location_quater)
    
        # 季报二批次数据文件下载
        def quater2_download(self, location_auqter, sftp, remote):
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            time_s = self.ui.dateEdit_2.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            end_time = re.sub('[-]', '', time_s)
            try:
                for file in sftp.listdir(remote):
                    if file.find('.') == -1:
                        remotes = os.path.join(remote, file) + '/'
                        self.quater2_download(location_auqter, sftp, remotes)
                    else:
                        if rule.match(file) and file.endswith('zip') and file[-7:-4] == '321' and int(begin_time) <= int(
                                file[-15:-7]) <= int(end_time):
                            sftp.get(os.path.join(remote + file), os.path.join(location_auqter + file))
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
                easygui.msgbox("季报二批次下载错误,请查看日志详细错误信息!", title="提示")
    
        # ------------------------------------------------季报二批次数据文件下载结束-----------------------------------------
    
        # -----------------------------------------------月报一批次异动说明程序开始--------------------------------------
        # 月报一批次异动说明文件个数判断
        def monex_file_count(self, path):
            lst = []
            lst1 = []
            count = 0
            for exist_file in os.listdir(path):
                count = count + 1
                lst1.append(exist_file[0:4])
            if count == len(dic_month1):
                easygui.msgbox("十四家机构全部下载!", title="提示")
            elif count == 0:
                easygui.msgbox("机构都未上传文件!", title="提示")
            else:
                for keys in dic_month1.keys():
                    if keys not in lst1:
                        lst.append(dic_month1[keys])
                for file_value in lst:
                    print('{}家没有下载,{}未上传文件,请检查!'.format(len(dic_month1) - count, file_value))
    
        # 月报一批次异动说明下载入口
        def monex_entrance(self):
            # 创建月报一批次异动说明目录
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            path = '月报一批次' + '411' + '-' + begin_time[4:6] + '异动说明'
            location_day = mkdir(path)
            self.monex_download(location_day, sftp, remote)
            easygui.msgbox("------------月报一批次异动说明下载完成!------------!", title="提示")
            self.monex_file_count(location_day)
    
        # 月报一批次异动说明下载功能
        def monex_download(self, location_day, sftp, remote):
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            time_s = self.ui.dateEdit_2.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            end_time = re.sub('[-]', '', time_s)
            try:
                for file in sftp.listdir(remote):
                    if file.find('.') == -1:
                        remotes = os.path.join(remote, file) + '/'
                        self.monex_download(location_day, sftp, remotes)
                    else:
                        index = file.find(last_month_end1)
                        name = str(last_month_end.month) + '月月报一批次'
                        if file[0:4] in dic_month1.keys() and file.find(name) != -1 and index != -1 and (
                                file.endswith('xlsx') or file.endswith('xls')) and int(
                            begin_time) <= int(
                            file[index:index + 8]) <= int(
                            end_time):
                            sftp.get(os.path.join(remote + file), os.path.join(location_day + file))
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
                easygui.msgbox("月报一批次异动说明下载错误,请查看日志详细错误信息!", title="提示")
    
        # -----------------------------------------------月报一批次异动说明程序结束--------------------------------------
    
        # -----------------------------------------------月报二批次异动说明程序开始--------------------------------------
        # 月报二批次异动说明文件个数判断
        def monex1_file_count(self, path):
            lst = []
            lst1 = []
            count = 0
            for exist_file in os.listdir(path):
                count = count + 1
                lst1.append(exist_file[0:4])
            if count == len(dic_month2):
                easygui.msgbox("十二家机构全部下载!", title="提示")
            elif count == 0:
                easygui.msgbox("机构都未上传文件!", title="提示")
            else:
                for keys in dic_month2.keys():
                    if keys not in lst1:
                        lst.append(dic_month2[keys])
                for file_value in lst:
                    print('{}家没有下载,{}未上传文件,请检查!'.format(len(dic_month2) - count, file_value))
    
        # 月报二批次异动说明下载入口
        def monex1_download(self):
            # 创建月报一批次异动说明目录
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            path = '月报二批次' + '421' + '-' + begin_time[4:6] + '异动说明'
            location_day = mkdir(path)
            self.monex_download2(location_day, sftp, remote)
            easygui.msgbox("------------月报二批次异动说明下载完成!------------!", title="提示")
            self.monex1_file_count(location_day)
    
        # 月报二批次异动说明下载功能
        def monex_download2(self, location_day, sftp, remote):
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            time_s = self.ui.dateEdit_2.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            end_time = re.sub('[-]', '', time_s)
            try:
                for file in sftp.listdir(remote):
                    if file.find('.') == -1:
                        remotes = os.path.join(remote, file) + '/'
                        self.monex_download2(location_day, sftp, remotes)
                    else:
                        index = file.find(last_month_end1)
                        name = str(last_month_end.month) + '月月报二批次'
                        if file[0:4] in dic_month1.keys() and file.find(name) != -1 and index != -1 and (
                                file.endswith('xlsx') or file.endswith('xls')) and int(
                            begin_time) <= int(
                            file[index:index + 8]) <= int(
                            end_time):
                            sftp.get(os.path.join(remote + file), os.path.join(location_day + file))
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
                easygui.msgbox("月报二批次异动说明下载错误,请查看日志详细错误信息!", title="提示")
    
        # -----------------------------------------------季报一批次异动说明程序开始--------------------------------------
        # 季报一批次异动说明文件个数判断
        def quater_file_count(self, path):
            lst = []
            lst1 = []
            count = 0
            for exist_file in os.listdir(path):
                count = count + 1
                lst1.append(exist_file[0:4])
            if count == len(dic_month1):
                easygui.msgbox("十四家机构全部下载!", title="提示")
            elif count == 0:
                easygui.msgbox("机构都未上传文件!", title="提示")
            else:
                for keys in dic_month1.keys():
                    if keys not in lst1:
                        lst.append(dic_month1[keys])
                for file_value in lst:
                    print('{}家没有下载,{}未上传文件,请检查!'.format(len(dic_month1) - count, file_value))
    
        # 季报一批次异动说明下载入口
        def qtrex_download(self):
    
            # 创建季报一批次异动说明目录
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            path = '季报一批次' + '311' + '-' + begin_time[4:6] + '异动说明'
            location_day = mkdir(path)
            self.qtrex_download1(location_day, sftp, remote)
            easygui.msgbox("------------季报一批次异动说明下载完成!------------!", title="提示")
            self.quater_file_count(location_day)
    
        # 季报一批次异动说明下载功能
        def qtrex_download1(self, location_day, sftp, remote):
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            time_s = self.ui.dateEdit_2.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            end_time = re.sub('[-]', '', time_s)
            try:
                for file in sftp.listdir(remote):
                    if file.find('.') == -1:
                        remotes = os.path.join(remote, file) + '/'
                        self.qtrex_download1(location_day, sftp, remotes)
                    else:
                        index = file.find(last_quarter_end1)
                        name = quater + '季度季报一批次'
                        if file[0:4] in dic_month1.keys() and file.find(name) != -1 and index != -1 and (
                                file.endswith('xlsx') or file.endswith('xls')) and int(
                            begin_time) <= int(
                            file[index:index + 8]) <= int(
                            end_time):
                            sftp.get(os.path.join(remote + file), os.path.join(location_day + file))
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
                easygui.msgbox("季报一批次异动说明下载错误,请查看日志详细错误信息!", title="提示")
    
        # -----------------------------------------------季报一批次异动说明程序结束--------------------------------------
    
        # -----------------------------------------------季报二批次异动说明程序开始--------------------------------------
        # 月报二批次异动说明文件个数判断
        def qtrex1_file_count(self, path):
            lst = []
            lst1 = []
            count = 0
            for exist_file in os.listdir(path):
                count = count + 1
                lst1.append(exist_file[0:4])
            if count == len(dic_month2):
                easygui.msgbox("十二家机构全部下载!", title="提示")
            elif count == 0:
                easygui.msgbox("机构都未上传文件!", title="提示")
            else:
                for keys in dic_month2.keys():
                    if keys not in lst1:
                        lst.append(dic_month2[keys])
                for file_value in lst:
                    print('{}家没有下载,{}未上传文件,请检查!'.format(len(dic_month2) - count, file_value))
    
        # 季报二批次异动说明下载入口
        def qtrex1_download(self):
            # 创建季报二批次异动说明目录
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            path = '季报二批次' + '321' + '-' + begin_time[4:6] + '异动说明'
            location_day = mkdir(path)
            self.qtrex_download2(location_day, sftp, remote)
            easygui.msgbox("------------季报二批次异动说明下载完成!------------!", title="提示")
            self.qtrex1_file_count(location_day)
    
        # 月报二批次异动说明下载功能
        def qtrex_download2(self, location_day, sftp, remote):
            times = self.ui.dateEdit.date().toString(Qt.ISODate)
            time_s = self.ui.dateEdit_2.date().toString(Qt.ISODate)
            begin_time = re.sub('[-]', '', times)
            end_time = re.sub('[-]', '', time_s)
            try:
                for file in sftp.listdir(remote):
                    if file.find('.') == -1:
                        remotes = os.path.join(remote, file) + '/'
                        self.qtrex_download2(location_day, sftp, remotes)
                    else:
                        index = file.find(last_quarter_end1)
                        name = quater + '季度季报二批次'
                        if file[0:4] in dic_month1.keys() and file.find(name) != -1 and index != -1 and  (
                                file.endswith('xlsx') or file.endswith('xls')) and int(
                            begin_time) <= int(
                            file[index:index + 8]) <= int(
                            end_time):
                            sftp.get(os.path.join(remote + file), os.path.join(location_day + file))
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
                easygui.msgbox("季报二批次异动说明下载错误,请查看日志详细错误信息!", title="提示")
        # -----------------------------------------------季报二批次异动说明程序结束--------------------------------------
    

    三、代码工程目录

    在这里插入图片描述

    展开全文
  • linux下QT实现ftp客户端

    2012-04-23 21:32:55
    ftp-QT.tar.gz,main.cpp,ftp,ftp.debug,ftpwindow.cpp,images,cdtoparent.png,file.png,dir.png,ftpwindow.h,ftp.pro,ftp.qrc,Makefile
  • 实现SFTP的上传。支持创建多层目录。
  • QSsh:基于Qt的SSH和SFTP
  • QT+SFtp tool

    2018-08-13 17:38:15
    Qt平台下使用sftp协议实现远程主机的文件查询,目录查询,文件下载,目录下载,文件上传,目录上传
  • FTP是文件传输协议。在网站上,如果你想把文件和人共享,最便捷的方式莫过于把文件上传到FTP服务器上,其他人通过FTP客户端程序来下载所需要的文件。 FTP进行文件传输需要通过端口进行。一般所需端口为: ...
  • QT5使用QFtp,编译、部署与使用

    千次阅读 2022-01-24 20:17:14
    文章目录1.简述2.QFtp编译与部署2.1 下载2.2 修改2.3 编译2.4 部署2.5 使用3.QFtp运用3.1 Ftp客户端3.2 树莓派搭建FTP服务器3.3 测试效果 1.简述 有时在windows环境下通过远程访问操作另一台linux主机。...SFTP是基.
  • 基于Qt5/sftp上传文件(增加全局快捷键功能) 从事内网开发快一年了,每次都是通过si/Qt creator/vs编辑代码,然后通过xftp上传到内网linux服务器,最后使用xshell编辑运行。虽然只有3步,但是频繁地来回切换就很...
  • qt ftp上传文件到vsftp服务器 内容精选换一换Model File:模型文件。单击右侧的文件夹图标,在后台服务器sample所在路径(工程目录/run/out/test_data/model)选择需要转化的模型对应的*.prototxt文件,并上传。Weight ...
  • QT学习(网络) FTP FTP的主要作用,就是让用户连接上一个远程计算机,查看远程计算机有哪些文件,然后把文件从远程计算机上拷贝到本地计算机,或者把本地计算机的文件送到远程计算机上。 注意: 我使用的是QT...
  • 基于Qssh的sftp客户端

    千次阅读 热门讨论 2018-09-20 19:59:39
    项目需要写一个sftp的自动升级程序,查阅了下网上的一些资料,有libssh2+openssl和基于qssh等方法。之前考虑从filezilla源码中参考自己封装,考虑到时间关系就选择最快的方式了。基于qssh来封装。实现上传下载,文件...
  • Qt远程部署调试

    千次阅读 2018-06-26 14:11:56
    1、安装最新的Qt Creator 2、在Qt Creator 添加远程设备 ... 添加:通用Linux设备, 输入名称(随便取),设备IP地址(arm端需要支持ssh服务端,和sftp服务端),用户,密码 点击下一步测试: 上图...
  • 用户名:root 密码:111111
  • Qt中ftp文件传输

    千次阅读 2022-02-03 16:28:47
    二、Qt实现文档传输 1、准备ftp传输所使用到的工具(头文件) 2、使用ftp对象工具 总结: 拓展: 一、前期准备 首先ls查看目录,文档要是这样的绿标(这个文件夹要是读写权限,chmod 777+“加文件夹...
  • QSsh, SSH和SFTPQt的支持 在Creator的Qt libQtcSsh.so 上,这个项目是基于 关于 QSshQSsh为Qt应用程序提供了SSH和SFTP支持。 这个项目的目的是提供一个简单的方法在任何Qt应用程序中使用这些协议。这个项目是基于 ...
  • qt获取ftp服务器目录

    千次阅读 2021-08-11 05:41:32
    qt获取ftp服务器目录 内容精选换一换Linux x86-64(64位)服务器,常见的有EulerOS、Ubuntu、Debian、CentOS、OpenSUSE等。Windows 7及以上版本。请参见JRE地址下载JRE。Linux服务器安装请参考如下步骤:使用root用户...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,201
精华内容 480
关键字:

qt sftp