如何判断当前的进程是否以root权限运行?

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/rikeyone/article/details/88723418

当前登录系统的用户叫做实际用户,而实际运行的进程是以有效用户ID来进行访问权限管理的,正常情况下有效用户就是实际用户,但是如果我们使用了sudo或者使能了设置用户ID位,
按照前面文章的介绍,这个有效用户是可能改变的,比如使用sudo执行,进程的有效用户ID就会变为root,那么此进程就相当于具有了root权限。如果我们的程序只允许使用root运行,那么该如何设计呢?

C语言程序设计

#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    if (geteuid() == 0)
        printf("Run as root, euid:%ld\n", (long) geteuid());
    else
        printf("Not Run as root, euid:%ld\n", (long) geteuid());

    return 0;
}

euid为0说明当前的有效用户ID就是root。运行结果如下:

$ ./euid 
Not Run as root, euid:1000
$ sudo ./euid 
Run as root, euid:0

shell脚本设计

#!/bin/bash

echo ${USER},${UID}

if [ ! x"${USER}" = x"root" ];then
    echo "Please rerun `basename $0` as root" 
    exit 1
else
    echo "Run as root"
fi

shell脚本中可以通过查看环境变量USERUSER和UID来判断是否是使用root权限来运行该脚本。
运行结果如下:

$ ./check_root.sh 
xiehaocheng,1000
Please rerun check_root.sh as root
$ sudo ./check_root.sh 
root,0
Run as root
展开阅读全文

判断一个进程是否运行

08-16

贴出代码如下:rn#include rn#include rn#include rn#include rnrnusing namespaces std;rnrnvoid main()rnrn string M_ProcessID="qq.exe";rn DWORD lpidProcesses[1024], cb = 0, cbNeeded = 0;rn HMODULE lphMods[1024];rn HANDLE hProcess = NULL;rn char szProcessID[MAX_PATH];rnrn memset(lpidProcesses, 0, sizeof(lpidProcesses));rn memset(lphMods, 0, sizeof(lphMods));rn memset(szProcessID, 0, sizeof(szProcessID));rnrn if ( !::EnumProcesses( lpidProcesses, sizeof(lpidProcesses), &cb ) )rn rn cout << " error " ;rn return ;rn rnrn for(int i=0; i< (int) (cb / sizeof(DWORD)); i++)rn rn memset(szProcessID, 0, sizeof(szProcessID));rn hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, lpidProcesses[i]);rn ::EnumProcessModules(hProcess, lphMods, sizeof(lphMods), &cbNeeded);rn ::GetModuleFileNameEx( hProcess, lphMods[0], szProcessID,sizeof(szProcessID));rn CloseHandle(hProcess);rn rnrn if (!strcmp(szProcessID,M_ProcessID))rn rn cout << "The process has opened!" ;rn rn elsern rnrn cout <<"The process need to open!" << endl;rn rnrnrnrn错误提示:rn1>c:\program files\microsoft visual studio 8\vc\platformsdk\include\winbase.h(226) : error C2146: syntax error : missing ';' before identifier 'Internal'rn1>c:\program files\microsoft visual studio 8\vc\platformsdk\include\winbase.h(226) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-intrn1>c:\program files\microsoft visual studio 8\vc\platformsdk\include\winbase.h(226) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-intrn……………………rn(下面都是类似的错误)rnrnwinbase.h文件中的部分:rntypedef struct _OVERLAPPED rn ULONG_PTR Internal; //226行rn ULONG_PTR InternalHigh;rn union rn struct rn DWORD Offset;rn DWORD OffsetHigh;rn ;rnrn PVOID Pointer;rn ;rnrn本人小白,rn代码也是参考网上的弄出来的,错误提示让我很不明白,应该是和是否用MFC有关……rn还望大神指导! 论坛

没有更多推荐了,返回首页