How to provide a subprocess password and get the standard version at the same time

I am trying to check for an executable file on a remote machine, and then run the specified executable file. To do this, I use a subprocess to run ssh <host> ls <file> , and if that succeeds, run ssh <host> <file> . ssh asks for a password, of course, and I would like to provide this automatically. Also, I would like to get the return code from ls, and stdout and stderr to execute the command.

So, I know that the communicate() method is necessary to avoid deadlocks, but I can not get the password to recognize Popen(stdin) . I also use Python 2.4.3 and stick with this version. Here is the code that I still have:


 import os import subprocess as sb def WallHost(args): #passwd = getpass.getpass() passwd = "password" for host in args: # ssh to the machine and verify that the script is in /usr/bin sshLsResult = sb.Popen(["ssh", host, "ls", "/usr/bin/wall"], stdin=sb.PIPE, stderr=sb.PIPE, stdout=sb.PIPE) (sshLsStdout, sshLsStderr) = sshLsResult.communicate(input=passwd) sshResult = sshLsResult.returncode if sshResult != 0: raise "wall is not installed on %s. Please check." % host else: sshWallResult = sb.Popen(["ssh", host, "/usr/bin/wall", "hello world"], stdin=sb.PIPE, stderr=sb.PIPE, stdout=sb.PIPE) (sshWallStdout, sshWallStderr) = sshWallResult.communicate(input=passwd) print "sshStdout for wall is \n%s\nsshStderr is \n\n" % (sshWallStdout, sshWallStderr) args = ["127.0.0.1", "192.168.0.1", "10.10.265.1"] WallHost(args) 

Any help allowing the process to accept this password is appreciated. Or, if you have a better way to test the executable and then run it on a remote host .;)

THX Anthony

+1
source share
1 answer

How about using authorized_keys . Then you do not need to enter a password.

You can also go hard (only works on Linux):

 import os import pty def wall(host, pw): pid, fd = pty.fork() if pid == 0: # Child os.execvp('ssh', ['ssh', host, 'ls', '/usr/bin/wall']) os._exit(1) # fail to execv # read '..... password:', write password os.read(fd, 1024) os.write(fd, pw + '\n') result = [] while True: try: data = os.read(fd, 1024) except OSError: break if not data: break result.append(data) pid, status = os.waitpid(pid, 0) return status, ''.join(result) status, output = wall('localhost', "secret") print status print output 

http://docs.python.org/2/library/pty.html

+3
source

Source: https://habr.com/ru/post/987154/


All Articles