變換使用者

應用說明

    • 本程式為由較高權限者〈如:root〉轉換為另一群組〈如:dasadm1〉下用戶〈如:dasusr1〉執行寫檔,再轉回原群組、原用戶、原目錄。
      • 轉換群組:GID = 101
      • 轉換用戶:UID = 501
      • 轉換家目錄:/home/dasusr1
      • [rich.lee@localhost src]$ sudo cat /home/dasusr1/myFile.dat NOW:Mon Oct 4 17:59:34 2010 [rich.lee@localhost src]$ ls -l /home/dasusr1/myFile.dat
      • -rw-r--r-- 1 dasusr1 dasadm1 30 Oct 4 17:59 /home/dasusr1/myFile.dat
  • 進階說明

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <string.h> #include <time.h> struct INFO { char homeDir[128]; uid_t UID; gid_t GID; } currentInfo, targetInfo; int main(void) { char *fileName = "myFile.dat"; FILE *fp; time_t nowTime; time(&nowTime); memset(&targetInfo, 0, sizeof(struct INFO)); memset(&currentInfo, 0, sizeof(struct INFO)); targetInfo.UID = 501; targetInfo.GID = 101; strcpy(targetInfo.homeDir, "/home/dasusr1"); currentInfo.UID = getuid(); currentInfo.GID = getgid(); getcwd(currentInfo.homeDir, sizeof(currentInfo.homeDir)); if (setgid(targetInfo.GID) != -1) { if (setuid(targetInfo.UID) != -1) { chdir(targetInfo.homeDir); fp = fopen(fileName, "w"); if (fp != NULL) { fprintf(fp, "NOW:%s\n", ctime(&nowTime)); fclose(fp); } else { perror(fileName); } } else { perror(fileName); } setgid(currentInfo.GID); setuid(currentInfo.UID); chdir(currentInfo.homeDir); } return EXIT_SUCCESS; }