pass parameter using system command

别来无恙 提交于 2019-12-02 07:23:07

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!

Use the snprintf to construct the command string before you use it:

char command[128];
snprintf(command, sizeof(command), "net use x: \\\\server1\\shares /user:%s %s",
         some_username, some_password);
system(command);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!