copySshKeyToRemote method
Implementation
Future<void> copySshKeyToRemote(
File sshKeyFile,
String username,
InternetAddress ip,
) async {
logger.detail('try to copy ssh key to remote');
final client = SSHClient(
await SSHSocket.connect(
ip.address,
22,
timeout: Duration(seconds: 10),
),
username: username,
onPasswordRequest: () {
stdout.write('Password: ');
stdin.echoMode = false;
return stdin.readLineSync() ?? exit(1);
},
);
logger.detail('creating ~/.ssh/authorized_keys');
final createAuthFile = await client.run(
'[ ! -d ~/.ssh ] && mkdir -p ~/.ssh; [ ! -f ~/.ssh/authorized_keys ] && touch ~/.ssh/authorized_keys',
);
logger.detail(
'creating ~/.ssh/authorized_keys: result is empty: ${createAuthFile.isEmpty}');
logger.detail(
'creating ~/.ssh/authorized_keys: ${utf8.decode(createAuthFile)}');
final session = await client.execute('cat >> .ssh/authorized_keys');
session.stdout.listen((data) {
final String dataAsString = utf8.decode(data);
logger.detail('SSH Session stdout: $dataAsString');
});
session.stderr.listen((data) {
final String dataAsString = utf8.decode(data);
logger.detail('SSH Session stderr: $dataAsString');
});
await session.stdin.addStream(sshKeyFile.openRead().cast());
// Close the sink to send EOF to the remote process.
await session.stdin.close();
// Wait for session to exit to ensure all data is flushed to the remote process.
await session.done;
client.close();
// You can get the exit code after the session is done
if (session.exitCode != 0) {
logger.detail('SSH Session ExitCode: ${session.exitCode}');
throwToolExit(
'Something went wrong while copying the ssh key to the remote device.');
}
}