應用說明:
/* * TaskMgr.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <string.h> #include <sys/wait.h> #include <errno.h> struct INFO { gid_t GID; uid_t UID; }; char *runnerHomeDir = "/home/rich.lee/Workspace/UserShell/src"; char *runnerShell = "UserShell2"; void runShell(struct INFO *newInfo) { char shellCmd[64]; memset(shellCmd, 0, sizeof(shellCmd)); sprintf(shellCmd, "%s/%s %d %d", runnerHomeDir, runnerShell, newInfo->GID, newInfo->UID); system(shellCmd); } int main(int argc, char *argv[]) { struct INFO newInfo; while (1) { printf("GID="); scanf("%d", &newInfo.GID); if (newInfo.GID == -1) break; printf("UID="); scanf("%d", &newInfo.UID); runShell(&newInfo); } }
/* * UserShell2.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <string.h> #include <sys/wait.h> #include <errno.h> char *cmd = "/usr/local/bin/getID"; struct INFO { gid_t GID; uid_t UID; }; int getEnv(int argc, char *argv[], struct INFO *newInfo) { int ret = -1; if (argc < 2) return ret; newInfo->GID = atoi(argv[1]); newInfo->UID = atoi(argv[2]); ret = 0; return ret; } void userTask(struct INFO *newInfo) { if (setgid(newInfo->GID) != -1) { if (setuid(newInfo->UID) != -1) { system(cmd); } else { perror("userTask::setuid() Error"); } } else { perror("userTask::setgid() Error"); } } int main(int argc, char *argv[]) { struct INFO newInfo; if (getEnv(argc, argv, &newInfo)) return EXIT_FAILURE; userTask(&newInfo); return EXIT_SUCCESS; }
/* * getID.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <string.h> struct INFO { uid_t UID; gid_t GID; } currentInfo; int main(void) { memset(¤tInfo, 0, sizeof(struct INFO)); currentInfo.UID = getuid(); currentInfo.GID = getgid(); printf("%d:%d\n", currentInfo.GID, currentInfo.UID); system("whoami;id"); return EXIT_SUCCESS; }