我已引用https://pexpect.readthedocs.io/en/stable/api/pxssh.html中的python脚本,以执行基于ssh密码的登录。代码如下:
from pexpect import pxssh
import getpass
try:
s = pxssh.pxssh()
hostname = input('hostname: ')
username = input('username: ')
password = getpass.getpass('password: ')
s.login(hostname, username, password)
s.sendline('uptime') # run a command
s.prompt() # match the prompt
print(s.before) # print everything before the prompt.
s.sendline('ls -l')
s.prompt()
print(s.before)
s.sendline('df')
s.prompt()
print(s.before)
s.logout()
except pxssh.ExceptionPxssh as e:
print("pxssh failed on login.")
print(e)
当我运行代码时,它会提示输入主机名,用户名和密码。通过CLI提供这些输入后,ssh登录将失败,但以下情况除外:
could not set shell prompt (received: b"unset PROMPT_COMMAND\r\nPS1='[PEXPECT]\\$ '\r\[email protected]'s password: \r\[email protected]'s password: ", expected: '\\[PEXPECT\\][\\$\\#] ').
对于相同的ssh凭据,手动登录可以正常工作。
Note:
Python version: 3.6
Pexpect version: 4.7
该错误归因于login_timeout,默认情况下为10秒。在login()中设置较高的login_timeout可解决此问题。