开发者

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 updat开发者_开发知识库e"
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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜