Skip to content
Advertisement

fabric — cant run commands after user is switched

I have been recently introduced to fabric and trying to approach the following:

  1. access remote host
  2. su root
  3. perform a command, for example change password for multiple users
  4. done! Please note that I cant use sudo, nor connect directly to the remote host using root. The commands I need to perform can only be performed if I explicitly change user to root.

I was able to approach the main concept of getting to the remote host and play with some commands, using fabric, but the problem im having is that once I switch to root “su root” I cant perform the rest of the commands unless I exit.

example of what im trying to approach:

def mytask():
    with settings(user="root"):
        run('whoami')
        run('echo "TEST using root user"')
        run('echo "ITS WORKING!!!"')

or something like this

def mytask():
    run ('su root')
    run ('passwd testUser')

In both cases once I enter the root password nothing would get executed, I would get the remote command line back, unless I exit back to the original user. I have seen few suggestions about using “fexpect” for prompts but not sure if that would make a difference.

I’m developing on a Linux environment.

Advertisement

Answer

You have to use fexpect and fexpect run command

from ilogue import fexpect

prompt = ['Password', 'mypassword']  # ('prompt', 'answer') Case sensitive

def test():
    with fexpect.expecting(prompt):
        fexpect.local("su -")
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement