python ssh实时交互_使用Paramiko在python中通过ssh实现交互式shell?

I want to write a program (in Python 3.x on Windows 7) that executes multiple commands on a remote shell via ssh. After looking at paramikos' exec_command() function, I realized it's not suitable for my use case (because the channel gets closed after the command is executed), as the commands depend on environment variables (set by prior commands) and can't be concatenated into one exec_command() call as they are to be executed at different times in the program.

Thus, I want to execute commands in the same channel. The next option I looked into was implementing an interactive shell using paramikos' invoke_shell() function:

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

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

channel = ssh.invoke_shell()

out = channel.recv(9999)

channel.send('cd mivne_final\n')

channel.send('ls\n')

while not channel.recv_ready():

time.sleep(3)

out = channel.recv(9999)

print(out.decode("ascii"))

channel.send('cd ..\n')

channel.send('cd or_fail\n')

channel.send('ls\n')

while not channel.recv_ready():

time.sleep(3)

out = channel.recv(9999)

print(out.decode("ascii"))

channel.send('cd ..\n')

channel.send('cd simulator\n')

channel.send('ls\n')

while not channel.recv_ready():

time.sleep(3)

out = channel.recv(9999)

print(out.decode("ascii"))

ssh.close()

There are some problems with this code:

The first print doesn't always print the ls output (sometimes it is only printed on the second print).

The first cd and ls commands are always present in the output (I get them via the recv command, as part of the output), while all the following cd and ls commands are printed sometimes, and sometimes they aren't.

The second and third cd and ls commands (when printed) always appear before the first ls output.

I'm confused with this "non-determinism" and would very much appreciate your help.

解决方案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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python Paramiko 是一个用于 SSH 和 SFTP 的 Python 模块,可以实现实时交互。通过 Paramiko,可以在 Python 远程执行命令、上传和下载文件等操作。在实时交互,可以通过 ParamikoSSHClient 类的 invoke_shell() 方法来创建一个交互式shell。然后,可以使用 send() 方法发送命令,使用 recv() 方法接收命令的输出。同时,还可以使用 select 模块来实现非阻塞式的交互。 ### 回答2: Python paramiko 是一个用于远程登录和管理的模块,常用于远程服务器管理和自动化测试等方面。在使用 paramiko 进行实时交互时,主要有以下几个步骤: 1. 连接远程服务器:首先需要使用 SSHClient() 方法创建一个 SSH 连接,然后使用 .connect() 方法连接远程服务器,参数包括远程服务器地址、端口号、用户名和密码等信息。 2. 执行命令:使用 .exec_command() 方法执行命令,该方法返回三个值,包括标准输入、标准输出和标准错误输出,我们通常会用到标准输出。可以使用 .readlines() 方法获取命令执行的结果,并将结果打印输出。 3. 交互操作:有些命令需要交互操作,例如输入密码等。此时需要创建一个 Channel 对象,并使用 .invoke_shell() 方法打开一个交互终端。然后使用 .send() 方法发送需要操作的命令或数据,使用 .recv() 方法接收命令执行的返回结果。需要注意的是,每次接收到返回结果后,都需要使用 .recv_ready() 方法判断是否还有数据,如果没有数据则交互结束。 下面给出一个简单的代码示例,该示例用于实现在远程服务器上安装 nginx 并启动服务的过程。 ``` import paramiko # 创建 SSHClient 对象 ssh = paramiko.SSHClient() # 自动保存远程主机的 SSH 公钥 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接远程服务器 ssh.connect('xxx.xxx.xxx.xxx', port=22, username='root', password='123456') # 安装 nginx stdin, stdout, stderr = ssh.exec_command('yum install -y nginx') print(stdout.readlines()) print(stderr.readlines()) # 启动 nginx 服务 channel = ssh.invoke_shell() channel.send('systemctl start nginx\n') while True: if channel.recv_ready(): print(channel.recv(1024).decode()) break # 关闭连接 ssh.close() ``` 在上述代码,首先通过调用 .exec_command() 方法安装 nginx,然后通过调用 .invoke_shell() 方法打开交互终端,在终端发送启动 nginx 服务的命令,并循环接收返回结果。最后关闭连接,本次实时交互结束。 ### 回答3: Python ParamikoPython编程语言的SSH客户端。通过Paramiko库,我们可以实现与远程计算机的SSH交互,包括执行Shell命令、传输文件、端口转发等操作。本文将介绍如何使用Paramiko实现Python与远程计算机之间的实时交互Paramiko库提供了SSHClient类,它实现了与SSH服务器之间的远程交互。要创建SSHClient对象,我们可以执行以下代码: ``` import paramiko ssh = paramiko.SSHClient() ``` 然后,要连接到远程计算机,需要使用SSHClient对象的connect()方法,例如: ``` ssh.connect(hostname='remote_host', port=22, username='username', password='password') ``` 连接成功后,我们就可以执行远程Shell命令,例如: ``` stdin, stdout, stderr = ssh.exec_command('ls -l') print(stdout.read()) ``` 上述代码执行了一条ls -l命令,以列表形式返回了目标目录下的文件和目录的详细列表。 如果我们需要与执行命令的交互,我们需要调用SSHClient对象的invoke_shell()方法,例如: ``` channel = ssh.invoke_shell() ``` 然后,我们就可以使用channel对象的方法执行实时交互。例如,如果我们需要在远程计算机上启动一个Python解释器,并执行Python代码: ``` channel.send('python\n') channel.send('print("Hello, world!")\n') response = channel.recv(1024) print(response.decode()) ``` 上述代码从本地电脑向远程计算机发送两个命令。第一个命令是打开Python解释器,第二个命令是使用解释器运行一行代码,打印出“Hello,world!” 最后,我们需要断开连接,我们可以使用SSHClient对象的close()方法: ``` ssh.close() ``` 总之,Python Paramiko库提供了强大的实现Python与远程计算机之间实时交互的能力。通过它,我们可以轻松地实现远程Shell命令和Python交互

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值