使用系统命令传递参数 [英] pass parameter using system command

查看:142
本文介绍了使用系统命令传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个PC的网络中运行的可执行程序。
起初,它得到的主机名(PC-001 .. PC-013等)。然后,我需要根据其主机名安装赔率一个在连PC的网络驱动器(服务器)和(服务器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.

我的问题是,我使用系统调用运行DOS命令NET USE例如:

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.

推荐答案

您可以建立传递给命令系统例如像

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); }

要小心给定的用户名密码。 A 用户名像字符串用户; somenaughtycommand(不带引号)会给你的噩梦。谨防 code注射的,所以测试既用户名密码在某种程度上有效,或者适当地逃离他们。不要忘记测试系统库调用的结果。

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.

您可能要检查放在 cmdbuf 的snprintf 。如果是>!= sizeof的(cmdbuf)你应该避免调用系统

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!

这篇关于使用系统命令传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆