简体   繁体   English

我如何在Windows上使用SSH从SSH登录到Unix框时使用子进程发送密码

[英]How can i send password using subprocess while logging in to unix box using ssh from windows using python

I am trying to connect to unix box using subprocess module of python from windows machine.Please Note : Strictly want to use subprocess module(plz dont suggest pexpect,paramiko as i cant run them from windows to connect to unix as per my knowledge also have environment restricitons) Here is my code that i have tried and i always get interactive keyboard authentication message with password prompt: i try to send password to that prompt but unable to do so. 我正在尝试从Windows机器使用python的子处理模块连接到unix框。请注意:严格要使用子处理模块(plz不建议使用pexpect,paramiko,因为我无法从Windows运行它们以连接到unix,据我所知环境限制)这是我尝试过的代码,并且始终收到带有密码提示的交互式键盘身份验证消息:我尝试将密码发送到该提示,但无法这样做。

import subprocess
cmd='plink -ssh username@hostname -pw password'
sp=subprocess.Popen(cmd,stdin=subprocess.pipe,stdout=subprocess.pipe,shell=False)
sp.stdin.write('password \n')
sp.stdin.flush()
error,out=sp.communicate
print error
print out

Using -pw in command doesnt work (have used one at a time- either -pw option or stdin.write), also have tried to stdin.write to console but couldn't do that also. 在命令中使用-pw不起作用(一次使用了-pw选项或stdin.write),也曾尝试将stdin.write控制台,但也不能这样做。 I have some limitations on my execution environment too, also pexpect require termios which isnt present in windows 我的执行环境也有一些限制,还期望Windows中不存在termios

This works fine on my Windows box to connect to a FreeBSD one: 这在我的Windows盒子上可以很好地连接到FreeBSD:

>>> import subprocess
>>> cmd = r'c:\path\to\plink -ssh user@machine -pw pass'
>>> p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
             stderr=subprocess.PIPE)
>>> p.stdin.write(b'ls -al\nexit\n')
12
>>> p.stdin.flush()
>>> err = p.stderr.read()
>>> out = p.stdout.read()
>>> print(err)
b'Using username "user".\r\n'
>>> print(out.decode())
Last login: Mon Nov 20 17:16:18 2017 from xxx
... remaining of login message
$ ls -al
total 240
... listing of home directory
$ exit

user , pass and machine should be set per your own Linux or Unix box... userpassmachine应根据您自己的Linux或Unix盒进行设置...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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