使用Python进行ssh而不使用模块
我正在编写一个脚本,它可以通过SSH连接到设备中,运行命令并将数据解析到文件中。我使用Pyparsing和Exscript编写了这篇文章,然后我发现我将要使用它的设备使用的是Python2.4.4和Debian4.1.1,因此这些模块将无法在上面工作。现在,我回到绘图板上,试图找出如何使用NO模块实现这一点。有人有任何参考资料或为我指出正确的方向吗?先谢谢你 这是我的代码:使用Python进行ssh而不使用模块,python,ssh,Python,Ssh,我正在编写一个脚本,它可以通过SSH连接到设备中,运行命令并将数据解析到文件中。我使用Pyparsing和Exscript编写了这篇文章,然后我发现我将要使用它的设备使用的是Python2.4.4和Debian4.1.1,因此这些模块将无法在上面工作。现在,我回到绘图板上,试图找出如何使用NO模块实现这一点。有人有任何参考资料或为我指出正确的方向吗?先谢谢你 这是我的代码: from Exscript.util.interact import read_login from Exscript.p
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
import uuid
from pyparsing import *
import re
import yaml
account = read_login()
conn = SSH2()
conn.connect('172.0.0.1')
conn.login(account)
conn.execute('foobar')
data = conn.response
conn.send('exit\r')
conn.close()
###### PARSER ######
date_regex = re.compile(r'\d\d-\d\d-\d\d')
time_regex = re.compile(r'\d\d:\d\d:\d\d')
pairs = [{'category': 'General Information',
'kv': Group(Word(alphanums) + Word(alphanums))},
{'category': 'Last Reset:',
'kv': Group(Word(alphas, max=1) + Word(alphas)) + Literal(':').suppress()
+ Group(Regex(date_regex) + Regex(time_regex)
+ Optional(SkipTo(LineEnd())))
}
]
# build list of categories with associated parsing rules
categories = [Word("# ").suppress() + x['category']
+ OneOrMore(Group(x['kv']))
for x in pairs]
# account for thing you don't have specific rules for
categories.append(Word("#").suppress() + Optional(SkipTo(LineEnd())) +
Group(OneOrMore(Combine(Word(alphanums) + SkipTo(LineEnd()))))
)
# OR all the categories together
categories_ored = categories[0]
for c in categories[1:]:
categories_ored |= c
configDef = OneOrMore(categories_ored)
suppress_tokens = ["show all", "SSH>", "Active System Configuration"]
suppresses = [Literal(x).suppress() for x in suppress_tokens]
for s in suppresses:
configDef.ignore(s)
result = configDef.parseString(data)
for e in result:
print(e)
with open('/Users/MyMac/development/data.yml', 'w') as outfile:
outfile.write( yaml.dump(e))
更新
我遵循了下面的建议,现在已经安装了
Pexpect
,并找到了我也安装的Python Pyparsing
的旧版本。因此,我在路上再次让我的脚本与模块一起工作。谢谢 看起来这个问题已经解决了,但是
只要为该主机配置了SSH(或者该主机不需要您登录),您就应该能够执行以下操作
import os
""" This will execute foobar on the remote host
and store the command output to a text file
on your machine."""
os.system("ssh 172.0.0.1 foobar > ~/data.txt")
""" Commence processing """
data = open("data.txt", mode='r')
# and so on and so on
您也可以使用
子流程
库,但是os.system
对于这些类型的任务来说是最简单的。使用子流程
与系统ssh
实用程序对话如何pexpect
看起来像一个早期的纯Python模块,只需要pty
。paramiko是另一个早期的纯Python SSH库。@hpaulj我曾考虑过使用子进程
,但在连接和运行命令时遇到了问题。在编写上述脚本之前,我查看了paramiko
,但遇到了一些问题,这就是为什么我选择了Exscript
。我将查看paramiko
的早期版本,看看这是否可行。另一件事是,debian
太旧了,不允许我很容易地安装模块。pexpect-2.4
足够紧凑(我认为)只需将一两个文件添加到您自己的目录即可“安装”。它不必位于系统目录中paramiko
可能需要在它自己的目录中,而不是你的目录中。@hpaulj谢谢!我在设备中添加了pexpect
,并且能够ssh
,现在希望我能找到一个使用pyparsing
或其他模块的解决方案。