Get Process Username c++

与世无争的帅哥 提交于 2019-12-08 07:29:31

问题


i am making a taskmanager like app. for windows,i can get all the system processes,now i want to get process's username.I got the code from net.

void enableDebugPrivileges()
{
    HANDLE hcurrent=GetCurrentProcess();
    HANDLE hToken;
    BOOL bret=OpenProcessToken(hcurrent,40,&hToken);
    LUID luid;
    bret=LookupPrivilegeValue(NULL,SE_LOAD_DRIVER_NAME, &luid);
    TOKEN_PRIVILEGES NewState,PreviousState;
    DWORD ReturnLength;
    NewState.PrivilegeCount =1;
    NewState.Privileges[0].Luid =luid;
    NewState.Privileges[0].Attributes=2;
    AdjustTokenPrivileges(hToken,FALSE,&NewState,28,&PreviousState,&ReturnLength);
}

char *GetProcessUsername(HANDLE *phProcess, BOOL bIncDomain) 
{
    static char sname[300];
    HANDLE tok = 0;
    HANDLE hProcess;
    TOKEN_USER *ptu;
    DWORD nlen, dlen;
    char name[300], dom[300], tubuf[300], *pret = 0;
    int iUse;

    //if phProcess is NULL we get process handle of this
    //process.
    hProcess = phProcess?*phProcess:GetCurrentProcess();

    //open the processes token
    if (!OpenProcessToken(hProcess,TOKEN_QUERY,&tok)) goto ert;

    //get the SID of the token
    ptu = (TOKEN_USER*)tubuf;
    if (!GetTokenInformation(tok,(TOKEN_INFORMATION_CLASS)1,ptu,300,&nlen)) goto ert;

    //get the account/domain name of the SID
    dlen = 300;
    nlen = 300;
    if (!LookupAccountSidA(0, ptu->User.Sid, name, &nlen, dom, &dlen, (PSID_NAME_USE)&iUse)) goto ert;


    //copy info to our static buffer
    if (dlen && bIncDomain) {
    strcpy(sname,dom);
    strcat(sname,"");
    strcat(sname,name);
    } else {
    strcpy(sname,name);
    }
    //set our return variable
    pret = sname;

    ert:
    if (tok) CloseHandle(tok);
    return pret;
}
int main(){
    enableDebugPrivileges();
    DWORD dwPID=3436;        
    HANDLE  hProcess_i = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwPID);
    printf("%s",GetProcessUsername(&hProcess_i,0));
}

Its working well for system and curr. user processes but not for NETWORK SERVICE and LOCAL SERVICES and i got null string.please tell how can i get usernames of these processes too. thanks.


回答1:


IIRC there's a separate pseudo account called LocalService, but its not in the normal security system (hence you get a null string). There's also a NetworkService account.



来源:https://stackoverflow.com/questions/4800924/get-process-username-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!