如何从远程计算机获取当前登录的用户名

How to get the currently logged in username from a remote computer

有没有办法从远程计算机获取当前登录的用户名? (我正在寻找与 getUserName() 相关的内容)

我有一个可行的解决方案,但(老实说)感觉就像用滑板发射的巡航导弹杀死一只苍蝇(复杂,肯定需要很长时间,而且可能杀伤力过大)。

我的解决方案(到目前为止):

QString NetworkHandle::getUserName(QString entry){
    QString s1, s2, command;
    std::string temp, line;
    const char *cmd;
    char buf[BUFSIZ];
    FILE *ptr, *file;
    int c;

    s1 = "wmic.exe /node:";
    s2 = " computersystem get username 2> nul";
    command = s1 + entry + s2;
    temp = command.toLocal8Bit().constData();
    cmd = temp.c_str();

    file = fopen("buffer.txt", "w");

    if(!file){
        this->setErrLvl(3);
        return "ERROR";
    }

    if((ptr = popen(cmd, "r")) != NULL){
        while (fgets(buf, BUFSIZ, ptr) != NULL){
            fprintf(file, "%s", buf);
        }
        pclose(ptr);
    }
    fclose(file);

    std::ifstream input("buffer.txt");
    c = 0;

    if(!input){
        this->setErrLvl(4);
        return "ERROR";
    }

    while(!input.eof()){
        std::getline(input, line);
        if(c == 1 && line.size() > 1){
            input.close();
            entry = QString::fromUtf8(line.data(), line.size());
            return entry;
        }
        c++;
    }
    input.close();
    std::remove("buffer.txt");
    return "Could not return Username.";
}

就像我说的:只是有点不切实际。

该方法获取带有 IP 地址的 QString,将其与 wmic.exe /node:computersystem get username 2> nul 组合并将 wmic.exe 的输出写入文本文件,读取所需行(第二个),将字符串缩短为必要的信息和returns表示的信息(the User-name)

现在我的问题如下:如果我只想在运行时获得一个用户名左右,这一切都很好而且花花公子......我不想。我需要填写整个 table(最多包含 200 个或更多条目,具体取决于网络 activity),这需要 10 到 15 分钟。

现在我的程序通过套接字处理获取 IP 和计算机名集合,但我是这种类型的编程的新手(坦白说:我刚开始使用 C++,我从未做过任何与网络相关的编程工作)所以我我不是很在意这件事。

有没有办法通过套接字获取远程计算机上当前登录的用户名?

您可以使用 QProcess 来处理 wmic.exe 工具,如下所示:

void NetworkHandle::getUserName(QString entry)
{
    QProcess *wmic_process = new QProcess();
    wmic_process->setProgram("wmic.exe");
    wmic_process->setArguments(QStringList() << QString("/node:%1").arg(entry) << "computersystem" << "get" << "username");
    wmic_process->setProperty("ip_address", entry);

    connect(wmic_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(parseUserName(int,QProcess::ExitStatus)) );
    wmic_process->start();
}

void NetworkHandle::parseUserName(int exitCode, QProcess::ExitStatus exitStatus)
{
    QProcess *process = dynamic_cast<QProcess*>(sender());
    if (exitStatus == QProcess::NormalExit)
    {
        qDebug() << "information for node" << process->property("ip_address").toString();
        qDebug() << process->readAllStandardOutput();
    }
    process->deleteLater();
}