2016-12-01 103 views
0

我是python的初學者,我想從自動化開始。 以下是我正在嘗試完成的任務。使用子進程的Python自動化

ssh -p 2024 [email protected] 

[email protected]'s password: 

我嘗試SSH到特定的機器和它的密碼提示。但我不知道如何將輸入提供給這個控制檯。我已經試過這

import sys 

import subprocess 

con = subprocess.Popen("ssh -p 2024 [email protected]", shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr =subprocess.PIPE) 

print con.stdout.readlines() 

如果我執行此,輸出會像

python auto.py 

[email protected]'s password: 

但我不知道如何給輸入了這一點。如果有人能幫我解決這個問題,會很感激。你也可以幫助我登錄後,如何通過SSH執行遠程機器上的命令。

請問如果這樣做

我試着用con.communicate()因爲標準輸入是PIPE mode我自動化進行。但沒有運氣。

如果這個不能被子進程完成,你能否建議我在遠程控制檯(一些其他模塊)上執行命令的替代方式對自動化有用?因爲我的大部分自動化取決於executin命令遠程控制檯上

感謝

+0

請參閱[Fabric](http://www.fabfile.org/)module – furas

+0

請參閱* ssh-agent *!不要試圖通過腳本傳遞paswords! –

回答

1

我已經通過Pexpect的實現。僅在Linux

import pexpect 
from pexpect import pxssh 

accessDenied = None 
unreachable = None 
username = 'someuser' 
ipaddress = 'mymachine' 
password = 'somepassword' 
command = 'ls -al' 
try: 
    ssh = pexpect.spawn('ssh %[email protected]%s' % (username, ipaddress)) 
    ret = ssh.expect([pexpect.TIMEOUT, '.*sure.*connect.*\(yes/no\)\?', '[P|p]assword:']) 
    if ret == 0: 
     unreachable = True 

    elif ret == 1: #Case asking for storing key 
     ssh.sendline('yes') 
     ret = ssh.expect([pexpect.TIMEOUT, '[P|p]assword:']) 
     if ret == 0: 
      accessDenied = True 
     elif ret == 1: 
      ssh.sendline(password) 
      auth = ssh.expect(['[P|p]assword:', '#']) #Match for the prompt 
    elif ret == 2: #Case asking for password 
     ssh.sendline(password) 
     auth = ssh.expect(['[P|p]assword:', '#'])  #Match for the prompt 

    if not auth == 1: 
     accessDenied = True 
    else: 
     (command_output, exitstatus) = pexpect.run("ssh %[email protected]%s '%s'" % (username, ipaddress, command), events={'(?i)password':'%s\n' % password}, withexitstatus=1, timeout=1000) 
    print(command_output) 
except pxssh.ExceptionPxssh as e: 
    print(e) 
    accessDenied = 'Access denied' 

if accessDenied: 
    print('Could not connect to the machine') 
elif unreachable: 
    print('System unreachable') 

這個工作過程Pexpect的僅適用於Linux系統:您運行代碼之前,您可能需要pip install pexpect。如果您需要在Windows上運行,您可以使用plink.exe。 paramiko是您可以嘗試的另一個模塊,我之前幾乎沒有問題。