python ssh实时交互_使用Paramiko在Python中实现ssh上的交互式shell?

import paramiko

import re

class ShellHandler:

def __init__(self, host, user, psw):

self.ssh = paramiko.SSHClient()

self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

self.ssh.connect(host, username=user, password=psw, port=22)

channel = self.ssh.invoke_shell()

self.stdin = channel.makefile('wb')

self.stdout = channel.makefile('r')

def __del__(self):

self.ssh.close()

def execute(self, cmd):

"""

:param cmd: the command to be executed on the remote computer

:examples: execute('ls')

execute('finger')

execute('cd folder_name')

"""

cmd = cmd.strip('\n')

self.stdin.write(cmd + '\n')

finish = 'end of stdOUT buffer. finished with exit status'

echo_cmd = 'echo {} $?'.format(finish)

self.stdin.write(echo_cmd + '\n')

shin = self.stdin

self.stdin.flush()

shout = []

sherr = []

exit_status = 0

for line in self.stdout:

if str(line).startswith(cmd) or str(line).startswith(echo_cmd):

# up for now filled with shell junk from stdin

shout = []

elif str(line).startswith(finish):

# our finish command ends with the exit status

exit_status = int(str(line).rsplit(maxsplit=1)[1])

if exit_status:

# stderr is combined with stdout.

# thus, swap sherr with shout in a case of failure.

sherr = shout

shout = []

break

else:

# get rid of 'coloring and formatting' special characters

shout.append(re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]').sub('', line).

replace('\b', '').replace('\r', ''))

# first and last lines of shout/sherr contain a prompt

if shout and echo_cmd in shout[-1]:

shout.pop()

if shout and cmd in shout[0]:

shout.pop(0)

if sherr and echo_cmd in sherr[-1]:

sherr.pop()

if sherr and cmd in sherr[0]:

sherr.pop(0)

return shin, shout, sherr

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值