pythonshellparamikociscoucs

Enter key works manually but not when sent via paramiko invoke_shell.sendall


I am looking for a way to login via SSH to a Cisco UCS server and execute few commands.

I am able to login and execute several commands and get the output. But the one command that requires y and Enter key doesn't seem to work.

If I try the same via terminal manually, it works. Looks like Enter key is not being executed on the server regardless of using \n, \r or \r\n.

ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=username, password=password)
ucs = ssh.invoke_shell()
ucs.sendall('scope chassis\r\n')
time.sleep(2)
ucs.sendall('power on\r\n')
time.sleep(2)
ucs.sendall("y\r\n")
time.sleep(10)
ucs.sendall('show\r\n')
time.sleep(10)
s = ucs.recv(4096)
with open("Output.txt", "ab") as text_file:
    text_file.write(s)
with open("temp2", "wb") as text_file:
    text_file.write(s)
ssh.close()
hostname# scope chassis
hostname /chassis #
hostname /chassis # power on
This operation will change the server's power state.
Do you want to continue?[y|N]y

hostname /chassis #
hostname /chassis # show
Power Serial Number Product Name  PID           UUID
----- ------------- ------------- ------------- ------------------------------------
off   xxxxxxxxxxx   UCS C240 M3S  UCSC-C240-M3S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Solution

  • I would be looking at this command:

    ucs.sendall('power on\r\n')
    

    It is possible that because you are using both \r and \n that the console is interpreting the \r to accept the power on command and the \n to immediately cancel it. So before you get the chance to input Y, the command has already been cancelled by the preceding \n.