linux 修改openwrt ntp服务器

修改openwrt ntp 服务器的demo

系统ntp配置文件如下:

config system
        option hostname 'OpenWrt'
        option zonename 'Asia/Shanghai'
        option timezone 'CST-8'
        option conloglevel '8'
        option cronloglevel '5'
        option log_file '/mnt/usr/log/system.log'
        option log_size '2048'
        option log_buffer_size '1024'
        option log_ip '192.168.178.100'
        option log_port '6666'

config timeserver 'ntp'
        list server '0.openwrt.pool.ntp.org'
        list server 'cn.ntp.org.cn'
        list server 'cn.pool.ntp.org'
        list server 'pool.ntp.org'
        option enabled '1'


#include

#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{   
    if (argc < 3)
    {
        printf("two few argument \n");
        return -1;
    }
    else
    {
        printf("file name is %s , add server is %s argc is %d \n", argv[1], argv[2], argc);
    }
    FILE *fd;
    fd = fopen(argv[1], "r+");
    if (fd == NULL)
    {
        printf("can not open file %s \n", argv[1]);
        return -1;
    }
    struct stat fileStat;
    stat(argv[1], &fileStat);
    printf("file size if %d \n", fileStat.st_size);
    unsigned char *fbuf = (unsigned char *)malloc(fileStat.st_size);
    memset(fbuf, 0, fileStat.st_size);
    char buf[256] = {0};
    char server[10][100] = {{0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}};
    int list = 0;
    while(fgets(buf, 256, fd) != NULL)
    {
        if (strstr(buf, "list server"))
        {
            strcpy(server[list], strstr(buf, "list server") + 13);
            server[list][strlen(server[list]) - 2] = '\0';
            printf("server id is %d is %s \n", list, server[list++]);
        }
        if (strstr(buf, "option enabled"))
        {
            printf("ntp file end %s \n", buf);
            break;
        }
        strcat(fbuf, buf);
        memset(buf, 0, 256);
    }
    system("rm /etc/config/system");
    FILE *fdNew;
    fdNew = fopen(argv[1], "w");
    if (fdNew == NULL)
        return -1;
    fwrite(fbuf, strlen(fbuf), 1, fdNew);
    char buf1[256] = {0};
    for (list = 0; list < argc - 2; list++)
    {
        sprintf(buf1, "\tlist server '%s'\n", argv[2+list]);
        printf("add server is %s \n", buf1);
        fwrite(buf1, strlen(buf1), 1, fdNew);
        memset(buf1, 0, sizeof(buf1));
    }
    fwrite(buf, strlen(buf), 1, fdNew);

    fclose(fdNew);
    fclose(fd);
    free(fbuf);
    system("reboot");

 }

你可能感兴趣的:(linux)