簡體   English   中英

使用Python捕獲來自SSH會話的登錄輸出

[英]Capturing Login Output from an SSH Session in Python

我正在尋找一種使用python中的子進程模塊從ssh會話捕獲(並驗證)用戶登錄輸出(即,位於Issues.net中的MOTD)的方法。 我已經嘗試了以下幾種變體,但是還沒有找到一種方法來捕獲所需的輸出,而無需掛起會話或僅返回已通過(即“ ls –la”)命令的輸出。 我正在使用Python 2.6,並且要求僅使用此安裝中可用的本機庫(Red Hat 6.5),因此對我而言當前無法使用諸如pexpect之類的模塊。 下面的代碼僅返回“ ls –la”輸出,而不返回所需的ssh登錄消息。 注意: “ testUser”利用了PKI,因此不需要處理密碼。

loginStr = ['ssh', testUser@someHost, "ls -la"]
p = subprocess.Popen(loginStr, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
    line = p.stdout.readline()
    if not line: break
print line

我也嘗試了類似的結果:

loginStr = ['ssh', testUser@someHost, 'ls', '-la']
p = subprocess.Popen(loginStr, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
print stdout

隊列和線程可以解決嗎? 任何想法將不勝感激

您可能正在使用python Expect(pexpect)

如下所示(適當地替換,主機,用戶,密碼):

(同樣,根據shell提示的正則表達式進行調整)

import pexpect

cmd = "ssh -o StrictHostKeyChecking=no %s -l %s" % (<host>, <user>)
exp = pexpect.spawn(cmd, timeout=7)
idx = exp.expect('assword:')
nc = exp.sendline(<passwd>)
idx = exp.expect('[\n\r](#|\$) ')
if idx == 0:
    before = exp.before 
    print before

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM