كيفية الحصول على إخراج وحدة التحكم من كمبيوتر بعيد (SSH + بيثون)

StackOverflow https://stackoverflow.com/questions/1311697

سؤال

لدي غوغوطة "بيثون SSH". هناك وحدة رائعة pexpect, ، والتي يمكنها الوصول إلى جهاز كمبيوتر بعيد باستخدام SSH (مع كلمة المرور).

بعد توصيل الكمبيوتر البعيد، يمكنني تنفيذ الأوامر الأخرى. ومع ذلك، لا يمكنني الحصول على النتيجة في بيثون مرة أخرى.

p = pexpect.spawn("ssh user@remote_computer")
print "connecting..."
p.waitnoecho()
p.sendline(my_password)
print "connected"
p.sendline("ps -ef")
p.expect(pexpect.EOF) # this will take very long time
print p.before

كيفية الحصول على نتيجة ps -ef في حالتي؟

هل كانت مفيدة؟

المحلول

قد ترغب أيضا في التحقيق paramiko. وهي مكتبة SSH أخرى لبيتثون.

نصائح أخرى

هل جربت نهجا أكثر بساطة؟

>>> from subprocess import Popen, PIPE
>>> stdout, stderr = Popen(['ssh', 'user@remote_computer', 'ps -ef'],
...                        stdout=PIPE).communicate()
>>> print(stdout)

منحت، وهذا يعمل فقط لأن لدي ssh-agent تعمل مسبقا مع مفتاح خاص يعرفه المضيف البعيد.

child = pexpect.spawn("ssh user@remote_computer ps -ef")
print "connecting..."
i = child.expect(['user@remote_computer\'s password:'])
child.sendline(user_password)
i = child.expect([' .*']) #or use i = child.expect([pexpect.EOF])
if i == 0:
    print child.after # uncomment when using [' .*'] pattern
    #print child.before # uncomment when using EOF pattern
else:
    print "Unable to capture output"


Hope this help..

محاولة لإرسال

p.sendline("ps -ef\n")

IIRC، يتم تفسير النص الذي ترسله حرفيا، لذلك ربما يكون الكمبيوتر الآخر ينتظرك لإكمال الأمر.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top