如何从C进入chroot环境? [英] howto Enter into chroot environment from C?

查看:58
本文介绍了如何从C进入chroot环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是让我的程序进入chroot环境并执行一些命令,然后退出.

what i am try to do is to get my program to enter chroot environment and do some commands and then exit.

例如

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

#define ChRoot "sudo  chroot \"/\" /usr/bin/env -i HOME=/root TERM=\"$TERM\" PATH=/bin:/usr/bin:/sbin:/usr/sbin:/bin /bin/bash --login +h"


void func1(){
    //enter the chroot environment
    char line[130];   FILE *fp;
    fp = popen(ChRoot, "r");
    while(fgets( line, sizeof line, fp)){
        printf ("%s\n",line);
    }
    pclose(fp);
}
void func2(){
    //run a command in  the chroot environment
    char line[130];   FILE *fp;
    fp = popen("ls", "r");
    while(fgets( line, sizeof line, fp)){
        printf ("%s\n",line);
    }
    pclose(fp);

}
int main() {
    func1();
    func2();
    return 0;
}

此代码的问题是,它将使我进入chroot环境,但是直到我退出chroot环境后,它才会启动func2.我需要的是让我的代码在chroot环境中执行func1然后在func2中执行然后退出.我知道我在代码中执行的操作是完全错误的,但是,我希望我能得到一些指导.

the problem with this code is, it will get me in the chroot environment however it will not fire func2 until i exit form the chroot environment. What i need is to get my code to do func1 and then func2 in chroot environment and then exit.I know what i am doing in my code is horribly wrong, however, i hope i could get some directions .

任何帮助将不胜感激.

推荐答案

如果您使用的是C语言并且想要输入chroot,则可以直接使用chroot()函数进行输入:

If you're in C and you want to enter a chroot you can do so directly using the chroot() function:

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

int main(void) {
     FILE *f;

     /* chroot */
     chdir("/tmp");
     if (chroot("/tmp") != 0) {
         perror("chroot /tmp");
         return 1;
     }

     /* do something after chrooting */
     f = fopen("/etc/passwd", "r");
     if (f == NULL) {
         perror("/etc/passwd");
         return 1;
     } else {
         char buf[100];
         while (fgets(buf, sizeof(buf), f)) {
              printf("%s", buf);
         }
     }
     return 0;
}

请注意,如果您在chroot之前没有设置当前目录,则有可能脱离chroot.

Note that if you don't set the current directory before chrooting it's possible to break out of the chroot.

这篇关于如何从C进入chroot环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆