0
votes

I am trying to execute few scripts in remote linux machine from windows host machine. I am hoping to achieve this using python subprocess +putty/plink. When I try Putty or plink commands from windows cmd, it works fine. But if I try the same command using python subprocess, I get a lot of errors.

C:\Users\username>plink.exe username@machinename -pw password

Works fine. But when I try from python,

process = subprocess.Popen('plink.exe username@machinename -pw password'.split(),
                           env={'PATH':'C:\\Program Files (x86)\\PuTTY\\'},
                           shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)

Throws the following error.

Unable to open connection:

gethostbyname: unknown error'

process = subprocess.Popen("putty.exe -ssh -2 -l username -pw password -m C:\\script.sh machinename",
                           env={'PATH':'C:\\Program Files (x86)\\PuTTY\\'},
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT
                           ,shell=True);

Unable to open connection:

gethostbyname: unknown error'

I tried subprocess.check_ouput too with no luck.

output = subprocess.check_output("putty.exe -ssh -2 -l username -pw password -m C:\\script.sh machinename", stderr=subprocess.STDOUT,shell=True)

Throws the following error

CalledProcessError: Command 'putty.exe -ssh -2 -l username -pw password -m C:\script.sh machinename' returned non-zero exit status 1

Could this be a firewall issue?

1
What happens if you don't reset the environment in the call to Popen? - alexis
Avoid using shell=True where possible, such as in this case. Maybe putty.exe returns a more useful exit code than the shell's exit code of "1" (fail). - Eryk Sun
Regarding env, generally you should modify os.environ.copy(). The docs clearly state what this parameter does: "If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment. Note: If specified, env must provide any variables required for the program to execute. On Windows, in order to run a side-by-side assembly the specified env must include a valid SystemRoot." The crypto API also requires SystemRoot. - Eryk Sun
@alexis it does not recognize putty if I don't give the path. I get "putty is not recognizable internal or external error" - Sathish
@eryksun If I don't use shell=True I get a strange "File not found" exception in Popen. - Sathish

1 Answers

2
votes

I highly advise against using PuTT or in general every external program to connect to shh and then interface with pipes.

Using the python library paramiko this can be done much better.

For example:

# ... connect like one of the examples on github
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
    print '... ' + line.strip('\n')