Search code examples
pythonsshserverparamiko

How to emulate press 'Enter' with paramiko Python?


I was trying to make a simple code that runs apt update and apt upgrade on a server using python paramiko. After entering these commands, I confirm the installation with stdin.write("Y" + '\n') and then the problem occurs. If I do it manually on the server, then a window pops up (screenshot 1), in Python it looks like this (screenshot 2) I tried sending the command stdin.write("1" + '\n') but that didn't give any results.

  • screenshot 1

    enter image description here

  • screenshot 2

    enter image description here


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")

Solution

  • First of all, I'd try running apt upgrade -y, to see if it makes the upgrade non-interactive.

    Secondly, if you want a larger degree of control against an interactive terminal I'd suggest using expect. Expect allows for performing specific actions given particular conditions. In python you can use pyexpect. In your case, after having successfully login with pyexpect you could use something like:

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

    NOTE: It is not trivial to make everything work in the first place with pyexpect, but I've been using it in the past for a lot of hacky things with interactive terminals and it helped a lot.