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

Python调用Node.js脚本时出现ERR_INVALID_AUTH_CREDENTIALS错误排查

问题排查:Python调用WhatsApp脚本出现ERR_INVALID_AUTH_CREDENTIALS错误

问题描述

在Ubuntu 22系统中,直接通过以下命令运行Node.js脚本(index.js)时一切正常:

xvfb-run -a -s "-screen 0 1024x768x24" node index.js

但通过Python的subprocess模块调用时,出现错误:

An error occurred: Error: net::ERR_INVALID_AUTH_CREDENTIALS at https://web.whatsapp.com

相关代码如下:

index.js代码

const { Client, LocalAuth } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');

(async () => {
    console.log('Starting browser launch...');

    try {
        const client = new Client({
            puppeteer: {
                executablePath: '/usr/bin/google-chrome',
                headless: true,
                args: [
                    '--no-sandbox',
                    '--disable-setuid-sandbox',
                    '--disable-web-security',
                    '--ignore-certificate-errors',
                    '--disable-gpu',
                    '--disable-dev-shm-usage',
                    '--remote-debugging-port=9222',
                    '--disable-software-rasterizer'
                ],
                ignoreHTTPSErrors: true,
                dumpio: true
            },
            authStrategy: new LocalAuth({ clientId: 'exampleSession' }),
        });

        client.on('qr', (qr) => {
            console.log('QR Code received.');
            qrcode.generate(qr, { small: true });
        });

        client.on('error', (error) => {
            console.error('Client error:', error);
        });

        await client.initialize();
        console.log('WhatsApp client initialized.');

        await new Promise(resolve => setTimeout(resolve, 60000));
        await browser.close();
        console.log('Browser closed.');
    } catch (error) {
        console.error('An error occurred:', error);
    }
})();

Python调用代码

import threading
import subprocess

def start_node_script():
    global process

    command = ['xvfb-run', '-a', '-s', '-screen 0 1024x768x24', 'node', 'index.js']

    # Start process Node.js
    process = subprocess.Popen( 
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        bufsize=1,
    )

    # Reading output in a separate thread
    threading.Thread(target=read_process_output, args=(process,), daemon=True).start()

    log("Node.js script started", session="server")
    return jsonify({"message": "Node.js script started"})

错误关联因素

这个错误主要和会话权限、进程运行上下文、环境变量传递、xvfb参数格式相关:

  • LocalAuth依赖本地会话目录存储登录凭证,若Python进程无读写权限会导致凭证加载失败。
  • Python调用时的环境变量(如HOME)可能与直接命令行运行时不一致,导致会话目录路径错误。
  • xvfb参数传递格式错误,可能导致Chrome运行环境异常,影响凭证验证。
  • Node脚本中存在未定义变量(browser),可能在后续执行中破坏会话状态。

排查方向

  • 会话目录权限检查:查看~/.wwebjs_auth目录的所有者和权限,对比直接运行命令的用户与Python进程的运行用户是否一致。
  • xvfb参数验证:确认Python中command数组的参数拆分是否正确,直接命令行中-s后的参数是一个整体,需保证subprocess传递时不被拆分。
  • 环境变量对比:分别打印直接运行和Python调用时的环境变量(如echo $HOME、echo $PATH),检查关键变量是否一致。
  • Node脚本语法检查:确认browser变量是否已定义,避免因脚本内部错误导致会话异常。

修复方案

  1. 修正xvfb参数传递格式
    直接命令行中-s "-screen 0 1024x768x24"是一个完整参数,在Python的command数组中需保持整体,修改为:

    command = ['xvfb-run', '-a', '-s', '"-screen 0 1024x768x24"', 'node', 'index.js']
    

    或者去掉引号(subprocess数组参数无需shell引号):

    command = ['xvfb-run', '-a', '-s', '-screen 0 1024x768x24', 'node', 'index.js']
    
  2. 确保会话目录权限一致
    若Python进程以不同用户运行,修改会话目录权限:

    chmod -R 775 ~/.wwebjs_auth
    chown -R <python运行用户>:<用户组> ~/.wwebjs_auth
    
  3. 传递完整环境变量
    在subprocess.Popen中添加env参数,继承当前环境变量:

    import os
    process = subprocess.Popen( 
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        bufsize=1,
        env=os.environ.copy()  # 添加此行
    )
    
  4. 修复Node脚本中的未定义变量
    将await browser.close()替换为WhatsApp客户端提供的关闭方法:

    await client.destroy();  // 或者 client.pupBrowser.close()
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 07:18:22