Python cannot print the client IP or client hostname - python

How can I print the IP or hostname of the client pc who delete a file in my shared folder?This code is working but it only print my own IP and Hostname not the other pc that delete a file inside my shared folder.
Im using Centos 6.3.I use Samba to share my folder.I use Python 2.7 and PYinotify script.
This is my code
import pyinotify
wm = pyinotify.WatchManager()
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE
class EventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
print "",now.strftime("%b-%d-%Y # %I:%M %p")," " ,socket.gethostname()," ","Create "," ",event.name," ",event.path
def process_IN_DELETE(self, event):
print "",now.strftime("%b-%d-%Y # %I:%M %p")," " ,socket.gethostname()," ","Shift+Del","",event.name," ",event.path
handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler)
wdd = wm.add_watch('/echoshare', mask, rec=True)
auto_add = '/echoshare'
notifier.loop()

I think you misunderstand what (py)inotify is.
It is a way to monitor filesystem events and you will get information about operations done by samba server on local filesystem.
If you take a look on inotify documentation you will notice that inotify_event structure does not carry any information about user performing the operations.
I guess a simplest solution to you problem would be to enable event logging on your samba server and parse generated events for information you want

Related

Python os.mkdir still creates folders locally even after connecting to SSH server using Paramiko

The principle of the script is that it should connect from one virtual machine to another via an SSH connection and generate a certain number of folders.
The script runs, but when executed, generates folders on the host machine.
import os
from paramiko import SSHClient, AutoAddPolicy
from sys import argv
address = argv[1]
port = int(argv[2])
name = argv[3]
path = argv[4]
prefix = argv[5]
counts = int(argv[6])
mode = int(argv[7])
def generateFolders(path, prefix, counts, mode):
for i in range(1, counts+1):
folderName = prefix + str(i)
pth = os.path.join(os.path.expanduser('~'), path, folderName)
os.mkdir(pth, mode)
command = generateFolders(path, prefix, counts, mode)
print(address)
client1 = SSHClient()
client1.set_missing_host_key_policy(AutoAddPolicy())
client1.connect(address, username=name, password='1')
stdin, stdout, stderr = client1.exec_command(command)
print(stdout.read())
client1.close()
The command in the terminal
But without a script, I can connect to another virtual machine
Jane, its making dirs on your local box because that is where the python script is running.
I suggest you look at this question and answer.
In that QandA, they show how to use ssh on the local box to execute commands on a remote box. You could use your existing code as the code which is run on the remote box using the above as your guide.
Specifically this this one
The os.mkdir creates folders on the local machine. It won't magically start working on a remote machine only because you have previous opened SSH connection to that machine (and you actually even did not, as you open it only after calling os.mkdir).
To create a folder on a remote machine via Paramiko module, use SFTPClient.mkdir.
sftp = client1.open_sftp()
for i in range(1, counts+1):
folderName = prefix + str(i)
pth = os.path.join(os.path.expanduser('~'), path, folderName)
sftp.mkdir(pth, mode)
Though you should not use os.path on SFTP paths as your code will break, if run on Windows and other platforms, that does not use / as a path separator. And os.path.expanduser will of course expand ~ to local user home. I do not think you want that.
Obligatory warning: Do not use AutoAddPolicy on its own – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".

How can I launch an Android app on a device through Python?

I have consulted several topics on the subject, but I didn't see any related to launching an app on a device directly using a ppadb command.
I managed to do this code:
import ppadb
import subprocess
from ppadb.client import Client as AdbClient
# Create the connect functiun
def connect():
client = AdbClient(host='localhost', port=5037)
devices = client.devices()
for device in devices:
print (device.serial)
if len(devices) == 0:
print('no device connected')
quit()
phone = devices[0]
print (f'connected to {phone.serial}')
return phone, client
if __name__ == '__main__':
phone, client = connect()
import time
time.sleep(5)
# How to print each app on the emulator
list = phone.list_packages()
for truc in list:
print(truc)
# Launch the desired app through phone.shell using the package name
phone.shell(????????????????)
From there, I have access to each app package (com.package.name). I would like to launch it through a phone.shell() command but I can't access the correct syntax.
I can execute a tap or a keyevent and it's perfectly working, but I want to be sure my code won't be disturbed by any change in position.
From How to start an application using Android ADB tools, the shell command to launch an app is
am start -n com.package.name/com.package.name.ActivityName
Hence you would call
phone.shell("am start -n com.package.name/com.package.name.ActivityName")
A given package may have multiple activities. To find out what they are, you can use dumpsys package as follows:
def parse_activities(package, connection, retval):
out = ""
while True:
data = connection.read(1024)
if not data: break
out += data.decode('utf-8')
retval.clear()
retval += [l.split()[-1] for l in out.splitlines() if package in l and "Activity" in l]
connection.close()
activities = []
phone.shell("dumpsys package", handler=lambda c: parse_activities("com.package.name", c, activities))
print(activities)
Here is the correct and easiest answer:
phone.shell('monkey -p com.package.name 1')
This method will launch the app without needing to have acces to the ActivityName
Using AndroidViewClient/cluebra, you can launch the MAIN Activity of a package as follows:
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from com.dtmilano.android.viewclient import ViewClient
ViewClient.connectToDeviceOrExit()[0].startActivity(package='com.example.package')
This connects to the device (waiting if necessary) and then invokes startActivity() just using the package name.
startActivity() can also receive a component which is used when you know the package and the activity.

getting eventlogs from Applications and Services log using python

I am trying to read event logs from Applications and Services log using python. However the output are not as expected. (Actual 10 vs output 838)
I am using the following code. Was wondering if there is a mistake with the parameters.
import win32evtlog
server = 'localhost'
logtype = "Microsoft-Windows-Storage-Storport/Operational"
hand = win32evtlog.OpenEventLog(server, logtype)
flags = win32evtlog.EVENTLOG_FORWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
while True:
events = win32evtlog.ReadEventLog(hand, flags,0)
if events:
for event in events:
print ('Source Name:', event.SourceName)
print ('Event ID:', event.EventID)
print ('Time Generated:', event.TimeGenerated)
Found a method to get the information through the use of powershell using python.
import subprocess
getinfo = subprocess.check_output(
['powershell.exe', 'get-Winevent Microsoft-Windows-xxx/Operational'])
where xxx is a variable

How to define more than one server environment in Fabric(Python)?

I need to use Fabric to do some operations in a website that use one machine for the filesystem and other machine to the database server. I need to handle two hosts. How can I do that?
I have some code but I cannot get the environment definition to work.
The idea is to connect to the remote Filesystem server and get the files and then connect to the remote Database server and get the database schema.
The code that I have for now is something like this:
from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm
'''
Here I define where is my "aid"s file structure
'''
local_root = '/home/andre/test' # This is the root folder for the audits
code_location = '/remote_code' # This is the root folder dor the customer code inside each audit
#
# ENVIRONMENTS CONFIGURATIONS
#
'''
Here I configure where is the remote file server
'''
def file_server():
env.user = 'andre'
env.hosts = ['localhost']
'''
Here I configure where is the database server
'''
def database_server():
env.user = 'andre'
env.hosts = ['192.168.5.1']
#
# START SCRIPT
#
def get_install(remote_location, aid):
### I will get the files
'''
Here I need to load the file_server() definitions
'''
working_folder = local_root + '/%s' % aid # I will define the working folder
local('mkdir ' + working_folder) # I will create the working folder for this audit
local('mkdir ' + working_folder + code_location) # I will create the folder to receive the code
get(remote_location, working_folder + code_location) # I will download the code to my machine
### I will get the database
'''
Here I need to load the database_server() definitions
'''
local('dir') # Just to test
How can I inside get_install() define the environments file_server() and database_server() ?
Best Regards,
I don't understand exactly what you are trying to do, but maybe you can split up your get_install function into two functions each for every server.
Then limit those functions to the correct servers with fabric.decorators.hosts(*host_list) decorator:
For example, the following will ensure that, barring an override on the command line, my_func will be run on host1, host2 and host3, and with specific users on host1 and host3:
#hosts('user1#host1', 'host2', 'user2#host3')
def my_func():
pass
(For more info see http://readthedocs.org/docs/fabric/en/1.1.0/api/core/decorators.html#fabric.decorators.hosts)
And you can than call those 2 functions in one go by defining your get_install method as:
def get_install():
func1()
func2()
You should be able to do this with fab database_server get_install. Basically, fab [environment] [command] should do what you want.

Is it possible to have SimpleHTTPServer serve files from two different directories?

If I do python -m SimpleHTTPServer it serves the files in the current directory.
My directory structure looks like this:
/protected/public
/protected/private
/test
I want to start the server in my /test directory and I want it to serve files in the /test directory. But I want all requests to the server starting with '/public' to be pulled from the /protected/public directory.
e.g.a request to http://localhost:8000/public/index.html would serve the file at /protected/public/index.html
Is this possible with the built in server or will I have to write a custom one?
I think it is absolutely possible to do that. You can start the server inside /test directory and override translate_path method of SimpleHTTPRequestHandler as follows:
import BaseHTTPServer
import SimpleHTTPServer
server_address = ("", 8888)
PUBLIC_RESOURCE_PREFIX = '/public'
PUBLIC_DIRECTORY = '/path/to/protected/public'
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def translate_path(self, path):
if self.path.startswith(PUBLIC_RESOURCE_PREFIX):
if self.path == PUBLIC_RESOURCE_PREFIX or self.path == PUBLIC_RESOURCE_PREFIX + '/':
return PUBLIC_DIRECTORY + '/index.html'
else:
return PUBLIC_DIRECTORY + path[len(PUBLIC_RESOURCE_PREFIX):]
else:
return SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self, path)
httpd = BaseHTTPServer.HTTPServer(server_address, MyRequestHandler)
httpd.serve_forever()
Hope this helps.
I think I have found the answer to this, basically it involves changing the current working directory, starting the server and then returning back to your original working directory.
This is how I achieved it, I've commented out two sets of options for you, as the solution for me was just moving to a folder within my app directory and then back up one level to the original app directory. But, you might want to go to an entire other directory in your file system and then return someplace else or not at all.
#Setup file server
import SimpleHTTPServer
import SocketServer
import os
PORT = 5002
# -- OPTION 1 --
#os.chdir(os.path.join(os.path.abspath(os.curdir),'PATH_TO_FOLDER_IN_APP_DIR'))
# -- OPTION 2 --
#os.chdir('PATH_TO_ROOT_DIRECTORY')
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
# -- OPTION 1 --
#os.chdir(os.path.abspath('..'))
# -- OPTION 2 --
#os.chdir('PATH_TO_ORIGINAL_WORKING_DIR')
Let me know how it works out!
I do not believe SimpleHTTPServer has this feature, however if you use a symbolic link inside of /test that points to /protected/public, that should effectively do the same thing.

Categories