如何使用C程序在命令propmt上传递命令?
我想从我的C程序通过一些命令,下面是示例程序:如何使用C程序在命令propmt上传递命令?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
FILE *ssh = popen("ssh [email protected]", "w");
pid_t pid;
pid = fork();
if(!ssh)
{
fprintf(stderr, "Could not open pipe for output.\n");
}
if (pid==0){
fprintf(stdout, "Child process properly created.\n");
fputs("user", ssh);
fputc('\n', ssh); // enter key
_exit(0);
}
fprintf(stdout, "Exit from child process.\n");
pclose(ssh);
return 0 ;
}
现在,当我运行这个程序,它要求密码在命令提示符下是这样的:
[email protected]'s password:
我想从我的示例程序中传递密码,而不是从命令提示符处传递密码。 任何人都可以请告诉我如何以编程方式在C中执行此操作。
SSH仅用于例子。也可以用于其他场景。
感谢, Yuvi
这是可能的,但需要更多的代码。首先,您需要使用fork()
而不是system()
加上exec*()
调用之一来用您想要运行的命令替换子进程。
有关详情,请点击这里或见Unix Programming Frequently Asked Questions,特别1. Process Control和1.5 How can a parent and child process communicate?
虽然(我认为)他也想“输入密码”,所以这也需要一些文件描述符来摆弄。 – dreamlax 2012-03-16 10:28:58
我觉得ssh
命令读取从stdin
密码,在这种情况下,你需要管密码进入程序,并为这可以使用popen
。 C99/POSIX示例:
#include <stdio.h>
int main()
{
FILE *ssh = popen("ssh [email protected]", "w");
fputs("p4ssw0rd", ssh);
fputc('\n', ssh); // enter key
pclose(ssh);
}
未经测试。使用fork
/exec
/dup
等组合可能会有更好的运气。
当它是ssh很多简化设置ssh密钥,因此您不必添加密码。但是,如果你真的想这样做,使用api命名expect是很容易的。我一直在用自己的成果。
你会请编辑您的答案以添加关于您提到的api的信息? – Freakyuser 2013-03-14 08:16:11
如果你的问题是关于'ssh'界面的话,我建议你在superuser.com上提问。 – pmg 2012-03-16 10:08:32
不,它与sssh无关 – Yuvi 2012-03-16 10:13:13
不,这不仅仅与ssh有关,我仅以ssh为例。有很多情况下,当你使用系统函数启动任何命令时,它会要求提供一些参数。 – Yuvi 2012-03-16 10:43:57