node 使用ssh2与虚机连接并上传文件到虚机

发布于:2024-04-14 ⋅ 阅读:(137) ⋅ 点赞:(0)

背景:需要将本地文件拷贝到虚机(将本地文件上传到虚机)

导入依赖

npm install path
npm install ssh2

const path = require('path');

const { Client } = require('ssh2')

配置本地文件路径及远程文件夹路径

// 将本地的C:/Users/xxx/Desktop/test 文件夹下面的test.txt 上传到虚机的/home/xxx/test
const localFilePath = 'C:/Users/yuan/Desktop/test/test.txt'

const remoteDirectory = '/home/yuan/test'

SSH 连接参数

const sshConfig = {
    host: '192.168.xx.xxx',
    port: 22, // 默认 SSH 端口
    username: 'yuan',
    password: 'xxxxxx' // 或者使用私钥代替
};

实例client

const client = new Client();
client.on('ready', () => {
    console.log('SSH 连接已建立');
    let exists = false
    // 判断远程是否存在该文件夹
    client.exec(`[ -d "${remoteDirectory}" ] && echo "Directory exists" || echo "Directory not found"`, (err, stream) => {
        if (err) {
            console.error('执行命令失败:', err);
            client.end();
            return;
        }

        stream.on('data', (data) => {
            console.log(`stdout: ${data}`);
            const buffer = Buffer.from(data).toString().trim();
            if (buffer == 'Directory not found') {
                exists = false
            } else {
                // Directory exists
                exists = true
            }
        });
        stream.on('close', (code, signal) => {
            console.log(`exit code: ${code}`);
            console.log(`signal: ${signal}`);
        })
    })

    // 执行 SFTP 操作
    client.sftp((err, sftp) => {
        if (err) {
            console.error('SFTP 连接失败:', err);
            client.end();
            return;
        }

        console.log('SFTP 连接已建立');
        if (!exists) {
            sftp.mkdir(remoteDirectory, true, (err) => {
                if (err) {
                    console.error('远程目录创建失败:', err);
                    sftp.end();
                    client.end();
                    return
                }
            })
            console.log('远程目录创建成功');
        }

        const localFileName = path.basename(localFilePath);
        // path.join会将/home/yuan/test 转换为 \home\yuan\test ===> 使用path.posix.join进行转换
        const remoteFilePath = path.posix.join(remoteDirectory, localFileName);
        // const remoteFilePath = `${remoteDirectory}/${localFileName}`;
        console.log('localFilePath', localFilePath)
        console.log('remoteFilePath', remoteFilePath)
        // 上传文件
        sftp.fastPut(localFilePath, remoteFilePath, {}, (err) => {
            if (err) {
                console.error('文件上传失败:', err);
            } else {
                console.log('文件上传成功');
            }

            // 关闭 SFTP 和 SSH 连接
            sftp.end();
            client.end();
        });
    });
});

调用

client.connect(sshConfig)

网站公告

今日签到

点亮在社区的每一天
去签到