LQ Newbie
Registered: Jun 2007
Posts: 27
Rep:
|
feteching file from remote system using scp through a C programme.
Hi,
I need to fetch a file from remote system using scp through a C programme.(basically not to enter passwd manually)
As we need to capture the prasswd promting in the programme i using the pipe.
Here is the my sample progrmme.
bool getRemoteFile(char *ip,char *user,char *passwd,char *srcFile,char *dstFile,char *errBuf)
{
char *exe = "/usr/bin/scp";
int result=0,ret = 0, pid=0;
int write_stdin[2], read_stdout[2];
char response[512];
char inputString[1024];
char *argv[10] = {exe,inputString,dstFile,NULL};
snprintf(inputString, 1023, "%s@%s:%s", user,Ip, srcFile);
pipe(write_stdin);
pipe(read_stdout);
/* Fork the process */
pid = fork();
switch (pid) {
case 0: /* Child process */
close(write_stdin[1]);
close(read_stdout[0]);
/* Replace stdin and stdout with the new fds */
dup2(write_stdin[0], STDIN_FILENO);
dup2(read_stdout[1], STDERR_FILENO);
dup2(read_stdout[1], STDOUT_FILENO);
close(write_stdin[0]);
close(read_stdout[1]);
execvp(exe, argv);
_exit(0);
break;
case -1: /* fork() error */
Log("Fork() error for host:%s, cmd:scp, user:%s", Ip,user);
break;
default: /* Parent process */
/* Close unneeded fds */
close(write_stdin[0]);
close(read_stdout[1]);
struct pollfd waitfordata[1];
waitfordata[0].fd=read_stdout[0];
waitfordata[0].events=POLLIN;
sleep(1);
int status;
int waittime=1;
// result = talkToIDPDevice(waitfordata,read_stdout[0], write_stdin[1], idpdevice->password);
do {
int err = poll(waitfordata, 1, 60000);
if (err == -1){
strncpy(errBuf,"poll failed failed",strlen("poll failed failed"));
return false;
}else{
if(err == 0 && waittime > 5 ){
/* Connection Timed Out
killl the child process
*/
kill(pid,9);
strncpy(errBuf,"Connection Timed Out",strlen("Connection Timed Out"));
return false;
}else{
memset(response,0,512);
read(read_stdout[0],response,511); /* process the buffer*/
if(strstr(response,"(yes/no)") == 0 ){
write(write_stdin[1],"yes",3);
write(write_stdin[1],"\n",2);
continue;
}else if(strstr(response,"password:") == 0 ){
write(write_stdin[1],passwd,strlen(passwd));
write(write_stdin[1],"\n",2);
break;
}
}
}
waittime++;
}while(1);
/* *call wait pid */
close(write_stdin[1]);
close(read_stdout[0]);
}
}
Generally using above programme we can execute a command in child and capture the output that command in parent.
Similarly i tried using scp command so that passwd prompting will received in the parent , but passwd prompting is going to STDOUT.
Why scp output was not captured in the parent.
Please help me.
Regards,
Ravikumar
|