2015-08-28 79 views
1

我想通过python通过Plink自动接受ssh-rsa密钥。但我得到错误FileNotFoundError:[WinError 2] python 3.4

下面是我的代码

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, '%[email protected]%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 %[email protected]%s %s" \ 
       % (self.option, self.password, self.user, self.ipaddress, command)) 
     self.process = subprocess.Popen("plink -ssh %s -pw %s %[email protected]%s %s" \ 
       % (self.option, self.password, self.user, self.ipaddress, command), shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE) 

但我得到错误的密钥()函数行过程1。下面是错误:

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 

回答

2

在Windows中,子使用echo,你将需要使用shell=True。这是因为echo不是一个单独的可执行文件,而是Windows命令行的内置命令。示例 -

process1 = subprocess.Popen(command1,stdout=subprocess.PIPE,shell=True) 

另外,请做笔记,你应该只使用shell=True在绝对必要(在这种情况下,在Windows中使用子echo)。


虽然作为一个整体,你可以直接在y通过使用PIPE.communicate()你的第二个命令。示例 -

def key(self): 
    command2 = ['plink', '-ssh', self.option, '-pw', self.password, '%[email protected]%s'%(self.user, self.ipaddress), '\"exit\"'] 
    process2 = subprocess.Popen(command2,stdin=subprocess.PIPE,stdout=subprocess.PIPE) 
    output, _ = process.communicate(b'y') 
+0

值得补充的是'shell = True'是一个安全风险。 https://docs.python.org/2/library/subprocess.html#popen-constructor –

+0

是的,正确的。增加了一个不使用'shell = True'的替代方法。 –

+0

我喜欢这个选择,因此upvoted。 :) –