简体   繁体   中英

SSHing from within a python script and run a sudo command having to give sudo password

I am trying to SSH into another host from within a python script and run a command that requires sudo.

I'm able to ssh from the python script as follows:

import subprocess
import sys
import json

HOST="hostname"
# Ports are handled in ~/.ssh/config since we use OpenSSH
COMMAND="sudo command"

ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print(error)
else:
    print(result)

But I want to run a command like this after sshing :

extract_response = subprocess.check_output(['sudo -u username internal_cmd',
                                          '-m', 'POST',
                                          '-u', 'jobRun/-/%s/%s' % (job_id, dataset_date)])

        return json.loads(extract_response.decode('utf-8'))[0]['id']

How do I do that?

Also, I don't want to be providing the sudo password every time I run this sudo command, for that I have added this command (ie, internal_cmd from above) at the end of visudo in the new host I'm trying to ssh into. But still when just typing this command directly in the terminal like this:

ssh -t hostname sudo -u username internal_cmd -m POST -u/-/1234/2019-01-03

I am being prompted to give the password. Why is this happening?

You can pipe the password by using the -S flag, that tells sudo to read the password from the standard input.

echo 'password' | sudo -S [command]

You may need to play around with how you put in the ssh command, but this should do what you need.

Warning: you may know this already... but never store your password directly in your code, especially if you plan to push code to something like Github. If you are unaware of this, look into using environment variables or storing the password in a separate file.

If you don't want to worry about where to store the sudo password, you might consider adding the script user to the sudoers list with sudo access to only the command you want to run along with the no password required option. See sudoers(5) man page.

You can further restrict command access by prepending a "command" option to the beginning of your authorized_keys entry. See sshd(8) man page.

If you can, disable ssh password authentication to require only ssh key authentication. See sshd_config(5) man page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM