How to make a sudo command using Paramiko

混江龙づ霸主 提交于 2019-12-22 05:59:25

问题


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


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




回答2:


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.



来源:https://stackoverflow.com/questions/4934572/how-to-make-a-sudo-command-using-paramiko

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!