#include <libssh/libssh.h>
#include <libssh/sftp.h>
int main() {
ssh_session my_ssh_session;
sftp_session sftp;
int rc;
// 創(chuàng)建 SSH 會(huì)話
my_ssh_session = ssh_new();
if (my_ssh_session == NULL) {
return -1;
}
// 設(shè)置連接選項(xiàng),如主機(jī)和用戶名
ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "example.com");
ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, "your_username");
// 連接到 SSH 服務(wù)器
rc = ssh_connect(my_ssh_session);
if (rc != SSH_OK) {
ssh_free(my_ssh_session);
return -1;
}
// 進(jìn)行用戶認(rèn)證(此處示例為公鑰認(rèn)證)
rc = ssh_userauth_publickey_auto(my_ssh_session, NULL, NULL);
if (rc != SSH_AUTH_SUCCESS) {
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
return -1;
}
// 創(chuàng)建 SFTP 會(huì)話
sftp = sftp_new(my_ssh_session);
if (sftp == NULL) {
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
return -1;
}
// 初始化 SFTP 會(huì)話
rc = sftp_init(sftp);
if (rc != SSH_OK) {
sftp_free(sftp);
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
return -1;
}
// ... 此處可以進(jìn)行具體的 SFTP 操作,如文件傳輸 ...
file = sftp_open(sftp, REMOTE_FILE, O_RDONLY, 0);
if (file == NULL) {
sftp_free(sftp);
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
return -1;
}
// 創(chuàng)建本地文件
local_file = fopen(LOCAL_FILE, "wb");
if (local_file == NULL) {
sftp_free(sftp);
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
return -1;
}
//SFTP傳輸文件
while ((nbytes = sftp_read(file, buffer, sizeof(buffer))) > 0) {
nwritten = fwrite(buffer, 1, nbytes, local_file);
if (nwritten != nbytes) {
fprintf(stderr, "Write error: %s\n", strerror(errno));
fclose(local_file);
sftp_close(file);
sftp_free(sftp);
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
return -1;
}
LOGM("write: %d bytes", nwritten);
fflush(stdout);
}
// SFTP關(guān)閉文件
fclose(local_file);
sftp_close(file);
// 清理資源
sftp_free(sftp);
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
return 0;
}