pass parameter using system command

后端 未结 2 675
迷失自我
迷失自我 2021-01-21 12:28

I have an executable program that runs in several pc\'s in a network. At first it gets the host name (pc-001.. pc-013 etc). Then i need to mount a network drive (server1) on ev

2条回答
  •  不思量自难忘°
    2021-01-21 12:54

    You could build the command passed to system e.g. like

     char cmdbuf[256];
     snprintf(cmdbuf, sizeof(cmdbuf), 
              "net use x: \\\\server1\\shares /user:%s %s", 
              username, password);
     int err = system(cmdbuf);
     if (err) { fprintf(stderr, "failed to %s\n", cmdbuf); 
                exit(EXIT_FAILURE); }
    

    Be careful about the given username and password. A username like the string "user; somenaughtycommand" (without the quotes) will give you nightmares. Beware of code injections, so test that both username and password are somehow valid, or appropriately escape them. Don't forget to test the outcome of system library call.

    You could want to check the number of characters put in cmdbuf i.e. the result of snprintf. If it is >= sizeof(cmdbuf) you probably should avoid calling system!

提交回复
热议问题