Python使用pexpect实现telnet登陆服务器

pip install pexpect

#!/usr/bin/env python

import pexpect

address = '192.168.2.1'
userName = 'root'
password = '12345678'
cmd = 'telnet ' + address
prompt = '[$#>]'

child = pexpect.spawn(cmd)
index = child.expect(['login', pexpect.EOF, pexpect.TIMEOUT], timeout=1)
if index == 0:
    child.sendline(userName)
    index = child.expect('Password', timeout=1)
    child.sendline(password)
    child.expect(prompt, timeout=1)

    child.sendline("ls -al")
    child.expect("ls -al", timeout=1)
    child.expect(prompt, timeout=1)
    print(child.before)
else:
    print('expect "login", but get EOF or TIMEOUT')

child.close()
posted @ 2022-07-16 09:59  船长博客  阅读(283)  评论(0编辑  收藏  举报
永远相信美好的事情即将发生!