admin
2025-07-17 6cd92a169cbc0db35042f243a09d976fd3e1445c
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#pragma once
 
#include <libssh2.h>
#include <libssh2_sftp.h>
#include <string>
#include <iostream>
#include <fstream>
#include <functional>
using namespace std;
struct SSHServer {
    string host;
    int port;
    string username;
    string password;
};
 
class SSHUtil {
private:
    static int _download_file(LIBSSH2_SESSION* session, const std::string& remote_path, const std::string& local_path, std::function<void(uint64_t transferred, uint64_t total)> progress_callback = nullptr) {
        LIBSSH2_SFTP* sftp_session = libssh2_sftp_init(session);
        if (!sftp_session) {
            throw string("Failed to init SFTP session!");
        }
 
        // ´ò¿ªÔ¶³ÌÎļþ£¨Ö»¶Á£©
        LIBSSH2_SFTP_HANDLE* sftp_handle = libssh2_sftp_open(sftp_session, remote_path.c_str(), LIBSSH2_FXF_READ, 0);
        if (!sftp_handle) {
            throw string("Failed to open remote file : ").append(remote_path);
            libssh2_sftp_shutdown(sftp_session);
            return -1;
        }
 
        // »ñÈ¡Îļþ´óС
        LIBSSH2_SFTP_ATTRIBUTES attrs;
        if (libssh2_sftp_fstat(sftp_handle, &attrs)) {
            libssh2_sftp_close(sftp_handle);
            libssh2_sftp_shutdown(sftp_session);
            throw string("Unable to get file size");
        }
        const long totalSize = attrs.filesize;
 
        // ´´½¨±¾µØÎļþ
        std::ofstream local_file(local_path, std::ios::binary);
        if (!local_file) {
            libssh2_sftp_close(sftp_handle);
            libssh2_sftp_shutdown(sftp_session);
            throw string("Failed to create local file: ").append(local_path);
        }
 
        // ¶ÁȡԶ³ÌÎļþ²¢Ð´Èë±¾µØ
        char buffer[32 * 1024];
        long receivedSize = 0;
        try {
            while (true) {
                int rc = libssh2_sftp_read(sftp_handle, buffer, sizeof(buffer));
 
                if (rc == LIBSSH2_ERROR_EAGAIN) {
                    continue;
                }
                else if (rc <= 0) {
                    break; // ÏÂÔØÍê³É»ò³ö´í
                }
 
                // Ð´Èë±¾µØÎļþ
                local_file.write(buffer, rc);
                if (!local_file) {
                    throw string("Failed to write to local file");
                    break;
                }
 
                // ¸üнø¶È
                receivedSize += rc;
                if (progress_callback) {
                    progress_callback(receivedSize, totalSize);
                }
            }
            if (receivedSize != totalSize) {
                throw string("The download file sizes are not equal");
            }
        }
        catch (string msg) {
            libssh2_sftp_close(sftp_handle);
            libssh2_sftp_shutdown(sftp_session);
            local_file.close();
            throw msg;
        }
 
        // ¹Ø±Õ×ÊÔ´
        libssh2_sftp_close(sftp_handle);
        libssh2_sftp_shutdown(sftp_session);
        local_file.close();
        return 0;
    }
 
    static int _upload_file(LIBSSH2_SESSION* session, const std::string& local_path, const std::string& remote_path, std::function<void(uint64_t transferred, uint64_t total)> progress_callback = nullptr) {
        LIBSSH2_SFTP* sftp_session = libssh2_sftp_init(session);
        if (!sftp_session) {
            throw string("Failed to init SFTP session!");
        }
 
        // ´ò¿ªÔ¶³ÌÎļþ£¨Ð´Èë + ´´½¨£©
        LIBSSH2_SFTP_HANDLE* sftp_handle = libssh2_sftp_open(
            sftp_session,
            remote_path.c_str(),
            LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_TRUNC,
            LIBSSH2_SFTP_S_IRUSR | LIBSSH2_SFTP_S_IWUSR  // È¨ÏÞ: Óû§¿É¶Á¿Éд
        );
        if (!sftp_handle) {
            libssh2_sftp_shutdown(sftp_session);
            throw string("Failed to open remote file:").append(remote_path);
        }
 
        // ´ò¿ª±¾µØÎļþ
        std::ifstream local_file(local_path, std::ios::binary | std::ios::ate);
        if (!local_file) {
            libssh2_sftp_close(sftp_handle);
            libssh2_sftp_shutdown(sftp_session);
            throw string("Failed to open local file : ").append(local_path);
        }
        // »ñÈ¡×ÜÎļþ´óС
        uint64_t file_size = local_file.tellg();
        local_file.seekg(0, std::ios::beg);
 
        // ¶ÁÈ¡±¾µØÎļþ²¢Ð´ÈëÔ¶³Ì
        uint64_t transferred = 0;
        char buffer[1024 * 32];
        try {
            while (!local_file.eof())
            {
                local_file.read(buffer, sizeof(buffer));
                ssize_t bytes_read = local_file.gcount();
                if (bytes_read > 0) {
                    ssize_t bytes_sent = 0;
                    while (bytes_sent < bytes_read) {
                        ssize_t rc = libssh2_sftp_write(
                            sftp_handle,
                            buffer + bytes_sent,
                            bytes_read - bytes_sent
                        );
 
                        if (rc < 0) {
                            throw string("Upload error: ").append(local_path);
                            break;
                        }
                        bytes_sent += rc;
                        transferred += rc;
                        if (progress_callback) {
                            progress_callback(transferred, file_size);
                        }
                    }
                }
            }
        }
        catch (...) {
            libssh2_sftp_close(sftp_handle);
            libssh2_sftp_shutdown(sftp_session);
            local_file.close();
            throw string("ÉÏ´«Îļþ³ö´í£¡");
        }
        // ¹Ø±Õ×ÊÔ´
        libssh2_sftp_close(sftp_handle);
        libssh2_sftp_shutdown(sftp_session);
        local_file.close();
        return 0;
    }
 
public:
    /**
     * Ö´ÐÐÃüÁî
     */
    static void excuteCmd(string cmd, SSHServer server) {
        int port = server.port;
        libssh2_init(0);
 
        // ´´½¨socket
        int sock = socket(AF_INET, SOCK_STREAM, 0);
 
        sockaddr_in sin;
        sin.sin_family = AF_INET;
        sin.sin_port = htons(port);
 
        // Ê¹Óàinet_pton Ìæ´ú inet_addr
        if (inet_pton(AF_INET, server.host.c_str(), &sin.sin_addr) <= 0) {
            throw string("IPµØÖ·´íÎó£º").append(server.host);
        }
 
        if (connect(sock, (sockaddr*)(&sin), sizeof(sockaddr_in)) != 0) {
            throw string("Á¬½Óʧ°Ü£º").append(server.host);
        }
 
        // ´´½¨SSH»á»°
        LIBSSH2_SESSION* session = libssh2_session_init();
        if (!session) {
            throw string("ÎÞ·¨´´½¨SSH»á»°£º").append(server.host);
        }
 
        // ÎÕÊÖ
        if (libssh2_session_handshake(session, sock)) {
            throw string("SSHÎÕÊÖʧ°Ü£º").append(server.host);
        }
 
        // ÈÏÖ¤
        if (libssh2_userauth_password(session, server.username.c_str(), server.password.c_str())) {
            throw string("ÈÏ֤ʧ°Ü£º").append(server.host);
        }
 
        // Ö´ÐÐÃüÁî
        LIBSSH2_CHANNEL* channel = libssh2_channel_open_session(session);
        if (!channel) {
            throw string("ÎÞ·¨´ò¿ªÍ¨µÀ£º").append(server.host);
        }
 
        if (libssh2_channel_exec(channel, cmd.c_str())) {
            throw string("Ö´ÐÐÃüÁîʧ°Ü£º").append(server.host);
        }
 
        char buffer[1024];
        int nbytes;
        while ((nbytes = libssh2_channel_read(channel, buffer, sizeof(buffer))) > 0) {
            std::cout.write(buffer, nbytes);
        }
        libssh2_channel_close(channel);
        libssh2_channel_free(channel);
        libssh2_session_disconnect(session, "Õý³£Í˳ö");
        libssh2_session_free(session);
        closesocket(sock);
    }
    /*
     * ÏÂÔØÎļþ
     */
    static void downloadFile(string remote_path,string local_path, SSHServer server, std::function<void(uint64_t transferred, uint64_t total)> progress_callback = nullptr) {
        int port = 22;
        libssh2_init(0);
 
        // ´´½¨socket
        int sock = socket(AF_INET, SOCK_STREAM, 0);
 
        sockaddr_in sin;
        sin.sin_family = AF_INET;
        sin.sin_port = htons(port);
 
        // Ê¹Óàinet_pton Ìæ´ú inet_addr
        if (inet_pton(AF_INET, server.host.c_str(), &sin.sin_addr) <= 0) {
            throw string("IPµØÖ·´íÎó").append(server.host);
        }
 
        if (connect(sock, (sockaddr*)(&sin), sizeof(sockaddr_in)) != 0) {
            throw string("Á¬½Óʧ°Ü").append(server.host);
        }
 
        // ´´½¨SSH»á»°
        LIBSSH2_SESSION* session = libssh2_session_init();
        if (!session) {
            throw string("ÎÞ·¨´´½¨SSH»á»°").append(server.host);
        }
 
        // ÎÕÊÖ
        if (libssh2_session_handshake(session, sock)) {
            throw string("SSHÎÕÊÖʧ°Ü").append(server.host);
        }
 
        // ÈÏÖ¤
        if (libssh2_userauth_password(session, server.username.c_str(), server.password.c_str())) {
            throw string("ÈÏ֤ʧ°Ü").append(server.host);
        }
        _download_file(session, remote_path, local_path, progress_callback);
        libssh2_session_disconnect(session, "Õý³£Í˳ö");
        libssh2_session_free(session);
        closesocket(sock);
    }
 
    /**
     * ÉÏ´«Îļþ
     */
    static void uploadFile(string remote_path, string local_path, SSHServer server, std::function<void(uint64_t transferred, uint64_t total)> progress_callback = nullptr) {
        int port = 22;
        libssh2_init(0);
 
        // ´´½¨socket
        int sock = socket(AF_INET, SOCK_STREAM, 0);
 
        sockaddr_in sin;
        sin.sin_family = AF_INET;
        sin.sin_port = htons(port);
 
        // Ê¹Óàinet_pton Ìæ´ú inet_addr
        if (inet_pton(AF_INET, server.host.c_str(), &sin.sin_addr) <= 0) {
            throw string("IPµØÖ·´íÎó£º").append(server.host);
        }
 
        if (connect(sock, (sockaddr*)(&sin), sizeof(sockaddr_in)) != 0) {
            throw string("Á¬½Óʧ°Ü£º").append(server.host);
        }
 
        // ´´½¨SSH»á»°
        LIBSSH2_SESSION* session = libssh2_session_init();
        if (!session) {
            throw string("ÎÞ·¨´´½¨SSH»á»°£º").append(server.host);
        }
 
        // ÎÕÊÖ
        if (libssh2_session_handshake(session, sock)) {
            throw string("SSHÎÕÊÖʧ°Ü£º").append(server.host);
        }
 
        // ÈÏÖ¤
        if (libssh2_userauth_password(session, server.username.c_str(), server.password.c_str())) {
            throw string("ÈÏ֤ʧ°Ü£º").append(server.host);
        }
        _upload_file(session, local_path, remote_path, progress_callback);
        libssh2_session_disconnect(session, "Õý³£Í˳ö");
        libssh2_session_free(session);
        closesocket(sock);
    }
 
 
 
 
 
 
 
};