• QT5 实现 SFTP 上传和下载文件


    1.QSsh-Botan-1: QSSH库,含有botan分支 - Gitee.com下载QSSH 源码,注意是选择botan-1分支

    使用QT 编译,可以屏蔽掉 examples的编译

    编译完成后将 src\libs\ssh src\libs\3rdparty\botan 头文件 拷贝至工程目录/Common/ssh

    将编译好的库文件拷贝至工程目录 lib64

    工程文件 添加 LIBS += -L$${PWD}/lib64 -lQSsh -lBotan
    INCLUDEPATH += ./Common/ssh

    2. 创建类,SecureFileUploader, examples 中已经有例子,我增加下载文件的接口

    securefileuploader.h

    1. /**************************************************************************
    2. **
    3. ** This file is part of QSsh
    4. **
    5. ** Copyright (c) 2012 LVK
    6. **
    7. ** Contact: andres.pagliano@lvklabs.com
    8. **
    9. ** GNU Lesser General Public License Usage
    10. **
    11. ** This file may be used under the terms of the GNU Lesser General Public
    12. ** License version 2.1 as published by the Free Software Foundation and
    13. ** appearing in the file LICENSE.LGPL included in the packaging of this file.
    14. ** Please review the following information to ensure the GNU Lesser General
    15. ** Public License version 2.1 requirements will be met:
    16. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
    17. **
    18. **************************************************************************/
    19. #ifndef SECUREFILEUPLOADER_H
    20. #define SECUREFILEUPLOADER_H
    21. #include
    22. #include "sftpchannel.h"
    23. #include "sshconnection.h"
    24. #define UPLOAD 0
    25. #define DOWNLOAD 1
    26. /// Very simple example to upload a file using FTPS
    27. class SecureFileUploader : public QObject
    28. {
    29. Q_OBJECT
    30. public:
    31. explicit SecureFileUploader(QObject *parent = 0);
    32. void setInfo(const QString &host, const QString &userName, const QString &passwd);
    33. void upload(const QString &dest,const QString &localFile);
    34. signals:
    35. void sigDownLoadFinished();
    36. void sigUpLoadFinished();
    37. void loadError(int);
    38. void connectError();
    39. private slots:
    40. void onConnected();
    41. void onConnectionError(QSsh::SshError);
    42. void onChannelInitialized();
    43. void onChannelError(const QString &err);
    44. void onOpfinished(QSsh::SftpJobId job, const QString & error = QString());
    45. private:
    46. QString m_localFilename;
    47. QString m_remoteFilename;
    48. QSsh::SftpChannel::Ptr m_channel;
    49. QSsh::SshConnection *m_connection;
    50. void parseDestination(const QString &dest);
    51. private:
    52. QString m_host;
    53. QString m_userName;
    54. QString m_pwd;
    55. /*******下载*****/
    56. public:
    57. void DownLoad(const QString &savePath, const QString &fname);
    58. void DownLoadFiles(const QString& savePath,const QStringList &fnames);
    59. void SftpDownLoadClient();
    60. private:
    61. QString DownSavePath;
    62. QString DownFileName;
    63. QStringList DownFilenames;
    64. QSsh::SftpChannel::Ptr m_Downchannel;
    65. QSsh::SshConnection *m_Downconnection;
    66. private slots:
    67. void onDownConnected();
    68. bool onDownLoadFile();
    69. void onDownLoadfinished(QSsh::SftpJobId job, const QString &err);
    70. };
    71. #endif // SECUREFILEUPLOADER_H

    securefileuploader.cpp

    1. /**************************************************************************
    2. **
    3. ** This file is part of QSsh
    4. **
    5. ** Copyright (c) 2012 LVK
    6. **
    7. ** Contact: andres.pagliano@lvklabs.com
    8. **
    9. ** GNU Lesser General Public License Usage
    10. **
    11. ** This file may be used under the terms of the GNU Lesser General Public
    12. ** License version 2.1 as published by the Free Software Foundation and
    13. ** appearing in the file LICENSE.LGPL included in the packaging of this file.
    14. ** Please review the following information to ensure the GNU Lesser General
    15. ** Public License version 2.1 requirements will be met:
    16. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
    17. **
    18. **************************************************************************/
    19. #include "securefileuploader.h"
    20. #include
    21. #include
    22. SecureFileUploader::SecureFileUploader(QObject *parent) :
    23. QObject(parent), m_connection(0)
    24. {
    25. }
    26. void SecureFileUploader::setInfo(const QString &host, const QString &userName, const QString &passwd)
    27. {
    28. m_host = host;
    29. m_userName = userName;
    30. m_pwd = passwd;
    31. }
    32. void SecureFileUploader::upload(const QString &dest,const QString &localFile)
    33. {
    34. QFileInfo info(localFile);
    35. m_localFilename = localFile;
    36. m_remoteFilename = dest + "/" + info.fileName();
    37. QSsh::SshConnectionParameters params;
    38. params.setHost(m_host);
    39. params.setUserName(m_userName);
    40. params.setPassword(m_pwd);
    41. params.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePassword;
    42. params.timeout = 30;
    43. params.setPort(22);
    44. m_connection = new QSsh::SshConnection(params, this); // TODO free this pointer!
    45. connect(m_connection, SIGNAL(connected()), SLOT(onConnected()));
    46. connect(m_connection, SIGNAL(error(QSsh::SshError)), SLOT(onConnectionError(QSsh::SshError)));
    47. qDebug() << "SecureUploader: Connecting to host" << m_host;
    48. m_connection->connectToHost();
    49. }
    50. void SecureFileUploader::onConnected()
    51. {
    52. qDebug() << "SecureUploader: Connected";
    53. qDebug() << "SecureUploader: Creating SFTP channel...";
    54. m_channel = m_connection->createSftpChannel();
    55. if (m_channel) {
    56. connect(m_channel.data(), SIGNAL(initialized()),
    57. SLOT(onChannelInitialized()));
    58. connect(m_channel.data(), SIGNAL(initializationFailed(QString)),
    59. SLOT(onChannelError(QString)));
    60. connect(m_channel.data(), SIGNAL(finished(QSsh::SftpJobId, QString)),
    61. SLOT(onOpfinished(QSsh::SftpJobId, QString)));
    62. m_channel->initialize();
    63. } else {
    64. qDebug() << "SecureUploader: Error null channel";
    65. }
    66. }
    67. void SecureFileUploader::onConnectionError(QSsh::SshError err)
    68. {
    69. qDebug() << "SecureUploader: Connection error" << err;
    70. emit connectError();
    71. }
    72. void SecureFileUploader::onChannelInitialized()
    73. {
    74. qDebug() << "SecureUploader: Channel Initialized";
    75. qDebug()<<"m_localFilename:"<"\n";
    76. qDebug()<<"m_remoteFilename:"<"\n";
    77. QSsh::SftpJobId job = m_channel->uploadFile(m_localFilename, m_remoteFilename,
    78. QSsh::SftpOverwriteExisting);
    79. if (job != QSsh::SftpInvalidJob) {
    80. qDebug() << "SecureUploader: Starting job #" << job;
    81. } else {
    82. emit loadError(UPLOAD);
    83. qDebug() << "SecureUploader: Invalid Job";
    84. }
    85. }
    86. void SecureFileUploader::onChannelError(const QString &err)
    87. {
    88. qDebug() << "SecureUploader: Error: " << err;
    89. }
    90. void SecureFileUploader::onOpfinished(QSsh::SftpJobId job, const QString &err)
    91. {
    92. qDebug() << "SecureUploader: Finished job #" << job << ":" << (err.isEmpty() ? "OK" : err);
    93. emit sigUpLoadFinished();
    94. }
    95. void SecureFileUploader::DownLoad(const QString &savePath, const QString &fname)
    96. {
    97. DownSavePath = savePath;
    98. DownFileName = fname;
    99. SftpDownLoadClient();
    100. }
    101. void SecureFileUploader::DownLoadFiles(const QString &savePath, const QStringList &fnames)
    102. {
    103. DownSavePath = savePath;
    104. DownFilenames = fnames;
    105. DownFileName = DownFilenames.takeFirst();
    106. SftpDownLoadClient();
    107. }
    108. void SecureFileUploader::SftpDownLoadClient()
    109. {
    110. QSsh::SshConnectionParameters params;
    111. params.setHost(m_host);
    112. params.setUserName(m_userName);
    113. params.setPassword(m_pwd);
    114. params.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePassword;
    115. params.timeout = 30;
    116. params.setPort(22);
    117. m_Downconnection = new QSsh::SshConnection(params, this); // TODO free this pointer!
    118. connect(m_Downconnection, SIGNAL(connected()), SLOT(onDownConnected()));
    119. connect(m_Downconnection, SIGNAL(error(QSsh::SshError)), SLOT(onConnectionError(QSsh::SshError)));
    120. qDebug() << "SecureUploader: Connecting to host" << m_host;
    121. m_Downconnection->connectToHost();
    122. }
    123. void SecureFileUploader::onDownConnected(){
    124. qDebug() << "SecureUploader: onDownConnected Connected";
    125. qDebug() << "SecureUploader: onDownConnected Creating SFTP channel...";
    126. m_Downchannel = m_Downconnection->createSftpChannel();
    127. if (m_Downchannel) {
    128. connect(m_Downchannel.data(), SIGNAL(initialized()),
    129. SLOT(onDownLoadFile()));
    130. connect(m_Downchannel.data(), SIGNAL(initializationFailed(QString)),
    131. SLOT(onChannelError(QString)));
    132. connect(m_Downchannel.data(), SIGNAL(finished(QSsh::SftpJobId, QString)),
    133. SLOT(onDownLoadfinished(QSsh::SftpJobId, QString)));
    134. m_Downchannel->initialize();
    135. } else {
    136. qDebug() << "SecureUploader: Error null channel";
    137. }
    138. }
    139. bool SecureFileUploader::onDownLoadFile()
    140. {
    141. qDebug() << "SecureUploader: onDownLoadFile Channel Initialized";
    142. QFileInfo fileInfo(DownFileName);
    143. QString SftpSavePath = DownSavePath;
    144. #ifdef Q_OS_LINUX
    145. SftpSavePath += "/";
    146. #else
    147. SftpSavePath += "\\";
    148. #endif
    149. SftpSavePath += fileInfo.fileName();
    150. QSsh::SftpJobId job = m_Downchannel->downloadFile(DownFileName,SftpSavePath,QSsh::SftpOverwriteExisting);
    151. if (job != QSsh::SftpInvalidJob) {
    152. qDebug() << "SecureUploader: Starting job #" << job;
    153. return true;
    154. } else {
    155. emit loadError(DOWNLOAD);
    156. qDebug() << "SecureUploader: Invalid Job";
    157. return false;
    158. }
    159. return false;
    160. }
    161. void SecureFileUploader::onDownLoadfinished(QSsh::SftpJobId job, const QString &err)
    162. {
    163. qDebug() << "SecureUploader: Finished DownLoad job #" << job << ":" << (err.isEmpty() ? "OK" : err);
    164. if(err.compare("No such file",Qt::CaseSensitive)==0){
    165. QFileInfo fileInfo(DownFileName);
    166. QString SftpSavePath = DownSavePath;
    167. #ifdef Q_OS_LINUX
    168. SftpSavePath += "/";
    169. #else
    170. SftpSavePath += "\\";
    171. #endif
    172. SftpSavePath += fileInfo.fileName();
    173. QFile fileremove(SftpSavePath);
    174. fileremove.remove();
    175. }
    176. if (DownFilenames.isEmpty())
    177. {
    178. delete m_Downconnection;
    179. m_Downconnection = NULL;
    180. emit sigDownLoadFinished();
    181. }
    182. else
    183. {
    184. DownFileName = DownFilenames.takeFirst();
    185. onDownLoadFile();
    186. }
    187. }

    在对 SecureFileUploader 进一步封装 SZRSFtpTools

    SZRSFtpTools.h

    1. #ifndef SZRSFTPTOOLS_H
    2. #define SZRSFTPTOOLS_H
    3. #include
    4. #include
    5. #define SFTP_UPLOAD 0
    6. #define SFTP_DOWNLOAD 1
    7. class SecureFileUploader;
    8. class Q_DECL_EXPORT SZRSFtpTools: public QObject
    9. {
    10. Q_OBJECT
    11. public:
    12. SZRSFtpTools(QObject* parent = NULL);
    13. ~SZRSFtpTools();
    14. void setSftpInfo(const QString& host,const QString& userName,const QString& pwd);
    15. void downLoadFile(const QString &savePath, const QString &fname);
    16. void downLoadFiles(const QString &savePath, const QStringList &fnames);
    17. void uploadFile(const QString &savePath, const QString &fname);
    18. signals:
    19. void DownloadFinished();
    20. void UploadFinished();
    21. void LoadFiled(int);
    22. void connectError();
    23. private:
    24. QString m_host;
    25. QString m_userName;
    26. QString m_pwd;
    27. SecureFileUploader* m_sftp;
    28. };
    29. #endif // SZRSFTPTOOLS_H

    SZRSFtpTools.cpp

    1. #include "SZRSFtpTools.h"
    2. #include "securefileuploader.h"
    3. #include
    4. SZRSFtpTools::SZRSFtpTools(QObject* parent):
    5. QObject(parent)
    6. {
    7. m_sftp = new SecureFileUploader(this);
    8. connect(m_sftp,&SecureFileUploader::sigDownLoadFinished,this,&SZRSFtpTools::DownloadFinished);
    9. connect(m_sftp,&SecureFileUploader::sigUpLoadFinished,this,&SZRSFtpTools::UploadFinished);
    10. connect(m_sftp,&SecureFileUploader::loadError,this,&SZRSFtpTools::LoadFiled);
    11. connect(m_sftp,&SecureFileUploader::connectError,this,&SZRSFtpTools::connectError);
    12. }
    13. SZRSFtpTools::~SZRSFtpTools()
    14. {
    15. delete m_sftp;
    16. }
    17. void SZRSFtpTools::setSftpInfo(const QString &host, const QString &userName, const QString &pwd)
    18. {
    19. m_sftp->setInfo(host,userName,pwd);
    20. m_host = host;
    21. m_userName = userName;
    22. m_pwd = pwd;
    23. }
    24. void SZRSFtpTools::downLoadFile(const QString &savePath, const QString &fname)
    25. {
    26. m_sftp->DownLoad(savePath,fname);
    27. }
    28. void SZRSFtpTools::downLoadFiles(const QString &savePath, const QStringList &fnames)
    29. {
    30. m_sftp->DownLoadFiles(savePath,fnames);
    31. }
    32. void SZRSFtpTools::uploadFile(const QString &savePath, const QString &fname)
    33. {
    34. m_sftp->upload(savePath,fname);
    35. }

  • 相关阅读:
    Lombok
    linux用户管理,用户权限命令详解
    代码审计-2 SQL注入
    如何在 Wio Terminal 上运行 RT-Thread 操作系统
    3.验证面试高频问题整理(附答案)
    `maven.test.skip` 和 `skipTests` 的区别
    【最新版】ChatGPT/GPT4科研应用与AI绘图论文写作(最新增加Claude3、Gemini、Sora、GPTs技术及AI领域中的集中大模型的最新技术)
    【数据结构与算法——C语言】“串操作与算法”之“编写模式匹配算法”
    How to get active Profiles in Spring
    iOS App外包开发的内存泄露解决
  • 原文地址:https://blog.csdn.net/du2005023029/article/details/133792549