当前位置:   article > 正文

基于libssh2拷贝文件夹下所有文件到本地目录_c++ 使用libssh2下载服务器文件到本地

c++ 使用libssh2下载服务器文件到本地
  1. 基于libssh2,使用层次遍历的方式,从远端拷贝文件到本地目录,支持所有目录(等同于ssh -r效果)
#include <string>
#include <QString>
#include <libssh2.h>
#include <libssh2_sftp.h>

static QString sourceDir = "";
static std::queue<QString> que;
static std::vector<QString> vec;

int sftp_hierarchical_traversal() {
	std::queue<QString> emptyQue;
	std::swap(que, emptyQue);
	vec.clear();
	que.push(sourceDir);

	const char* username = "";
	const char* password = "";
	std::string clientAddress = "";
	const char* hostname = "";
	const char* remote_path = "";
	const char* local_path = "";
	int port = 22;
	struct sockaddr_in sin;
	unsigned long hostaddr;

	// 初始化 libssh2 库
	int rc = libssh2_init(0);
	if (rc != 0) {
		fprintf(stderr, "Failed to initialize libssh2\n");
		return 1;
	}

	// 连接到远程主机
	LIBSSH2_SESSION* session = libssh2_session_init();
	if (!session) {
		fprintf(stderr, "Failed to create SSH session\n");
		libssh2_exit();
		return 1;
	}

	hostaddr = inet_addr(hostname);
	sin.sin_family = AF_INET;
	sin.sin_port = htons(22);
	sin.sin_addr.s_addr = hostaddr;
	// 创建socket
	int sock = socket(AF_INET, SOCK_STREAM, 0);//ws2_32.lib
	if (sock == -1) {
		std::cerr << "Failed to create socket" << std::endl;
		return 1;
	}

	if (::connect(sock, (struct sockaddr*)(&sin),
		sizeof(struct sockaddr_in)) != 0) {
		fprintf(stderr, "failed to connect!\n");
		return -1;
	}

	// 设置连接选项
	libssh2_session_set_blocking(session, 1);
	//rc = libssh2_session_startup(session, socket, username, hostname, port);
	rc = libssh2_session_handshake(session, sock);
	if (rc) {
		fprintf(stderr, "Failed to connect to %s:%d\n", hostname, port);
		libssh2_session_disconnect(session, "Failed to connect");
		libssh2_session_free(session);
		libssh2_exit();
		return 1;
	}

	// 使用用户名和密码进行身份验证
	if (libssh2_userauth_password(session, username, password)) {
		fprintf(stderr, "Authentication by password failed\n");
		libssh2_session_disconnect(session, "Authentication failed");
		libssh2_session_free(session);
		libssh2_exit();
		return 1;
	}

	// 初始化 SFTP 会话
	LIBSSH2_SFTP* sftp_session = libssh2_sftp_init(session);
	if (!sftp_session) {
		fprintf(stderr, "Failed to initialize SFTP session\n");
		libssh2_session_disconnect(session, "Failed to initialize SFTP session");
		libssh2_session_free(session);
		libssh2_exit();
		return 1;
	}

	while (!que.empty()) {
		QString remotePath = que.front();

		// Open the remote directory
		LIBSSH2_SFTP_HANDLE* sftp_handle;
		sftp_handle = libssh2_sftp_opendir(sftp_session, remotePath.toLocal8Bit().constData());
		if (!sftp_handle) {
			return 0;
		}

		// Iterate through the remote directory
		char buffer[512];
		while (1) {

			LIBSSH2_SFTP_ATTRIBUTES attrs;
			const char* filename;
			int rc = libssh2_sftp_readdir(sftp_handle, buffer, sizeof(buffer), &attrs);
			if (rc <= 0) {
				break;
			}
			if (strcmp(buffer, ".") == 0 || strcmp(buffer, "..") == 0) {
				continue;
			}
			filename = buffer;

			QString remoteFile = remotePath + "/" + filename;
			if (LIBSSH2_SFTP_S_ISDIR(attrs.permissions)) {
				que.push(remoteFile);
			}
			else {
				vec.push_back(remoteFile);

				// 拷贝文件到本地
				LIBSSH2_SFTP_ATTRIBUTES attrs;
				libssh2_sftp_stat(sftp_session, remoteFile.toLocal8Bit().constData(), &attrs);
				if (attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS && LIBSSH2_SFTP_S_ISREG(attrs.permissions)) {
					QString local_file = remoteFile;
					local_file.replace(sourceDir, stateCache_imageDir);

					QFileInfo fileInfo(local_file);
					QDir directory = fileInfo.dir();
					// 判断文件对应的目录是否存在
					if (!directory.exists()) {
						QDir().mkpath(directory.absolutePath());
					}

					FILE* local_fp = fopen(local_file.toLocal8Bit().constData(), "wb");
					LIBSSH2_SFTP_HANDLE* remote_handle = libssh2_sftp_open(sftp_session, remoteFile.toLocal8Bit().constData(), LIBSSH2_FXF_READ, 0);
					size_t nread;
					char buffer[1024];
					do {
						nread = libssh2_sftp_read(remote_handle, buffer, sizeof(buffer));
						if (nread > 0) {
							fwrite(buffer, 1, nread, local_fp);
						}
					} while (nread > 0);
					fclose(local_fp);
					libssh2_sftp_close(remote_handle);
				}
			}
		}

		que.pop();
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  1. 直接调用ssh可执行文件的方式(需要在本机上生成公钥私钥,把公钥放到远端主机的.ssh目录下):
	//1. 拷贝数据
	//===========================================================
	// scp -r -i ~/Desktop/id_rsa -o "StrictHostKeyChecking no" root@192.168.226.41:/source ~/Desktop/
	// 创建QProcess对象
	QString appPath = QCoreApplication::applicationDirPath();
	// 设置要执行的命令行程序和参数
	QString program = "scp.exe";
	QStringList arguments;
	arguments << "-r" << QString::fromLocal8Bit("-i") << QString(appPath + "/id_rsa") << QString("-o") << QString("StrictHostKeyChecking no") << QString("root\@:/source ")) << stateCache_imageDir;
	qDebug() << appPath + "/id_rsa";
	// 启动外部进程
	QProcess process;
	process.start(program, arguments);
	process.waitForFinished(-1); // 等待进程执行完毧

	// 读取外部进程的输出
	QByteArray output = process.readAllStandardOutput();
	QByteArray error = process.readAllStandardError();
	LOG_ERROR(QString("Output : %1.").arg(QString(output)));
	LOG_ERROR(QString("Error : %1.").arg(QString(error)));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/894676
推荐阅读
相关标签
  

闽ICP备14008679号