自动化

python实现交互式远程命令执行

2020-02-06  本文已影响0人  佛系小懒

前置环境

pip3.5 install interactive  paramiko

借助spawn及expect进行远程交互式功能实现

pexpect模块中的run与spawn

代码实现

def posix_shell(chan):

    import select

    oldtty = termios.tcgetattr(sys.stdin)

    try:

        tty.setraw(sys.stdin.fileno())

        tty.setcbreak(sys.stdin.fileno())

        chan.settimeout(0.0)

        r, w, e = select.select([chan, sys.stdin], [], [])

        if chan in r:

            try:

                x = chan.recv(1024)

                if len(x) == 0 or x.decode("utf-8").__eq__("EOF"):

                    print('EOF')

                sys.stdout.write(x.decode("utf-8"))

                sys.stdout.flush()

            except socket.timeout:

                pass

        if sys.stdin in r:

            x = sys.stdin.read(1)

            chan.send(x)

    finally:

        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)

测试代码

# 建立ssh连接

ssh = paramiko.SSHClient()

ssh.load_system_host_keys()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('XXXX', port=22, username='XXX', password='XXX', compress=True)

# 建立交互式shell连接

channel = ssh.invoke_shell()

# 建立交互式管道

interactive_shell.interactive_shell(channel)

# 关闭连接

channel.close()

ssh.close()

上一篇 下一篇

猜你喜欢

热点阅读