Pexpect模块的pxssh扩展子模块详解

来源:互联网 发布:欠淘宝贷款200万 编辑:程序博客网 时间:2024/06/08 20:43

在Pexpect模块中,pexpect.pxssh.pxssh类扩展自pexpect.spawn类,专用于SSH连接的设置。
通过pxssh类的login()方法,在第一次连接远程SSH服务器的时候,能够将服务器的证书保存在known_hosts中。
pxssh类支持通过密钥认证,而无需输入密码。
pxssh类使用的Shell提示符能够兼容大多数Borne/Bash或Csh。
基本使用示例如下:

from pexpect import pxsshimport getpasstry:    s = pxssh.pxssh()    hostname = raw_input('hostname: ')    username = raw_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)

设置SSH连接的参数
s = pxssh.pxssh(options={    "StrictHostKeyChecking": "no",    "UserKnownHostsFile": "/dev/null"})...


给出私钥的路径,通过密钥认证

s.login (hostname, username, ssh_key='/path/to/your/private_key')
事实上,就是通过-i /path/to/your/private_key建立SSH连接。

禁用密钥认证,只能通过密码认证

s.force_password = Trues.login (hostname, username, password)

参考链接:

https://pexpect.readthedocs.io/en/stable/api/pxssh.html