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

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.

主站蜘蛛池模板: 巴马| 泸水县| 芦山县| 囊谦县| 东台市| 丹寨县| 乌海市| 同江市| 安阳县| 剑阁县| 鹤庆县| 谢通门县| 杭锦后旗| 监利县| 南溪县| 安顺市| 南川市| 南充市| 揭西县| 开封县| 黎川县| 黄山市| 浏阳市| 永福县| 屏边| 师宗县| 弋阳县| 荣成市| 卢氏县| 宣武区| 铜川市| 庐江县| 海晏县| 靖西县| 惠州市| 定州市| 田林县| 高清| 汶川县| 石城县| 罗甸县|