Skip to main content

Posts

Showing posts from November, 2013

Python: Replace a string at all occurrence in all files in a directory, including files in sub-directories

Now this is for all super lazy out there. Replace a string at all occurrence in all files in a directory, including files in sub-directories. Works with python 2.x.

--------------------------------------------------------------------------------------
import os
import fileinput
import sys
#from fnmatch import fnmatch

root = '/root/mypython/log'
names = []
for path, subdirs, files in os.walk(root):
    for name in files:
        filenames = os.path.join(path, name)
        names.append(filenames)
for item in names:
    for line in fileinput.input(item, inplace=True):
        line = line.replace('linux', 'android')
        sys.stdout.write(line)
    print 'String replaced in ' + item

Python: Random password generator, length of password given by user

Hi, you can increase the characters to generate the password by inserting new characters in the variable 'seq'. Works in Python 3.x

----------------------------------------------------------------------------------------


import random
a= random.randint(100000000, 900000000)
a = str(a)
c = ''
for x in range (1, 50):
    seq='qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*()+'
    b=random.choice(seq)
    c= c + b
d= a + c
password = list(d)
random.shuffle(password)
result = ''.join(password)

while True:
    num = int(input('Enter the length of password between 5 to 50 '))
    if num > 50 or num < 5:
        print('Inefficient or insufficient length provided')
    else:
        break

while True:
    if len(result) > num:
        result = result[1:]
    else:
        break
print(result)
input()

Python: Log on to a server, run a command, and store the output in a text file.

Do you need to go to a server everytime to see something, like a log file, or to create daily report ( Like me !! ). This is the end of all your miseries. 

1. You need to install paramiko for this:

https://pypi.python.org/pypi/paramiko

2. alert.txt is the name of the file where the output will be saved. This will be create in same folder as the script. 

--------------------------------------------------------------------------------------


import os
import sys
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.123.128', username='root', password='superlazy')
stdin, stdout, stderr = ssh.exec_command("tail -20 /home/alert.log")
sys.stdout = open('alert.txt', 'w')
type(stdin)
print stdout.readlines()
sys.stdout.close()
ssh.close()

Python: Create a daemon in Linux to empty log file every 10 seconds

This script will run a daemon and will clear any log mentioned in variable cmd1 every 10 seconds. Two things:

1. You need to install python-daemon to run this.

https://pypi.python.org/pypi/python-daemon/

2. It is not a simple python script, so you can't run it using ./mydaemon.py. You have to run it by using ./mydaemon.py start.

3. Again, you can't stop this script by "Ctrl + C" . You have to use./mydaemon.py stop

4. Works with python 2.x

-------------------------------------------------------------------------------

#!/usr/bin/python
import time
import os
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/foo.pid'
        self.pidfile_timeout = 5
    def run(self):
        while True:
            print "Going to clear log !! "
            cmd1 = 'cat /dev/null > /var/log/mysqld.lo…

Python: Move all files to a single directory without subdirectories

Hi friends,

Below script will move all files in a folder, without subdirectory. Means if you have structure like this :



Then all files in folders Program files, 7-Zip, Lang, CCleaner, Common Files, DESIGNER, logishrd, Microsoft shared, DW EQUATION, 1033 will be moved to a single folder. In this destination, there will be only files and no folders. 

Also, if any file with same name exits already, it will rename the new file as filename_1. If filename_1 also exits, it will rename it as filename_2 and so on. Works with python 3.x.

-----------------------------------------------------------------------------------------

import os
import os.path
import fileinput
import sys
import shutil
#from fnmatch import fnmatch

#root = '/root/mypython/log'

src1 = 'D:\\doc'
des1 = 'E:\\vbox'


def check_file(self, n):

    name = '.'.join(self.split('.')[:-1])
    ext = self.split('.')[-1]

    if n==1:
        temp=self
    else:
        temp=name +'_'+ str(n) + '.&#…

Python : Automatic Apache Configuration

Yes, no need to open httpd.conf everytime. If you want to create a new website on your server, this is it. It will make changes to your httpd.conf file, make a empty folder (root document) for putting code, create database for your site in mysql, change permission and ownership of the root document and then restart the apache service. Works on python 2.x
----------------------------------------------------------------------------------------


import os
from io import open
project = raw_input(u'Enter the name of site ')
domain = raw_input (u'Enter the domain ')
docroot = raw_input(u'Enter root folder that should be created ')
virtualhost=u"""
<VirtualHost *:80>
    ServerAdmin scripto@gkmail.com
    DocumentRoot /""" +docroot+ u"""/""" +project+ u"""
    ServerName """ +project+ u""".""" +domain+ u""".com
    ErrorLog logs/""&…

Python : Add prefix and suffix to each line of a text

The below script add a prefix and a suffix to each line of a text. This script opens a notepad, you need to paste the text, and close the notepad after saving. The notepad opens again, automatically, showing the result. Works on windows with python 3.x



import subprocess
import fileinput
import sys

prefix = input('Enter the prefix ')
suffix = input('Enter the suffix ')
open('mytext.txt', 'w').close()
subprocess.call(['notepad.exe', 'mytext.txt'])
for line in fileinput.input('mytext.txt', inplace=True):
    line = line.rstrip()
    line = prefix + ' ' + line + ' ' + suffix + '\n'
    sys.stdout.write(line)
subprocess.call(['notepad.exe', 'mytext.txt'])