2014-05-22 4 views
0

을 사용하여 권한이 부여되지 않은 C 프로그램 내에서 root로만 쓸 수있는 /etc의 파일에 쓰려고합니다. .루트 권한을 가진 파일에`sudo`를 덧붙여 야합니다.

system("sudo /bin/sh -c 'echo 'iface wlan0 inet dhcp' >> /etc/network/interfaces'"); 

이것은 실패한 것으로 보이지 않지만 파일은 수정되지 않았습니다. 뭐가 잘못 되었 니?

+0

했나 대신에'c'라고 태그를 붙이시겠습니까? – Sayse

+0

oh thx .. wrong tag – user2906282

+0

이미 시도했지만 작동하지 않습니다. 나는 "iface wlan0 inet dhcp"행을 파일 루트 디렉토리에 추가하려고합니다. – user2906282

답변

2

당신이 그것을 가지고, 재 지정은 외부 sudo 작업을 을 평가 구조 때문에 루트 권한이없는 및 쓰기를 위해 /etc/network/interfaces를 열 수 없습니다. 이 대신처럼 작업을 수행해야합니다 리디렉션이 sudo는 내부 쉘 에 의해 평가

system("sudo /bin/sh -c \"echo 'iface wlan0 inet dhcp' >> /etc/network/interfaces\""); 

있도록.

가 (. 또한, 당신은 작은 따옴표 안에 둥지 따옴표 수 없습니다) 여기에 완성도를 위해서

+0

Thanks !! 효과가있다. – user2906282

2

, 나는 그 "는 C의 방법을"할 거라고하는 방법입니다

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

int main(void) { 
    const char string_to_append[] = "iface wlan0 inet dhcp\n"; 
    size_t string_size; 
    FILE *fd; 

    /* Check for permissions */ 
    if (getuid()) { 
     fprintf(stderr, "Run as root!\n"); 
     return EXIT_FAILURE; 
    } 

    /* Now try to open the file for appending 
    * NOTE: fopen() will fail anyway if you dont have enough 
    * permissions to open this file with the specified mode, 
    * so the above check calling getuid() is somewhat redundant 
    */ 
    if ((fd = fopen("/etc/network/interfaces", "a")) == NULL) { 
     perror("Error opening file"); 
     return EXIT_FAILURE; 
    } 

    /* Actual writing happens here */ 
    string_size = strlen(string_to_append); 
    if (fwrite(string_to_append, sizeof(char), string_size, fd) != string_size) { 
     fprintf(stderr, "Error writing to file\n"); 
     return EXIT_FAILURE; 
    } 

    return EXIT_SUCCESS; 
} 
관련 문제