问题
I am able to give the following command in the command-line
C:\>cd "C:\Program Files\ExtraPuTTY\Bin"
C:\Program Files\ExtraPuTTY\Bin>putty.exe -ssh root@172.20.0.102 22
This helps me open the SSH session through PuTTY.
Whereas I am not able to reproduce them in the Python script.
cwd="C://Program Files//ExtraPuTTY//Bin"
COMMAND="ls"
ssh = Popen(['putty.exe -ssh','%s'%HOST, COMMAND,cwd],shell=True,stdout=f,stderr=f)
The error that I see is
"putty.exe -ssh"' is not recognized as an internal or external command,operable program or batch file
回答1:
In the putty download page, download and install plink
, and make sure its in the windows path ($PATH
variable)
Then, this python snippet should work:
import subprocess
cmd='plink -ssh {}@{} -pw {}'.format(user,server,password)
sp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
sp.stdin.write(stdin)
sp.stdin.close()
stdout= sp.stdout.read()
stderr=sp.stderr.read()
sp.wait()
stdin
is the commands typed by the user in the terminal, stdout
and stderr
are the server output.
Fill in your credentials in the user="root"
, server="172.20.0.102 22"
and maybe password
for the ssh connection
回答2:
You have to pass the cwd
as the cwd
parameter of the Popen
:
Popen(['putty.exe -ssh'...], shell=True, stdout=f, stderr=f, cwd=cwd)
And you should use Plink, not PuTTY, for automating the remote command execution. The Plink accepts the command on its command-line (PuTTY does not):
Popen(['plink.exe -ssh root@172.20.0.102 ls'], shell=True, stdout=f, stderr=f, cwd=cwd)
来源:https://stackoverflow.com/questions/32598361/python-script-for-ssh-through-putty