官术网_书友最值得收藏!

Pexpect and SSH

If you try to use the previous telnet example and just plug into a ssh session, you might find yourself pretty frustrated. You always have to include the username in the session, ssh new key question, and more such. There are many ways to make ssh sessions work, but luckily, Pexpect has a subclass called pxssh, which specializes setting up SSH connections. The class adds methods for login, logout, and various tricky things to handle many situation in the ssh login process. The procedures are mostly the same with the exception of login() and logout():

>>> from pexpect import pxssh
>>> child = pxssh.pxssh()
>>> child.login('172.16.1.20', 'cisco', 'cisco', auto_prompt_reset=False)
True
>>> child.sendline('show version | i V')
19
>>> child.expect('iosv-1#')
0
>>> child.before
b'show version | i VrnCisco IOS Software, IOSv Software (VIOS-ADVENTERPRISEK9-M), Version 15.6(2)T, RELEASE SOFTWARE (fc2)rnProcessor board ID 9MM4BI7B0DSWK40KV1IIRrn'
>>> child.logout()
>>>

Notice the 'auto_prompt_reset=False' argument in the login() method. By default, pxssh uses the shell prompt to synchronize the output. But since it uses the PS1 option for most of bash or Csh, they will error out on Cisco or other network devices.

主站蜘蛛池模板: 阳谷县| 福鼎市| 黄冈市| 安远县| 罗源县| 时尚| 都江堰市| 杭锦后旗| 吴川市| 饶河县| 朔州市| 岳池县| 沛县| 衡南县| 祁连县| 呼和浩特市| 万载县| 富顺县| 禄劝| 集安市| 昌邑市| 石泉县| 海原县| 临猗县| 林西县| 高青县| 宣城市| 金寨县| 启东市| 交城县| 灵寿县| 辉县市| 泸溪县| 红桥区| 襄汾县| 宜君县| 资溪县| 中超| 丘北县| 专栏| 东源县|