您的位置:首页 > 运维架构 > Linux

linux password重定向stdin 【用于在程序中修改系统密码】

2009-07-06 00:24 489 查看
今天 因为项目的需求,希望能通过C程序修改 使用者的密码,而不是通过终端,在GOOGLE了半天后

最开始是希望能找到passwd的源码从而不通过命令调用修改,然而始终是比较困难,后来不知道在哪里找到了对应的源码包【至于在那里找,可自己GOOGLE -_- 】

shadow-4.0.3.tar

可惜修改密码的函数并不好找 'v'

后来偶然发现可从定向passwd的输入:

http://www.lslnet.com/linux/f/docs1/i21/big5196970.htm

但是他上面的程序并不正确:

1、你的程序要有足夠的權限改GUEST的密碼
2、execl之後,你的程序就完全被改了,你應該用fork一個新進程來做這事。
3、既然又FORK,又EXECL,何不popen呢?

不說其他的,就說說execl,你的程序只有execl執行失敗了才會走到下面這裡:
write( from[1], pass, sizeof(pass));
write( from[1], pass, sizeof(pass));
如果execl執行成功write根本走不到

他的代码如下:

#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main()
{
int from[2];
char buf[80];
char pass[] = "0000/n";
char s[] = "hello/n";

pipe( from );
close( from[0] );
dup( 0 );

execl("/bin/passwd", "passwd", "guest", (char *)0);

write( from[1], pass, sizeof(pass));
write( from[1], pass, sizeof(pass));

}


根据达人提供的思路

3、既然又FORK,又EXECL,何不popen呢?

我写了代码如下:

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main()
{
FILE * stream;
char user_name[]="mike";
char cmd[50];
char pwd[]="111111/n";		// /n is important

//create cmd
sprintf(cmd,"/usr/bin/passwd --stdin %s  > /dev/null ",user_name);	//--stdin:因为passwd(1)默認不允許從stdin輸入口令,必須從終端輸入才行。
stream = popen(cmd, "w" );							//cmd命令的输入来自管道的FILE* stream
fwrite(pwd, 1, strlen(pwd), stream);				//将pwd中的数据写到FILE    *wstream对应的流中,也是写到文件中
fwrite(pwd, 1, strlen(pwd), stream);
pclose(stream);
}


注意:起初我忘记了加上/n

char pwd[]="111111/n";		// /n is important


而导致修改时候显示是成功的,但是并没有修改对:

[root@Mike /down]# ./pwd
Changing password for user mike.
passwd: all authentication tokens updated successfully.
[root@Mike /down]#
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: