How to make sudo command using Paramiko

I am having some problems with commands that use sudo with paramiko
f.ex sudo apt-get update

here is my code:

try:
    import paramiko
except:
    try:
        import paramiko
    except:
        print "There was an error with the paramiko module"
cmd = "sudo apt-get update"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
    ssh.connect("ip",username="lexel",password="password")
    print "succesfully conected"
except:
    print "There was an Error conecting"
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('password\n')
stdin.flush()
print stderr.readlines()
print stdout.readlines()

This is a quick code. I know that I need to add sys.exit (1) and all this, but this is just for demonstration

I used this for reference: Jessenoller.com

+5
source share
2 answers

Fabrichas a team sudo. It uses Paramico for ssh connections. Your code will look like this:

#fabfile.py
from fabric.api import run, sudo

def update():
    """Run `sudo apt-get update`.

    lorem ipsum
    """
    sudo("apt-get update")

def hostname():
    """Run `hostname`"""
    run("hostname")

Using:

$ fab update -H example.com
[example.com] Executing task 'update'
[example.com] sudo: apt-get update
...snip...
[example.com] out: Reading package lists... Done
[example.com] out: 

Done.
Disconnecting from example.com... done.

$ fab --display update
Displaying detailed information for task 'update':

    Run `sudo apt-get update`.

        lorem ipsum

$ fab --list
Available commands:

    hostname  Run `hostname`
    update    Run `sudo apt-get update`.

From the docs :

fab, Fabrics Python, Pythonic SSH , , , , ( ).

+1

, :

sudo :

: your_username! requiretty

requiretty.

, sudo.

+1

All Articles