簡體   English   中英

如何使用 paramiko Python 模擬按“Enter”?

[英]How to emulate press 'Enter' with paramiko Python?

我試圖制作一個簡單的代碼,使用 python paramiko 在服務器上運行apt updateapt upgrade 輸入這些命令后,我使用stdin.write("Y" + '\n')確認安裝,然后出現問題。 如果我在服務器上手動執行此操作,則會彈出 window(屏幕截圖 1),在 Python 中它看起來像這樣(屏幕截圖 2) 我嘗試發送命令stdin.write("1" + '\n')但那沒有'給出任何結果。

  • 屏幕截圖 1

    在此處輸入圖像描述

  • 屏幕截圖 2

    在此處輸入圖像描述


def sendCommand(command):
    print("Sending command")
    if (client):
        stdin, stdout, stderr = client.exec_command(command)
        while not stdout.channel.exit_status_ready():
            if stdout.channel.recv_ready():
                alldata = stdout.channel.recv(1024)
                while stdout.channel.recv_ready():
                    alldata += stdout.channel.recv(1024)

                print(str(alldata, "utf8"))

def sendCommand_Text(command, text):
    print("Sending command")
    if (client):
        stdin, stdout, stderr = client.exec_command(command)
        stdin.write(text + '\n')
        stdin.flush()

        stdin.write("1" + '\n')
        stdin.flush()

        stdin.write('\n')
        stdin.flush()
        while not stdout.channel.exit_status_ready():
            if stdout.channel.recv_ready():
                alldata = stdout.channel.recv(1024)
                while stdout.channel.recv_ready():
                    alldata += stdout.channel.recv(1024)

                print(str(alldata, "utf8"))

sendCommand("apt update\n")

sendCommand_Text('apt upgrade\n', "Y")

首先,我會嘗試運行apt upgrade -y ,看看它是否使升級成為非交互式的。

其次,如果您想對交互式終端進行更大程度的控制,我建議您使用expect Expect 允許在特定條件下執行特定操作。 在 python 你可以使用pyexpect 在你的例子中,在使用 pyexpect 成功登錄后,你可以使用類似的東西:

child.expect("What do you want to do about modified configuration file sshd_config?")
child.sendline("1")

注意:首先使用 pyexpect 使一切正常工作並不是微不足道的,但我過去一直在使用它來處理交互式終端的許多 hacky 事情並且它有很大幫助。

暫無
暫無

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

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