SSH連接僅使用公鑰完成。服務器然後要求輸入用戶名和密碼。 連接後立即將用戶名寫入流中,然後輸入「Enter」,然後輸入密碼。這讓我可以訪問服務器,並且可以在下面的情況下觸發SSH命令(幫助)。
我希望這可以幫助別人掙扎,因爲這是我的第一個Node.js項目,請隨時發表評論,並幫助我更好的解決方案,如果你知道一個!
var Connection = require('ssh2');
var c = new Connection();
c.host = '<ip/host>';
c.port = 22;
c.username = 'user';
c.password = 'password';
c.on('ready', function() {
console.log('Connection :: ready');
// If we got here we have a connection
// Start by creating a shell
c.shell(onShell);
});
var onShell = function(err, stream) {
if (err != null) {
console.log('error: ' + err);
}
var cmdcnt = 0;
stream.on('data', function(data, extended) {
//console.log((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ') + data);
console.log('[['+cmdcnt+'] '+data+']');
var str_data = String(data);
if (str_data.substr(data.length - 6) == 'xi52# ') {
//We are logged in, start sending commands...
if (cmdcnt == 2) stream.write('help\r');
}
// Set password after login, promtp #1
if (cmdcnt == 1) stream.write(c.password+'\r');
// command counter
cmdcnt++;
});
stream.on('end', function() {
console.log('Stream :: EOF');
});
stream.on('close', function() {
console.log('Stream :: close');
});
stream.on('exit', function(code, signal) {
console.log('Stream :: exit :: code: ' + code + ', signal: ' + signal);
c.end();
});
// Send username at connect
stream.write(c.username+'\r');
//console.log('Shell');
} // End onShell function
c.on('error', function(err) {
console.log('Connection :: error :: ' + err);
});
c.on('end', function() {
console.log('Connection :: end');
});
c.on('close', function(had_error) {
console.log('Connection :: close');
});
c.connect({
host: c.host,
port: c.port,
username: c.username,
password: ''
});
沒有用戶?您的PuTTY配置(Connection-> Data)中是否設置了默認用戶?您是否使用ssh-agent或Pageant進行身份驗證,或者您的PuTTY配置(Connection-> SSH-> Auth)中是否設置了私鑰? – mscdex
我有相同的設置和相同的問題。沒有用戶名,也沒有私鑰需要登錄到SSH服務器。 唯一的要求是接受Putty中的服務器指紋,然後獲得連接。連接中的用戶 - >數據爲空,並且在Putty中沒有設置私鑰。 我在ssh2中得到與TS相同的錯誤。 – Anders
你必須使用telnet或其他的東西,因爲ssh需要一個用戶名(來自某處),如果它是一個真正的ssh服務器(除非連接速度非常慢),ssh2模塊纔會給你提供握手超時錯誤信息。 – mscdex