当我运行下面的命令时,我能够通过git-bash/Putty连接到EC2实例: ssh host-name ssh能够工作,因为在ssh/ .This文件中所有的参数都存在。我的要求是使用Node-js npm库做同样的事情。有什么办法可以做到吗?谢谢
发布于 2020-10-21 08:44:37
有一个npm包可用。https://www.npmjs.com/package/node-ssh
创建EC2实例(例如ubuntu服务器)时,可以下载认证所需的私钥文件yourprivatekey.pem
。创建一个新的节点项目并运行npm i node-ssh
。复制项目文件夹中的yourprivatekey.pem
,修改文件permission chmod 400 yourprivatekey.pem
。在项目文件夹中创建一个index.js
文件,并使用ssh copy命令粘贴以下示例代码,以将文件从EC2复制到本地计算机。
const fs = require('fs')
const path = require('path')
const {NodeSSH} = require('node-ssh')
const ssh = new NodeSSH()
ssh.connect({
host: 'abc123456-example.compute-1.amazonaws.com', //replace with your ec2 host
username: 'ubuntu', //replace with your EC2 username
privateKey: './yourprivatekey.pem' //replace with your private key file
})
.then(function() {
// Local, Remote (replace with you own file path)
ssh.getFile('/home/pi/test.txt', '/home/ubuntu/test.txt').then(function(Contents) {
console.log("The File's contents were successfully downloaded")
}, function(error) {
console.log("Something's wrong")
console.log(error)
})
})
其他ssh操作请参阅上述链接上的API文档。
https://stackoverflow.com/questions/64453486
复制相似问题