You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ssh2-sftp-client连接Linux SFTP失败,FileZilla可正常连接

排查方案与信息收集方法

1. 开启调试日志获取详细交互过程

ssh2-sftpClient基于ssh2模块,开启调试模式能看到完整的认证交互细节,对比FileZilla的日志就能找到差异。修改连接配置添加debug参数:

let sftp = new Client();
let conn = await sftp
    .connect({
        protocol: 'sftp', // 注意修正拼写错误:原代码里的protocal应为protocol
        host: '##.##.##.##',
        port: 22,
        username: 'gp',
        privateKey: key,
        debug: (msg) => console.log('SSH调试信息:', msg)
    })
    .then(() => console.log('连接成功!'))
    .catch((err: any) => console.log(err, '捕获错误'));

同时在FileZilla开启详细日志:编辑→设置→调试→调试信息级别设为3,对比两者的认证步骤差异。

2. 检查私钥的格式与加载正确性

  • 确认key变量是完整的私钥内容:从文件读取时用fs.readFileSync('私钥路径', 'utf8'),避免编码缺失。
  • 若私钥本身有加密密码,需在连接配置里添加passphrase: '你的私钥密码'参数(FileZilla会弹窗提示输入,但代码需显式配置)。
  • 尝试转换私钥格式:用ssh-keygen -p -f 私钥文件路径 -m pem命令把OpenSSH格式转成PEM格式,再重新测试。

3. 强制指定认证方法顺序

部分Linux服务器对认证方法顺序有要求,手动配置algorithms参数优先尝试公钥认证:

.connect({
    // 其他基础配置...
    algorithms: {
        kex: ['diffie-hellman-group-exchange-sha256', 'diffie-hellman-group14-sha256'],
        serverHostKey: ['ssh-rsa', 'ecdsa-sha2-nistp256'],
        cipher: ['aes256-gcm@openssh.com', 'aes128-gcm@openssh.com'],
        hmac: ['hmac-sha2-256-etm@openssh.com'],
        compress: ['none']
    },
    preferKeyboardInteractive: false // 禁用键盘交互优先,强制先尝试公钥认证
})

4. 启用键盘交互认证逻辑

部分Linux服务器会将公钥认证与键盘交互绑定,取消注释代码里的tryKeyboard: true并添加交互处理:

let sftp = new Client();
sftp.tryKeyboard = true;
// 监听键盘交互事件,根据服务器提示返回对应内容(无输入需求则传空数组)
sftp.on('keyboard-interactive', (name, instructions, _, prompts, finish) => {
    finish(prompts.map(() => ''));
});
// 后续执行connect逻辑

5. 清理冗余连接参数

连接配置里的remotePath属于后续文件操作的参数,连接阶段不需要配置,直接删除该参数避免干扰。

内容的提问来源于stack exchange,提问作者spacedog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:41:34