[英]Python automation using subprocess
我是 python 的初學者,我想從自動化開始。 以下是我正在嘗試執行的任務。
ssh -p 2024 root@10.54.3.32
root@10.54.3.32's password:
我嘗試通過 ssh 連接到特定機器並提示輸入密碼。 但我不知道如何向這個控制台提供輸入。 我試過這個
import sys
import subprocess
con = subprocess.Popen("ssh -p 2024 root@10.54.3.32", shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr =subprocess.PIPE)
print con.stdout.readlines()
如果我執行這個,輸出會像
python auto.py
root@10.54.3.32's password:
但我不知道如何為此提供輸入。 如果有人能在這方面幫助我,將不勝感激。 還請您在登錄后幫助我,如何通過 ssh 在遠程機器上執行命令。
如果完成,將繼續我的自動化
我嘗試使用con.communicate()
因為 stdin 處於PIPE mode
。 但沒有運氣。
如果這不能通過子進程完成,您能否建議我在遠程控制台(其他一些模塊)上執行對自動化有用的命令的替代方法? 因為我的大部分自動化依賴於遠程控制台上的執行命令
謝謝
我已經通過 pexpect 實現了。 在運行代碼之前,您可能需要pip install pexpect
:
import pexpect
from pexpect import pxssh
accessDenied = None
unreachable = None
username = 'someuser'
ipaddress = 'mymachine'
password = 'somepassword'
command = 'ls -al'
try:
ssh = pexpect.spawn('ssh %s@%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 %s@%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')
這僅適用於 Linux,因為 pexpect 僅適用於 Linux。 如果您需要在 Windows 上運行,您可以使用 plink.exe。 paramiko
是您可以嘗試的另一個模塊,我之前遇到過一些問題。
我已經通過 paramiko 實現了。 在運行代碼之前,您可能需要pip install paramiko
:
import paramiko
username = 'root'
password = 'calvin'
host = '192.168.0.1'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=str(username), password=str(password))
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
chan = ssh.invoke_shell()
time.sleep(1)
print("Cnnection Successfully")
如果要傳遞命令並獲取輸出,只需執行以下步驟:
chan.send('Your Command')
if chan is not None and chan.recv_ready():
resp = chan.recv(2048)
while (chan.recv_ready()):
resp += chan.recv(2048)
output = str(resp, 'utf-8')
print(output)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.