在这之前需要安装 ssh2-sftp-client 直接在终端输入:npm i ssh2-sftp-client
直接上代码:
- const path = require('path');
- const Client = require('ssh2-sftp-client');
-
- // 配置连接参数
- const config = {
- host: 'your-server-ip', // 云服务器的IP地址
- port: 22, // SSH端口号,默认为22
- username: 'your-username', // SSH用户名
- password: 'your-password' // SSH密码
- };
-
- // 创建 SFTP 客户端
- const sftp = new Client();
-
- // 上传的本地文件路径
- const localFilePath = path.resolve(__dirname, 'userInfo.json'); // 我这里数据userInfo.json
-
- // 远程服务器上的目标路径
- const remoteFilePath = '/root/userInfo.json'; // 我这里的目录是/root
- // 后面只是上传数据的名字,如果没有弄后面的userInfo.json,上传默认数据名字就是root
-
- sftp.connect(config)
- .then(() => {
- return sftp.put(localFilePath, remoteFilePath);
- })
- .then(() => {
- console.log(`JSON 文件上传成功`);
- sftp.end();
- })
- .catch((err) => {
- console.error(`上传文件时出错: ${err.message}`);
- sftp.end();
- });