Created
July 23, 2023 19:08
-
-
Save cconstab/11171392833db9a34a6f2da3ebacdc6b to your computer and use it in GitHub Desktop.
Dart FFI libssh with private key auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:ffi'; | |
import 'dart:io'; | |
import 'package:ffi/ffi.dart'; | |
import 'package:libssh_binding/libssh_binding.dart'; | |
import 'dart:ffi' as ffi; | |
import 'package:path/path.dart' as path; | |
void main() async { | |
// Some vars (change to suit) | |
String remoteFile = "/home/cconstab/testfile"; | |
String localFile = "./testfile"; | |
String sshKeyFile = "/home/cconstab/.ssh/GitHub_rsa"; | |
var host = "192.168.1.149"; | |
var port = 22; | |
var username = "cconstab"; | |
// Open the dynamic library | |
var libraryPath = path.join('/lib/x86_64-linux-gnu/', 'libssh.so.4'); | |
final dll = ffi.DynamicLibrary.open(libraryPath); | |
var libssh = LibsshBinding(dll); | |
// Set up session | |
var mySshSession = libssh.ssh_new(); | |
libssh.ssh_options_set(mySshSession, ssh_options_e.SSH_OPTIONS_HOST, stringToNativeVoid(host)); | |
libssh.ssh_options_set(mySshSession, ssh_options_e.SSH_OPTIONS_PORT, intToNativeVoid(port)); | |
libssh.ssh_options_set(mySshSession, ssh_options_e.SSH_OPTIONS_USER, stringToNativeVoid(username)); | |
// Connect to server | |
var rc = libssh.ssh_connect(mySshSession); | |
if (rc != SSH_OK) { | |
print('Error connecting to host: $host\n'); | |
} | |
ffi.Pointer<ffi.Pointer<ssh_key_struct>> sshKey = calloc(); | |
rc = libssh.ssh_pki_import_privkey_file( | |
stringToNativeInt8(sshKeyFile), nullptr, nullptr, nullptr, sshKey); | |
rc = libssh.ssh_userauth_publickey(mySshSession, stringToNativeInt8(username), sshKey[0]); | |
if (rc != ssh_auth_e.SSH_AUTH_SUCCESS) { | |
var error = libssh.ssh_get_error(mySshSession.cast()); | |
print("Error authenticating with Keys:$error\n"); | |
libssh.ssh_disconnect(mySshSession); | |
libssh.ssh_free(mySshSession); | |
exit(-1); | |
} | |
await libssh.sftpDownloadFileTo( | |
mySshSession, stringToNativeInt8(remoteFile), path.join(Directory.current.path, localFile)); | |
libssh.ssh_disconnect(mySshSession); | |
libssh.ssh_free(mySshSession); | |
exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment