Reputation: 39
I am trying to change the password in C Code using popen
.
On the Linux I have, on command prompt, passwd (busybox) works fine
# passwd simon
Changing password for simon
New password:
Retype password:
Password for simon changed by root
I am trying to do this within C (running as root):
int len=strlen(s_password); char line[1024];
sprintf(line,"passwd %s", s_username);
FILE *fp= popen(line,"w");
int i;
for(i=0; i<len;++i)fputc(s_password[i], fp);
for(i=0; i<len;++i)fputc(s_password[i], fp);
fputc('\n', fp);
//fprintf(fp,"%s\n",s_password);
//fprintf(fp,"%s",s_password);
pclose(fp);
I tried also fprintf
(commented) but without success. Seems like the first entry is passing but not the second. When I execute the code, I get:
Changing password for simon
New password:
Retype password:
passwd: password for simon is unchanged
I tried all possible scenarios (with '\n' omitting '\n') without success.
As if the 'Retype password' is different than the 'New password'.
What am I doing wrong?
Upvotes: 1
Views: 2416
Reputation: 53155
This util works fine for me:
#include <stdio.h>
#include <sys/wait.h>
int main(int argc, char **argv)
{
if (argc < 3) {
printf("Usage: %s username password\n", argv[0]);
return 1;
}
char cmd[32];
sprintf(cmd, " passwd %s", argv[1]);
FILE *fp= popen(cmd, "w");
fprintf(fp, "%s\n", argv[2]);
fprintf(fp, "%s\n", argv[2]);
printf("Return value: %i\n", WEXITSTATUS(pclose(fp)));
return 0;
}
gcc -Wall -Wpedantic -Wextra main.c
Upvotes: 3
Reputation: 35408
I think you should write
to fileno(fp)
instead of simple fp. That is your end of the pipe if I understood correctly the docs:
http://linux.die.net/man/3/fileno and
http://pubs.opengroup.org/onlinepubs/009696699/functions/popen.html
Upvotes: 2