React Native
React Native
SFTP Public-Key Authentication
See more SFTP Examples
Demonstrates how to authenticate with an SSH/SFTP server using publickey authentication.Chilkat React Native Downloads
import { SFtp, SshKey } from '@chilkat/react-native'
async function chilkatExample() {
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const sftp = new SFtp();
// Set some timeouts, in milliseconds:
sftp.connectTimeoutMs = 5000;
sftp.idleTimeoutMs = 15000;
// Connect to the SSH server.
// The standard SSH port = 22
// The hostname may be a hostname or IP address.
const hostname = 'sftp.example.com';
const port = 22;
try {
await sftp.connectAsync(hostname, port);
} catch {
console.log(sftp.lastErrorText);
return;
}
const key = new SshKey();
// Load a PEM file into a string variable:
// (This does not load the PEM file into the key. The LoadText
// method is a convenience method for loading the full contents of ANY text
// file into a string variable.)
let privKey: string;
try {
privKey = key.loadText('myPrivateKey.pem');
} catch {
console.log(key.lastErrorText);
return;
}
// Load a private key from a PEM string:
// (Private keys may be loaded from OpenSSH and Putty formats.
// Both encrypted and unencrypted private key file formats
// are supported. This example loads an unencrypted private
// key in OpenSSH format.
try {
key.fromOpenSshPrivateKey(privKey);
} catch {
console.log(key.lastErrorText);
return;
}
// Authenticate with the SSH server. Chilkat SFTP supports
// both password-based authenication as well as public-key
// authentication.
try {
await sftp.authenticatePkAsync('myLogin', key);
} catch {
console.log(sftp.lastErrorText);
return;
}
console.log(sftp.lastErrorText);
console.log('Public-Key Authentication Successful!');
}