Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a sudo command using Paramiko

I am having some problems with commands that have sudo using 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 that but this is just to demostration

I used this for reference: Jessenoller.com

like image 459
LeXeL Avatar asked Nov 06 '22 03:11

LeXeL


2 Answers

Fabric has sudo command. It uses Paramico for ssh connections. Your code would be:

#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")

Usage:

$ 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:

In addition to use via the fab tool, Fabric’s components may be imported into other Python code, providing a Pythonic interface to the SSH protocol suite at a higher level than that provided by e.g. Paramiko (which Fabric itself leverages.)

like image 94
jfs Avatar answered Nov 09 '22 10:11

jfs


I was having the same problem, and I fix with this:

In your sudo file, just add this:

Defaults:your_username !requiretty

or remove Defaults requiretty.

Also make sure your user have permission to run the command with sudo.

like image 38
Arx Cruz Avatar answered Nov 09 '22 09:11

Arx Cruz