2

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 even pc's and (server2) on odds one based on its host name.

My problem is that i use system call to run dos command 'net use' for example

system ("net use x: \\\\server1\\shares /user:username pass");

How can i pass a variable to username? username is the host name which i know its value and pass is the same for all computers.

apo
  • 69
  • 2
  • 9

2 Answers2

3

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);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

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!

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547