如题,需要一份C++上传文件到SFTP服务器的代码。包括:上传、检验文件是否上传成功、创建文件夹、删除文件/文件夹功能。本人抄了些代码如下,还没有成功访问到服务器,停在了libssh2_session_handshake这一步,甚至连错误里边的内容都没有打印程序就自己结束了。我在命令窗已经验证过能够访问到服务器的,见下图。希望广大朋友们都看看!不限制库类型,如有其他上传的方式,比如curl或者其他,我也可以接受
// 初始化 libssh2 库
int rc = libssh2_init(0);
if (rc != 0) {
std::cerr << "libssh2 initialization failed" << std::endl;
return 1;
}
std::cerr << "1" << std::endl;
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(1, 1);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0)
{
return 1;
}
// 建立 TCP 连接
const char* hostname = "10.107.33.86";
int port = 30022;
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
std::cerr << "socket failed" << std::endl;
libssh2_exit();
return 1;
}
std::cerr << "2" << std::endl;
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = inet_addr(hostname);
if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) {
std::cerr << "connect failed" << std::endl;
close(sock);
libssh2_exit();
return 1;
}
std::cerr << "3" << std::endl;
// 建立 SFTP 会话
LIBSSH2_SESSION* session = libssh2_session_init();
if (!session) {
std::cerr << "libssh2_session_init failed" << std::endl;
close(sock);
libssh2_exit();
return 1;
}
std::cerr << "4" << std::endl;
rc = libssh2_session_handshake(session, sock);
if (rc != 0) {
std::cerr << "libssh2_session_handshake failed" << std::endl;
close(sock);
libssh2_session_free(session);
libssh2_exit();
return 1;
}
std::cerr << "5" << std::endl;
const char* user = "ftp01";
const char* password = "ggAe763@123!";
rc = libssh2_userauth_password(session, user, password);
if (rc != 0) {
std::cerr << "libssh2_userauth_password failed" << std::endl;
close(sock);
libssh2_session_free(session);
libssh2_exit();
return 1;
}
std::cerr << "6" << std::endl;
LIBSSH2_SFTP* sftp = libssh2_sftp_init(session);
if (!sftp) {
std::cerr << "libssh2_sftp_init failed" << std::endl;
close(sock);
libssh2_session_free(session);
libssh2_exit();
return 1;
}