我试图通过Plink通过python自动接受ssh-rsa密钥。但是我收到了错误
以下是我的代码
def __init__(self, ipaddress, option, user, password, command=""):
"""
Constructor creates the connection to the host.
"""
self.ipaddress = ipaddress
self.option = option
self.user = user
self.password = password
self.command = command
self.key()
def key(self):
command1 = ['echo', 'y']
process1 = subprocess.Popen(command1,stdout=subprocess.PIPE)
command2 = ['plink', '-ssh', self.option, '-pw', self.password, '%s@%s'%(self.user, self.ipaddress), '\"exit\"']
process2 = subprocess.Popen(command2,stdin=process1.stdout,stdout=subprocess.PIPE)
def sendSingleCommand(self, command):
"""
Set up a ssh connection a device, send command, close connection and return stdout,stderr tuple.
"""
try:
print("plink -ssh %s -pw %s %s@%s %s" \
% (self.option, self.password, self.user, self.ipaddress, command))
self.process = subprocess.Popen("plink -ssh %s -pw %s %s@%s %s" \
% (self.option, self.password, self.user, self.ipaddress, command), shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
但是我遇到了line process1的Key()函数错误。以下是错误:
File "C:\Python34\lib\subprocess.py", line 859, in __init__
Error: restore_signals, start_new_session)
Error: File "C:\Python34\lib\subprocess.py", line 1112, in _execute_child
Error: startupinfo)
Error: FileNotFoundError: [WinError 2] The system cannot find the file specified
答案 0 :(得分:2)
在Windows中,要在子流程中使用echo
,您需要使用shell=True
。这是因为echo不是单独的可执行文件,而是windows命令行的内置命令。示例 -
process1 = subprocess.Popen(command1,stdout=subprocess.PIPE,shell=True)
另外,请注意,只有在绝对必要时才应使用shell=True
(在这种情况下,在子进程的窗口中使用echo
)。
虽然作为一个整体,您可以使用y
和PIPE
直接将.communicate()
传递到第二个命令。示例 -
def key(self):
command2 = ['plink', '-ssh', self.option, '-pw', self.password, '%s@%s'%(self.user, self.ipaddress), '\"exit\"']
process2 = subprocess.Popen(command2,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
output, _ = process.communicate(b'y')