56 lines
2.0 KiB
TypeScript
56 lines
2.0 KiB
TypeScript
![]() |
import * as fs from 'fs';
|
||
|
import * as path from 'path';
|
||
|
import * as os from 'os';
|
||
|
import * as vscode from 'vscode';
|
||
|
const { NodeSSH } = require('node-ssh')
|
||
|
|
||
|
export default class RemoteContainer {
|
||
|
|
||
|
async firstConnect(host: string, username: string, password: string, port: number): Promise<void> {
|
||
|
// connect the host and add the public key to the remote authorized_keys
|
||
|
const defaultPublicKeyPath = path.join(os.homedir(), '.ssh', 'id_rsa.pub');
|
||
|
// TODO: if there is no public key, generate one
|
||
|
const publicKey = fs.readFileSync(defaultPublicKeyPath, 'utf8');
|
||
|
|
||
|
|
||
|
// first connect to the remote host using password
|
||
|
const ssh = new NodeSSH();
|
||
|
try {
|
||
|
await ssh.connect({
|
||
|
host: host,
|
||
|
username: username,
|
||
|
password: password,
|
||
|
port: port
|
||
|
});
|
||
|
|
||
|
// add the public key to the remote authorized_keys
|
||
|
await ssh.execCommand(`mkdir -p ~/.ssh && echo '${publicKey}' >> ~/.ssh/authorized_keys`);
|
||
|
console.log('Public key added to remote authorized_keys');
|
||
|
} catch (error) {
|
||
|
console.error('Error adding public key: ', error);
|
||
|
} finally {
|
||
|
await ssh.dispose();
|
||
|
}
|
||
|
|
||
|
// TODO: request change password
|
||
|
|
||
|
// TODO: use remote.SSH.configFile
|
||
|
const sshConfigPath = path.join(os.homedir(), '.ssh', 'config');
|
||
|
// append the host to the local ssh config file
|
||
|
const sshConfigContent =
|
||
|
`\nHost ${host}\n HostName ${host}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ~/.ssh/id_rsa\n `;
|
||
|
// append the host to the local ssh config file
|
||
|
fs.writeFileSync(sshConfigPath, sshConfigContent, { encoding: 'utf8', flag: 'a' });
|
||
|
console.log('Host registered in local ssh config');
|
||
|
}
|
||
|
|
||
|
|
||
|
openRemoteFolder(host: string, path: string): void {
|
||
|
const command = `code --remote ssh-remote+${host} ${path} --reuse-window`
|
||
|
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
|
||
|
terminal.show(true);
|
||
|
terminal.sendText(command);
|
||
|
}
|
||
|
|
||
|
}
|