python ssh shell交互_使用Paramiko在Python上用ssh实现交互式shell?
我想编写一个程序(在Windows 7上的Python 3.x中),它通过ssh在远程shell上执行多个命令.在查看paramikos的exec_command()函数之后,我意识到它不适合我的用例(因为在执行命令后通道被关闭),因为命令依赖于环境变量(由先前的命令设置)并且不能连接到一个exec_command()调用,因为它们将在程序中的不同时间执行.
因此,我想在同一个通道中执行命令.我研究的下一个选项是使用paramikos的invoke_shell()函数实现交互式shell:
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()
这段代码存在一些问题:
>第一次打印并不总是打印ls输出(有时它只打印在第二次打印时).
>第一个cd和ls命令始终存在于输出中(我通过recv命令获取它们,作为输出的一部分),而有时会打印以下所有cd和ls命令,有时它们不会.
>第二个和第三个cd和ls命令(打印时)总是出现在第一个ls输出之前.
我对这种“非决定论”感到困惑,非常感谢你的帮助.
最佳答案
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
python ssh shell交互_使用Paramiko在Python上用ssh实现交互式shell?相关推荐
- python与网页交互_可爱的 Python: 使用 mechanize 和 Beautiful Soup 轻松收集 Web 数据
可爱的 Python 使用 mechanize 和 Beautiful Soup 轻松收集 Web 数据 使用 Python 工具简化 Web 站点数据的提取和组织 David Mertz 2010 ...
- python与cad交互_与命令行进行交互_Python数据分析实战应用_数据挖掘与分析视频-51CTO学院...
为什么学Python: 重要:数据分析是职业技能必备,Python是大数据分析** 趋势:Python是目前非常火的编程语言,使用人多 好学:学习简单,容易上手,使用灵活,可扩展强 **:会Pytho ...
- 我的python学习笔记全集_记录我的Python学习笔记
不想再像以前那样,什么都从头开始学习语法.总结语法,这样反而会过分纠结于语法,耽误了开发,毕竟语言的主要属性是工具,次要的属性是语言本身. 所以还是先熟练使用语言去进行开发,等足够熟悉了,再去研究语言 ...
- python利用写模块_使用C++编写python扩展模块
简介 长话短说,这里说的扩展Python功能与直接用其它语言写一个动态链接库,然后让Python来调用有点不一样(虽然本质是一样的).而是指使用Python本身提供的API,使用C++来对Python ...
- 密钥生成并配置_如何在 CentOS 8 上设置 SSH 密钥
本文最先发布在: 如何在 CentOS 8 上设置 SSH 密钥www.itcoder.tech 安全 Shell (SSH) 是一个被设计用来在客户端和服务器之间进行安全连接的加密网络协议. 最流 ...
- python领域语言教案_第一单元 走进Python 编程世界
(共17张PPT) 今年一场突如其来的新冠肺炎不仅使得人人带上了口罩,过了一个不一样的寒假,同时也使得我们以不一样的方式开启我们的学习. 同学们你们知道那些人容易得肺炎重症呢? 有基础病的 身体素质差 ...
- python怎么打日志_怎样调试 日志 python 代码
展开全部 使用 pdb 进行调试 pdb 是 python 自带e5a48de588b662616964757a686964616f31333361306366的一个包,为 python 程序提供了一 ...
- python 项目实战视频_腾讯视频 Python 爬虫项目实战
做了一些小项目,用的技术和技巧会比较散比较杂,写一个小品文记录一下,帮助熟悉. 需求:经常在腾讯视频上看电影,在影片库里有一个"豆瓣好评"板块.我一般会在这个条目下面挑电影.但是电 ...
- python定期自动运行_干货分享 | 适合 Python 入门的 8 款强大工具,不会就你还不知道吧!...
点击上方"人工智能Corner","星标或置顶公众号" 干货分享,第一时间送达 Python是一种开源的编程语言,可用于Web编程.数据科学.人工智能以及许多科 ...
最新文章
- 《 百度大脑AI技术成果白皮书》,介绍百度大脑5.0,附48页PDF下载
- Android开发--图形图像与动画(二)--Animation实现图像的 渐变 缩放 位移 旋转
- 如何使用Angular Generator创建新的Component
- GDKOI2015 Day2
- CentOS 7 防止端口自动关闭
- 每日top3热点搜索词统计案例
- 第一章MCS-51单片机结构,单片机原理、接口及应用
- 定位position(前面布局无法实现
- 在Linux中查找用户帐户信息和登录详细信息的11种方法
- 浅论园子的人对广告的认识
- ios弧形进度条_iOS圆弧渐变进度条的实现
- java计算机毕业设计风情旅游网站源码+mysql数据库+系统+lw文档+部署
- Ps 2021教程,如何更换证件照背景?
- autoit脚本实现电脑加域,退域,重加域
- 高登数学,线性代数问题的数值解(SciPy第三方库,近似解)
- .net MVC学习笔记(1)
- OpenType字库文件
- GPRS学习(1)----网络结构及主要网元功能
- echarts蚊香图
- HTML+CSS大作业: 抗击疫情网页制作作业_疫情防控网页设计模板HTML_ 简单学生网页设_静态HTML+CSS网站制作成品...
热门文章
- java前期_【JAVA】前期环境配置
- excel中线性函数_Excel中特别有用的不常用函数之Indirect函数
- mac nginx 非brew安装_Nginx服务器环境手动安装Discuz! Q非详细教程
- mysql 7下载安装及问题解决
- codeforces Round #320 (Div. 2) C. A Problem about Polyline(数学) D. Or Game(暴力,数学)
- 蓝桥杯 历届试题 危险系数
- from server sql 拼接统计两个子查询_[SQL SERVER系列]之嵌套子查询和相关子查询
- elemntui icon 大小_自定义elementui中的图标
- orange pi java_[中文]Orange Pi家族各大成员一览表
- Oracle 11g系统自动收集统计信息