Ani
Ani

Reputation: 1536

Trying to force run `su' in a pty

I have a shell, where I switch to another user with su -l anotheruser, this mostly works But when there is no pty allocated to su, it errors out with:

su: must be run from a terminal

So, I tried to wrap su with code to create a pty:

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

int main (int argc, char *argv[])
{
    int fd;
    char* args[] = {"/bin/su", "-l", "anotheruser", NULL };
    char name[16] = {0};
    int pid ;

    pid = forkpty(&fd, name, NULL, NULL);
    if (pid != -1) {
        printf("\n pty: [%s]\n", name);
        if (execve(args[0], args, NULL) == -1) {
            printf("\n execve: failed\n");
        }
    } else {
        printf("\n forkpty: failed \n");
    }

    return 0;
}

But this doesn't seem to work.. I am missing something here, but not able to make out.. do I have to redirect stdin/stdout before execve()?

Upvotes: 1

Views: 86

Answers (1)

ticktalk
ticktalk

Reputation: 942

use execvp as it uses environment settings

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

int main (int argc, char *argv[])
{
    int fd;
    char* args[] = {"/bin/su", "anotheruser", "-l", "-P", NULL };
    char name[16] = {0};
    int pid ;

    pid = forkpty(&fd, name, NULL, NULL);
    if (pid != -1) {
        printf("\npty:[%s], TERM:%s\n", name, getenv("TERM") );
        if (execvp(args[0], args ) == -1) {
            perror("\nexecvp failed\n");
        }
    } else {
        printf("\n forkpty: failed \n");
    }

    return 0;
}

Upvotes: 2

Related Questions