I have written a simple Python Script that parses a log and prints a string if a line is equal to a mac address.
My next step is to parse out the log file into a txt file.
Is there a way to create a variable for each mac address of the access point so that when it parses out into text file, it will not show mac address it will show the AP name, and user name?
here is an example line
[2014-07-22 10:21:06,821] <inform_stat-3> WARN event - [event] User[78:a3:e4:3b:bd:3d] roams from AP[dc:9f:db:1a:60:64] to AP[dc:9f:db:1a:2d:95] on "channel 11(ng)"
My code is currently as follows
for line in open("system.log"):
if "e4:98:d6:27:4c:b6" in line:
print line
Start with the dictionary:
dd = {'78:a3:e4:3b:bd:3d' : 'Joe Smith',
'dc:9f:db:1a:60:64' : 'Server1',
'dc:9f:db:1a:2d:95' : 'Server1'}
dat = '[2014-07-22 10:21:06,821] <inform_stat-3> WARN event - [event] User[78:a3:e4:3b:bd:3d] roams from AP[dc:9f:db:1a:60:64] to AP[dc:9f:db:1a:2d:95] on "channel 11(ng)"'
aps = []
for elem in dat.split():
if elem.startswith('User['):
uname = dd.get(elem[5:-1], 'Unknown')
if elem.startswith('AP['):
aps.append(dd.get(elem[3:-1], 'Unknown'))
now you should have enough information to print to the text file
Related
How to replace string after specific character using python
I have a file with below contents
The Test file contents are as below "Test1"{
Serial = 12345
IP = 12.10.23.10
User = user1
}
how do i replace the contents after the = symbol using python ?
for example i want to replace with below contents.
The Test file contents are as below "Test1"{
Serial = 22330011
IP = 1.1.1.1
User = User_11
}
The contents after = symbols are not pre defined, hence substituting 12345 with 22330011 is not required here.
need a logic to find what is there after = symbol and replace it with the user defined value.
Lets say i have above data in temp.txt
file=open('temp.txt','r')
data=file.readlines()
outdata=[]
for line in data:
try:
lhs,rhs=line.split('=')
rhs=input()
outdata.append('='.join([lhs,' '+rhs,'\n']))
except:
outdata.append(line)
file.close()
file=open('temp.txt','w')
for line in outdata:
file.write(line)
This code read from the file and ask the input from user for rhs and updates in the file again
I want to redirect results out to a file without leaving the wsadmin command line.
Jyhton code :
dsid = AdminConfig.getid('/DataSource:IG.JASPER.DS/')
AdminControl.testConnection(dsid)
I find something like below. but I am not sure really Can someone please let me know how to do this?
file = open("C:\\Test\\conn.txt","w")
file.write("Admin.config.... blah")
file.close()
See here for more details.
Open the file with "w" or "w+" file mode for writing to a file object.
When a file opened for write operation you can use the following :
redirecting operator >>
write function
writelines function
So the below script should work for your datasource test connection
dsid = AdminConfig.getid('/DataSource:BPH Oracle XA DataSource')
status = AdminControl.testConnection(dsid)
file=open('results.txt', 'w')
#print >>file, status
#file.write(status)
file.write(AdminControl.testConnection(dsid))
file.close()
For successful connection, the generated file (results.txt) should contain an entry like "WASX7217I: Connection to provided datasource was successful."
I am very new to python and writing a script that will extract a few URLs from two configuration files. The following is the body of the script as of now:
import os
import sys
import logging
logger = logging.getLogger('check_store')
logger.setLevel(logging.DEBUG)
env= raw_input("Enter environmentname (ex. dev/qa/prod): ")
cust= raw_input("Enter customer name: ")
engage_properties= '/opt/engage/engageconf.properties'
symmetric_properties= '/opt/engage/symmetric.properties'
with open ("%s" % (engage_properties)) as inF:
for line in inF:
if ("%s-%s.%sfqdn.com" % (env,cust,env)) in line:
print line
The output as as follows:
Enter environmentname (ex. dev/qa/prod): qa
Enter customer name: cust
connect.rest.address=http://connect.qa-cust.qafqdn.com
connect.rest.ssl.address=https://connect.qa-cust.qafqdn.com
connect.rest.giftregistry.service=http://connect.qa-cust.qafqdn.com:8280/services
receipt.server.host=engage.central.qa-cust.qafqdn.com
What I am trying to accomplish is having the script specifically look for the following as also shown above:
connect.rest.address=
connect.rest.ssl.address=
connect.rest.giftregistry.service=
and report back to the user if one of them is incorrect..
So, if i enter in when prompted: 'qa' for then env name and 'cust' for the customer name, if either of the URLs have anything other than something formatted like so:
connect.qa-cust.qafqdn.com
then it will tell the user which of the three URL variables are not formatted correctly.
So, to clarify.. if 'connect.rest.ssl.address=' did not equal the input that I provided (equaling qa-cust.qafqdn.com) but the rest of them did, then I would see an error like:
connect.rest.address - OK
connect.rest.ssl.address - ERROR: does not match value provided
connect.rest.giftregistry.service - OK
This script is basically a environment sanity checker.
I tried to make this as clear as possible and I appreciate the assistance.
I'm not sure I understood the question properly, but if you are expecting any line in the file to have the correct properties, then if the line has part of but not all of the correct formatting it is wrong.
with open ("%s" % (engage_properties)) as inF:
for line in inF:
if ("%s-%s.%srhythmforstores.com" % (env,cust,env)) in line:
print line
elif "rhythmforstores.com" in line:
print error_message
So I have a simple reddit bot set up which I wrote using the praw framework. The code is as follows:
import praw
import time
import numpy
import pickle
r = praw.Reddit(user_agent = "Gets the Daily General Thread from subreddit.")
print("Logging in...")
r.login()
words_to_match = ['sdfghm']
cache = []
def run_bot():
print("Grabbing subreddit...")
subreddit = r.get_subreddit("test")
print("Grabbing thread titles...")
threads = subreddit.get_hot(limit=10)
for submission in threads:
thread_title = submission.title.lower()
isMatch = any(string in thread_title for string in words_to_match)
if submission.id not in cache and isMatch:
print("Match found! Thread ID is " + submission.id)
r.send_message('FlameDraBot', 'DGT has been posted!', 'You are awesome!')
print("Message sent!")
cache.append(submission.id)
print("Comment loop finished. Restarting...")
# Run the script
while True:
run_bot()
time.sleep(20)
I want to create a file (text file or xml, or something else) using which the user can change the fields for the various information being queried. For example I want a file with lines such as :
Words to Search for = sdfghm
Subreddit to Search in = text
Send message to = FlameDraBot
I want the info to be input from fields, so that it takes the value after Words to Search for = instead of the whole line. After the information has been input into the file and it has been saved. I want my script to pull the information from the file, store it in a variable, and use that variable in the appropriate functions, such as:
words_to_match = ['sdfghm']
subreddit = r.get_subreddit("test")
r.send_message('FlameDraBot'....
So basically like a config file for the script. How do I go about making it so that my script can take input from a .txt or another appropriate file and implement it into my code?
Yes, that's just a plain old Python config, which you can implement in an ASCII file, or else YAML or JSON.
Create a subdirectory ./config, put your settings in ./config/__init__.py
Then import config.
Using PEP-18 compliant names, the file ./config/__init__.py would look like:
search_string = ['sdfghm']
subreddit_to_search = 'text'
notify = ['FlameDraBot']
If you want more complicated config, just read the many other posts on that.
I'm trying to access a spreadsheet in google docs with a python script. But I always get errors when executing the following "standard" example:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import gdata.spreadsheet.service
if __name__ == "__main__":
email = 'email#gmail.com'
password = 'secret'
weight = '180'
# Find this value in the url with 'key=XXX' and copy XXX below
spreadsheet_key = '0AiKRVC_dEsdfafdC1Id2FGdGVMR1pHb3E4UGlmbUYxS1E'
# All spreadsheets have worksheets. I think worksheet #1 by default always
# has a value of 'od6'
worksheet_id = 'od6'
spr_client = gdata.spreadsheet.service.SpreadsheetsService()
spr_client.email = email
spr_client.password = password
spr_client.source = 'Example Spreadsheet Writing Application'
spr_client.ProgrammaticLogin()
# Prepare the dictionary to write
dict = {}
dict['date'] = time.strftime('%m/%d/%Y')
dict['time'] = time.strftime('%H:%M:%S')
dict['weight'] = weight
print dict
entry = spr_client.InsertRow(dict, spreadsheet_key, worksheet_id)
if isinstance(entry, gdata.spreadsheet.SpreadsheetsList):
print "Insert row succeeded."
else:
print "Insert row failed."
It simply does not work. I always get the following error
{'date': '01/07/2013', 'weight': '180', 'time': '19:58:44'}
Traceback (most recent call last):
File "/Path/to/Project//Python2GoogleDocs/src/P2GTest.py", line 31, in <module>
entry = spr_client.InsertRow(dict, spreadsheet_key, worksheet_id)
File "/Library/Python/2.7/site-packages/gdata/spreadsheet/service.py", line 339, in InsertRow
converter=gdata.spreadsheet.SpreadsheetsListFromString)
File "/Library/Python/2.7/site-packages/gdata/service.py", line 1236, in Post
media_source=media_source, converter=converter)
File "/Library/Python/2.7/site-packages/gdata/service.py", line 1358, in PostOrPut
'reason': server_response.reason, 'body': result_body}
gdata.service.RequestError: {'status': 400, 'body': 'We're sorry, a server error occurred. Please wait a bit and try reloading your spreadsheet.', 'reason': 'Bad Request'}
What is going wrong here? Email and password are correct and I extracted the spreadsheet key from the url of the document itself.
Make sure that your columns in the dictionary match the columns in your spreadsheet. If they aren't present in the sheet, you will get an error. Also, although this isn't your problem here, you want to make sure that your dictionary keys are the lowercased column name with all spaces replaced with _'s. That is another source of potential error (and one that has tripped me up more than once :) ).
Try a library named python-google-spreadsheet (which I wrote). It's designed to make suff like what you are trying to do much simpler than using the API directly.