first python program need a bit of help writing to file - python

I have a small program that I'm trying to create to get ip addresses from an sqlite db and run the whois command on and write it to a data file.
import sqlite3
import os
v_path = os.path.abspath('')
v_db = os.path.abspath("../")+"/logsql.sqlite"
v_ip = v_path+"/Whois.Resources/Who.IP.txt"
print v_ip
try:
f1 = open(v_db)
f2 = open(v_ip, "w")
conn = sqlite3.connect(v_db)
c = conn.cursor()
c.execute("select remote_host from connections group by remote_host;")
for row in c:
print row
#p.write("sts")
c.close()
f1.close()
f2.close()
except IOError as e:
print 'Oh dear, shit just hit the fan.'
The output looks like this
bash$ python WhoIs.Program.py
/Users/frankwiebenga/Documents/Spring 2012/Malware/WhoIs/Whois.Resources/Who.IP.txt
Oh dear, shit just hit the fan.
The issue is opening v_ip, the v_db opens fine. The file is there
bash$ pwd
/Users/frankwiebenga/Documents/Spring 2012/Malware/WhoIs/WhoIs.Resources
bash$ ls
Who.IP.txt
frank-wiebengas-macbook-pro:WhoIs.Resources frankwiebenga$
The directory structure is
logsql WhoIs{directory}
____________
WhoIs.Program.py WhoIs.Resources{directory}
____________
Who.IP.txt

Whois.Resources should be WhoIs.Resources. Linux is case sensitive.
P.S. Thanks for including enough information in your question to figure this out. It's rare for that to happen.

Related

Sqlite python - attempt to write a read only database

I have a simple python script that puts data in a database. Both the script and
the database have owner www-data. When I run sudo python and write the
commands one by one it works, but if I run python monitor.py or sudo python monitor.py it doesn't work; it says, "attempt to write a read only database".
This is my script: (it receives data from arduino)
from serial import Serial
from time import sleep
import sqlite3
serial_port = '/dev/ttyACM0';
serial_bauds = 9600;
# store the temperature in the database
def log_light(value):
conn=sqlite3.connect('/var/db/arduino.db')
curs=conn.cursor()
curs.execute("UPDATE sensor1 set status = (?)", (value,))
# commit the changes
conn.commit()
conn.close()
def main():
s = Serial(serial_port, serial_bauds);
s.write('T');
sleep(0.05);
line = s.readline();
temperature = line;
s.write('H');
sleep(0.05);
line = s.readline();
humidity = line;
s.write('L');
sleep(0.05);
line = s.readline();
light = line;
log_light(light);
if __name__=="__main__":
main()
It sounds like a permission problem. Write access is granted only to the user, which is root. You need to change the user to be directly yourself, not root. You can do this using chmod on many *nix systems.
You could also gove write access to anyone in the group.

python spur ssh check if file exists

I am using spur in python to ssh into a linux server and it's doing everything I want it to, except, I am unsure of the best way to use spur to ssh into the linux server and check if a file exists on that server. I am currently doing it this way, but it is quite slow, is there a quicker way?
import spur
shell = spur.SshShell(hostname="192.168.0.22", username="username", password="password", missing_host_key=spur.ssh.MissingHostKey.accept)
inFile = "/home/myFolder/Desktop/fileNmae.avi"
try:
result = shell.run(["ls", inFile])
print "Pass"
except:
print "Fail"
You can use spurplus that we developed since we found paramiko and spur to be both a bit too low-level. Here is an example how to check if a file exists:
import spurplus
with spurplus.connect_with_retries(
hostname='some-machine.example.com', username='devop') as shell:
file_exists = shell.exists("/path/to/some/file")
pth = pathlib.Path("/path/to/another/file")
another_file_exists = shell.exists(pth)

Using Python to ssh with no modules

I'm in a pickle with writing a script that can SSH into device, run a command and parse that data out to a file. I've written this using Pyparsing and Exscript then I found out that the device I'm going to be using this on is using Python 2.4.4 and Debian 4.1.1 so the modules will not work on this. Now I am back to the drawing board trying to find out how to do this with NO modules. Anyone have any reference or point me in the right direction for this? Thank you in advance.
Here is my code:
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))
UPDATE
I have followed the advice below and now have Pexpect installed and found a older version of Python-Pyparsing that I have also installed. So I'm on my way again to getting my scripts to work with modules. Thanks!
Looks like this is already solved, but...
As long as your SSH is configured for this host (or the host doesn't require you to log-in), you should be able to do the following.
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
You can also use the subprocess library, but os.system for these types of tasks is the simplest IMO.

accessing a database from a python cgi

I configured the httpd file to run python scripts as given in a website. After the configuration I was amazed to see .py file getting executed when placed in the htdocs folder, but .cgi files are not being executed. The error says an internal error.
Thought of proceeding with .py files but when I try to access mysql database, I am not able to.
My .py file is:
import cgi
import MySQLdb
print "Content-type: text/html"
print
print "<html><head>"
print ""
print "</head><body>"
form=cgi.FieldStorage()
name=form["t1"].value
print "Hello. %s" %name
print "hai"
print '<input type="submit"/>'
Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="root", passwd="pwd", db="db1")
cursor = Con.cursor()
sql="SELECT * FROM rec"
cursor.execute(sql)
data = cursor.fetchone()
print "%s" %data
print "</body></html>"
I am not getting any error, but 'data' is not getting printed
output I got was:
hello name hai submit button
new to python. So can u guys please help me out?
python version-2.7
db-mysql
server-apache 2.2
win32 bit
Put following line at first line, and see what error happened (traceback).
import cgitb; cgitb.enable()

mapreduce wordcount example in using Octo module

I just started to learn mapreduce with Octo module with the word count example. I try to count the words in the dir hw3data (as specified below). My PC works as both the server and client.
I started with my windows cmd with 2 terminals
server: octo.py server wordcount.py
It seems the server side started without problem
client: octo.py client localhost
It seems that python can't find the txt files I stored in the hw3data dir, so it says no work, sleeping. So anyone can help?
The wordcount.py code is below
wordcount.py
server
import glob
text_files=glob.glob('C:/Python27/octopy-0.1/hw3data/*.txt')
def file_contents(file_name):
f=open(file_name)
try:
return f.read()
finally:
f.close()
source=dict((file_name,file_contents(file_name)) for file_name in text_files)
f=open('outfile','w')
def final(key,value):
print key,value
f.write(str((key,value)))
client
def mapfn(key,value):
for line in value.splitlines():
for word in line.split():
yield word.lower(),1
def reducefn(key,value):
return key,len(value)
Verify if your data files have a ".txt" in his names. I'm current working in this problem to my homework #3. Good Luck!
Change the following code
text_files=glob.glob('C:/Python27/octopy-0.1/hw3data/*.txt')
to
text_files=glob.glob('C:/Python27/octopy-0.1/hw3data/*')
and try. I guess the files in the folder do not have the extensions.

Categories