How to run sudo with Paramiko? (Python)
What I've tried:
invoke_shell()
thenchannel.send
su
and then sending the password resulted in not being rootinvoke_shell()
and thenchannel.exec_command
resulted in a "Channel Closed" error_transport开发者_如何学Go.open_session()
thenchannel.exec_command
resulted in not being rootinvoke_shell()
then writing to stdin and flushing it resulted in not being root
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!
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 )
AlexS
Fine tuned answer (which I am now using it in production) would be:
def sudo_run_commands_remote(command, server_address, server_username, server_pass, server_key_file):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=server_address,
username=server_username,
password=server_pass,
key_filename=server_key_file)
session = ssh.get_transport().open_session()
session.set_combine_stderr(True)
session.get_pty()
session.exec_command("sudo bash -c \"" + command + "\"")
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
stdin.write(server_pass + '\n')
stdin.flush()
print(stdout.read().decode("utf-8"))
Remove the key_filename
part of connect
method if you dont use a key file and in contrast if you only use a key without password, remove the password
part.
Some notes about this is that, it is multi command capable. Meaning that is is running a bash
as root
so you can as much commands as you can in a single run with just separating them with ;
.
You Can use channel to send sudo password:
passwd = getpass.getpass()
ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
ssh.load_system_host_keys()
ssh.connect(host, allow_agent=True)
chan = ssh.get_transport().open_session()
chan.get_pty()
chan.setblocking(1)
chan.exec_command("sudo -k dmesg")
while chan.recv_ready()==False:
stdout=chan.recv(4096)
if re.search('[Pp]assword', stdout):
chan.send(passwd+'\n')
time.sleep(1)
while chan.recv_ready():
stdout += chan.recv(20000)
chan.close()
ssh.close()
Im sorry i dont have time for details answer but i was able to implement sudo commands on paramiko using this advise
import paramiko
l_password = "yourpassword"
l_host = "yourhost"
l_user = "yourusername"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(l_host, username=l_user, password=l_password)
transport = ssh.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
#for testing purposes we want to force sudo to always to ask for password. because of that we use "-k" key
session.exec_command("sudo -k dmesg")
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
#you have to check if you really need to send password here
stdin.write(l_password +'\n')
stdin.flush()
for line in stdout.read().splitlines():
print 'host: %s: %s' % (l_host, line)
I came up with this:
def ssh_command(ssh_client, command, sudo=False):
"""Like SSHClient.exec_command, but raises if the command fails.
Otherwise, the stdout result is returned as a string.
"""
nbytes = 4 * 2e20 # 4 MiB
with ssh_client.get_transport().open_session() as channel:
command = 'sudo ' + command if sudo else command
if sudo:
channel.set_combine_stderr(True)
channel.get_pty()
channel.exec_command(command)
if sudo:
while not channel.recv_ready():
stdout = channel.recv(nbytes).decode('UTF-8')
if re.search('[Pp]assword', stdout):
channel.send(ROBOT_PASSWORD + '\n')
time.sleep(1)
status = channel.recv_exit_status() # blocking call
if status != 0:
if sudo:
output = channel.recv(nbytes).decode('UTF-8')
else:
output = channel.recv_stderr(nbytes).decode('UTF-8')
raise RuntimeError(f'command {command} exited with {status}, '
f'output: {output}')
return channel.recv(nbytes).decode('UTF-8')
I'm surprised this basic functionality is left for Paramiko users to reinvent themselves.
To my mind it would be much easier and secure to create a script which has sudoer rights.
For example, add this to sudoers:
myuser ALL=NOPASSWD:/home/myuser/somescript.sh
Now you can just invoke the script via paramiko on the host machine and be done with it.
I was able to run sudo cupsdisable
command on the remote server manually without having to enter the password when I login to that server as one of the admin user(not root) but when I execute the same using stdin, stdout, stderr = client.exec_command("sudo cupsdisable <Printqueuename>")
it does nothing.
The command that worked for me was:
stdin, stdout, stderr = client.exec_command("sudo -u root /usr/sbin/cupsdisable <printQueuename>")
This is specific to the above mentioned scenario only. Hope this helps someone
精彩评论