在下面的代码中,我使用Paramiko远程登录到嵌入式站点服务器,并检索所有.log和.txt文件,并将它们放置在本地文件夹中机器来搜索潜在的引脚#可能是清晰的。在第二段代码中,这是脚本的一部分,它可以解压缩.tgz文件并以ascii,十六进制等方式执行字符串搜索......我发现远程获取文件不具有成本效益,并且认为它更好只需在登录时搜索嵌入式设备上的所有.log和.txt。但是,我仍然是一名Python新手,并且花了很长时间才想出我现在使用的代码。为了时间的缘故,我寻求帮助。有人能告诉我如何使用下面的代码来实现更多的exec_commands(我已经有代码搜索 - 在第一个代码下面)?我只是不确定在哪里以及如何实施它。谢谢!如何搜索下面我要返回的文件
import paramiko
import sys
import os
import re
sim_ip = raw_input('Host: ')
pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
if re.match(pattern, sim_ip):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(sim_ip, username='root', password='******')
apath = '/'
apattern = '"*.txt" -o -name "*.log"'
rawcommand = 'find {path} -name "*.txt" -o -name "*.log"' #{pattern}
command = rawcommand.format(path=apath, pattern=apattern)
stdin, stdout, stderr = ssh.exec_command(command)
filelist = stdout.read().splitlines()
ftp = ssh.open_sftp()
for afile in filelist:
(head, filename) = os.path.split(afile)
print(filename)
#ftp.get(afile, 'c:\\Extracted\\' + filename) #'./'+filename)
ftp.close()
ssh.close()
else:
print "You entered an invalid IP Address!!!"
这里是我目前使用的搜索日志和文本文件中的代码:
print "\nDirectory to be searched: " + directory
print "\nFile result2.log will be created in: c:\Temp_log_files."
paths = "c:\\Temp_log_files\\result2.log"
temp = file(paths, "w")
userstring = raw_input("Enter a string name to search: ")
userStrHEX = userstring.encode('hex')
userStrASCII = ''.join(str(ord(char)) for char in userstring)
regex = re.compile(r"(%s|%s|%s)" % (re.escape(userstring), re.escape(userStrHEX), re.escape(userStrASCII)))
goby = raw_input("Press Enter to begin search (search ignores whitespace)!\n")
for root,dirname, files in os.walk(directory):
for file1 in files:
if file1.endswith(".log") or file1.endswith(".txt"):
f=open(os.path.join(root, file1))
for i,line in enumerate(f.readlines()):
result = regex.search(line)
if result:
ln = str(i)
pathnm = os.path.join(root,file1)
template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
output = template.format(ln, pathnm, result.group())
print output
temp.write(output)
break
else:
print "String Not Found in: " + os.path.join(root,file1)
temp.write("\nString Not Found: " + os.path.join(root,file1) + "\n")
f.close()
re.purge()
你的问题是你想在远程服务器上执行一个Python脚本吗? –
@Mikko Ohtamaa - 我想你可以这么说。 – suffa
我弄明白了,很快就会发布代码。 – suffa