5

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

Jeffrey Blake
  • 9,659
  • 6
  • 43
  • 65
LeXeL
  • 51
  • 1
  • 2
  • 4
    This is, in essence, a duplicate of [Paramiko and Pseudo-tty Allocation](http://stackoverflow.com/questions/2909481/paramiko-and-pseudo-tty-allocation). I suggest you read the answer to that question :). – Andrew Aylett Feb 08 '11 at 17:03
  • Another, very similar question I answered is [here](http://stackoverflow.com/questions/6269000/why-cant-paramiko-run-this-command-python/6269567#6269567) – Spencer Rathbun Sep 27 '11 at 20:50
  • 1
    Possible duplicate of [How to run sudo with paramiko? (Python)](https://stackoverflow.com/questions/6270677/how-to-run-sudo-with-paramiko-python) – oz123 Aug 28 '17 at 18:47

2 Answers2

1

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.

Arx Cruz
  • 115
  • 1
  • 3
1

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.)

jfs
  • 399,953
  • 195
  • 994
  • 1,670