0

How can I log in with the su command in one line in the terminal? I know that the sudo command can do that:

echo [password] | sudo -S [command]

But when I try to imply it in the su command :

echo [password] | su [username]

I get an error:

standard in must be tty

I don't have access to the sudo account (so I can't access and edit the sudoers file).

I know that the right syntax is basically:

su [username]

What I want to do is to add a su command to aliases without being needed to enter password every time

  • 2
    you can't, the error message is pretty clear; see also larsks' answer here – don_crissti Jul 5 '16 at 10:52
  • The synatax is incorrect for su – LXGA Jul 5 '16 at 11:34
0

The correct answer is:
THIS IS DANGEROUS ! DO NOT DO THIS ! IT COMPLETELY BREAKS YOUR SECURITY !!!

But...
If you don't care about security you can do it like this:

  • Create a file main.c with the contents:
#include <stdlib.h>
#include <unistd.h>

int main() {
  setuid(0);
  system("/bin/bash"); //you can replace bash by another shell if wanted
  return 0;
}
  • Compile this code and transform it into a suid shell with:
gcc main.c -o mysuidshell
sudo chown root mysuidshell && sudo chmod u+s mysuidshell

You can now create the alias that you mentinoed in the comment on LXGA's answer:

alias switch="/path/to/mysuidshell".

Although it's still terrible idea security-wise, you also have the extremely tiny advantage that your password is not somewhere visible in cleartext.

Depending on what you want to do you can change the code so that it can change to other users than root, run different shells, ...

But you will be basically re-inventing the wheel (su and sudo) but less secure.

0

This is exactly what Expect was designed for. It was written originally for Tcl/Tk, but I'm not terribly au fait with that language, so here it is in Python:

#!/usr/bin/python3
import os,sys,pexpect

child = pexpect.spawn("sudo head /etc/shadow")

# Give it a list of expected responses (only one here)    
Result = child.expect([" password for"])

# Did we find the zeroth answer in our list?
if Result==0:
    # Yes, then send the password
    child.sendline('<your password>')
    # Output its response
    print(child.read())
else:
    print("Didn't get expected response")

You'll have to edit it to suit your purpose, hopefully that's enough to get you started.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.