Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run sudo with Paramiko? (Python)

What I've tried:

  1. invoke_shell() then channel.send su and then sending the password resulted in not being root
  2. invoke_shell() and then channel.exec_command resulted in a "Channel Closed" error
  3. _transport.open_session() then channel.exec_command resulted in not being root
  4. invoke_shell() then writing to stdin and flushing it resulted in not being root
like image 703
Takkun Avatar asked Jun 07 '11 19:06

Takkun


People also ask

How do I use Paramiko in python?

A Paramiko SSH Example: Connect to Your Server Using a Password. This section shows you how to authenticate to a remote server with a username and password. To begin, create a new file named first_experiment.py and add the contents of the example file. Ensure that you update the file with your own Linode's details.

Does Paramiko use OpenSSH?

Paramiko does not itself leverage OpenSSH-style config file directives, but it does implement a parser for the format, which users can honor themselves (and is used by higher-level libraries, such as Fabric).

What is a Paramiko in python?

Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement for SSL to make a secure connection between two devices. It also supports the SFTP client and server model.

What is Paramiko transport?

class paramiko.Transport. An SSH Transport attaches to a stream (usually a socket), negotiates an encrypted session, authenticates, and then creates stream tunnels, called Channels, across the session. class paramiko.SSHClient. A high-level representation of a session with an SSH server.


2 Answers

check this example out:

ssh.connect('127.0.0.1', username='jesse', 
    password='lol')
stdin, stdout, stderr = ssh.exec_command(
    "sudo dmesg")
stdin.write('lol\n')
stdin.flush()
data = stdout.read.splitlines()
for line in data:
    if line.split(':')[0] == 'AirPort':
        print line

Example found here with more explanations: http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/

Hope it helps!

like image 96
W0bble Avatar answered Oct 10 '22 07:10

W0bble


invoke_shell worked for me like this:

import paramiko, getpass, re, time

ssh_client = paramiko.SSHClient()   
ssh_client.connect( host )
sudo_pw = getpass.getpass("sudo pw for %s: " % host)
command = "sudo magicwand"

channel = ssh_client.invoke_shell() 
channel.send( command )       
# wait for prompt             
while not re.search(".*\[sudo\].*",channel.recv(1024)): time.sleep(1)
channel.send( "%s\n" % sudo_pw )
like image 39
seelaman Avatar answered Oct 10 '22 07:10

seelaman