🙂NodeJSのssh2モジュールを使用して、パスワード認証のサーバを作成する方法を教えてください。
💻Node.js の ssh2
モジュールを使用して、パスワード認証の SSH サーバを作成するには以下の手順を踏むことができます。
ssh2
モジュールをインストールする:npm install ssh2
const ssh2 = require('ssh2');
const server = new ssh2.Server({
hostKeys: [fs.readFileSync('host.key')]
}, (client) => {
console.log('Client connected!');
client.on('authentication', (ctx) => {
if (ctx.method === 'password'
&& ctx.username === 'username'
&& ctx.password === 'password') {
ctx.accept();
} else {
ctx.reject();
}
}).on('ready', () => {
console.log('Client authenticated!');
client.on('session', (accept, reject) => {
const session = accept();
session.once('exec', (accept, reject, info) => {
console.log('Client wants to execute: ' + info.command);
const stream = accept();
stream.stderr.write('Oh no, the command failed!\\n');
stream.write('Hello, world!\\n');
stream.exit(0);
stream.end();
});
});
}).on('end', () => {
console.log('Client disconnected');
});
});
server.listen(22, '0.0.0.0', () => {
console.log('Listening on port ' + server.address().port);
});
このコードは、ssh2
モジュールを使用して SSH サーバを作成し、ユーザ名とパスワードを使用した認証を行います。ユーザ名が username
、パスワードが password
の場合にのみ認証が成功します。また、クライアントが exec
コマンドを実行すると、標準出力に "Hello, world!" が表示されます。
この例は簡単なものですが、必要に応じて詳細な認証ロジックやコマンドの実行処理をカスタマイズすることができます。