TransWikia.com

Logging in with 'su' without entering a password

Unix & Linux Asked by user3561602 on October 31, 2021

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 Answers

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.

Answered by Philip Kearns on October 31, 2021

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.

Answered by Garo on October 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP