python 3.6
pip install pexpect
#!/usr/bin/python3 import os import sys curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = os.path.split(curPath)[0] sys.path.append(rootPath) import platform from src import logutils log=logutils.logger("app",rootstdout=True,handlerList=['I','E']) if platform.system() =="Windows": raise SystemError('Windows目前不支持 pxssh') elif platform.system() =="Linux": try: from pexpect import pxssh except Exception: raise ImportError('Windows目前不支持 pxssh') def px_ssh(host,user,pwd): px=pxssh.pxssh() px.login(server=host,username=user,password=pwd) px.sendline("echo ''|telnet 192.168.81.129 8882 ") px.prompt() log.info(deal_std(px.before)) px.logout() def deal_std(res): std='' if type(res).__name__=='list': return ''.join(res) elif type(res).__name__=="bytes": std=res.decode("utf-8") return std elif type(res).__name__ == "str": return res for i in res: output=i.decode("utf-8") std +=output return std
[root@hostuser src]# vi pexpect_ssh.py [root@hostuser src]# python3 pexpect_ssh.py [INFO]2019-05-15 00:23:30 Wed --app-- pexpect_ssh.py: df -m &&ps -ef|grep java Filesystem 1M-blocks Used Available Use% Mounted on /dev/mapper/centos-root 27627 8618 19009 32% / devtmpfs 894 0 894 0% /dev tmpfs 910 1 910 1% /dev/shm tmpfs 910 11 900 2% /run tmpfs 910 0 910 0% /sys/fs/cgroup /dev/sda1 1014 232 783 23% /boot tmpfs 182 1 182 1% /run/user/42 tmpfs 182 0 182 0% /run/user/0 root 21286 21238 0 00:23 pts/2 00:00:00 grep --color=auto java [root@hostuser src]# cat pexpect_ssh.py