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()