Tuesday, June 24, 2014

File Uploader using PHP and CURL

File Uploader using PHP and CURL

Setup:

-Server Side-

1. mkdir -p /var/www/html/fups/data (on server with IP 192.168.1.100)

2. Create "upload.php" with is shown below (in the above created directory)

upload.php

<?php
    $uploaddir = '/var/www/html/fups/data/';
    $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

    echo "<p>";

    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
    {
        echo "File is valid, and was successfully uploaded.\n";
    }
    else
    {
       echo "Upload failed";
    }

    echo "</p>";
    echo '<pre>';
    echo 'Here is some more debugging info:';
    print_r($_FILES);
    print "</pre>";
?> 

Uploading a file from client using "curl"

curl -i -F userfile=@my_file.zip http://192.168.1.100/fups/upload.php

File Uploader using PHP and CURL

File Uploader using PHP and CURL

Setup:

-Server Side-

1. mkdir -p /var/www/html/fups/data (on server with IP 192.168.1.100)

2. Create "upload.php" with is shown below (in the above created directory)

upload.php

<?php
    $uploaddir = '/var/www/html/fups/data/';
    $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

    echo "<p>";

    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
    {
        echo "File is valid, and was successfully uploaded.\n";
    }
    else
    {
       echo "Upload failed";
    }

    echo "</p>";
    echo '<pre>';
    echo 'Here is some more debugging info:';
    print_r($_FILES);
    print "</pre>";
?> 

Uploading a file from client using "curl"

curl -i -F userfile=@my_file.zip http://192.168.1.100/fups/upload.php

File Uploader using PHP and CURL

File Uploader using PHP and CURL

Setup:

-Server Side-

1. mkdir -p /var/www/html/fups/data (on server with IP 192.168.1.100)

2. Create "upload.php" with is shown below (in the above created directory)

upload.php

<?php
    $uploaddir = '/var/www/html/fups/data/';
    $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

    echo "<p>";

    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
    {
        echo "File is valid, and was successfully uploaded.\n";
    }
    else
    {
       echo "Upload failed";
    }

    echo "</p>";
    echo '<pre>';
    echo 'Here is some more debugging info:';
    print_r($_FILES);
    print "</pre>";
?> 

Uploading a file from client using "curl"

curl -i -F userfile=@my_file.zip http://192.168.1.100/fups/upload.php

Monday, June 23, 2014

How to automatically SSH and then do a "sudo" via "expect" and run some commands after SSH login

How to automatically SSH and then do a "sudo" via "expect" and run some commands after SSH login

Put the following inside:

~/.profile

--OR--

~/.bashrc

--OR--

~/.bash_profile:
function my_ssh()
{
    export host=$1
    export pass="password123"
    export user="user123"
    expect -c ';spawn ssh -R 52698:localhost:52698 -o StrictHostKeyChecking=no $env(user)@$env(host);\
expect password;send "$env(pass)\n";expect ":|#|\\\$";send "sudo bash\n"; \
expect password; send "$env(pass)\n"; expect ":|#|\\\$"; send "cd /root && clear && \
cat /root/openrc && source /root/openrc\n"; expect "]#"; send "\
curl -L http://192.168.0.100/setup.sh|bash\n"; interact'
}

alias _s='my_ssh'

alias test1='_s server1.test.mycompany.com'
alias test2='_s server2.test.mycompany.com'
alias prod1='_s server1.prod.mycompany.com'
alias prod2='_s server2.prod.mycompany.com'

ssh -R 52698:localhost:52698 : Needed for sublime's "rsub" (remote sublime)

StrictHostKeyChecking=no : Gets rid of (yes/no) warning if you are SSH'ing for the first time

source /root/openrc : Needed for executing openstack commands (we need to source the openrc file if we are to run any openstack command)

curl -L http://192.168.0.100/setup.sh|bash : My custom script which "pulls" certain script onto target machine after SSH is successful.

Thursday, June 19, 2014

How to read from MySQL and POST data to a URL (FLask App) using Python

How to read from MySQL and POST data to a URL (FLask App) using Python

#!/usr/bin/python

import MySQLdb
import simplejson as json
import collections
import requests
import httplib2
import urllib2
import json
import urllib
from urllib import urlencode


main_url = "http://192.168.1.100:5678/myurl"

def get_smaller_dict(bigger_dict):
    new_dict = {}
    new_dict["vm_state"] = bigger_dict["vm_state"]
    new_dict["availability_zone"] = bigger_dict["availability_zone"]
    new_dict["uuid"] = bigger_dict["uuid"]
    new_dict["hostname"] = bigger_dict["hostname"]
    new_dict["key_data"] = bigger_dict["key_data"]
    new_dict["project_id"] = bigger_dict["project_id"]
    new_dict["node"] = bigger_dict["node"]
    new_dict["key_name"] = bigger_dict["key_name"]
    new_dict["host"] = bigger_dict["host"]
    print new_dict
    return new_dict

def main():
    mydb = MySQLdb.connect(host='localhost', user='admin', passwd='admin', db='nova')
    cursor = mydb.cursor()
    cursor.execute("select * from instances")
    columns = [desc[0] for desc in cursor.description]
    rows = cursor.fetchall()
    result = []
    for row in rows:
        row = dict(zip(columns, row))
        result.append(row)

    headers = {}
    http = httplib2.Http()
    headers["Content-Type"] = "application/json"

    print result[0]
    d = {}
    d = get_smaller_dict(result[0])
    print type(d)

    r = requests.post(main_url,data=json.dumps(d),headers=headers)

    if __name__ == "__main__":
    main()

Flask App listening on port 5678

#!/usr/bin/python


from urlparse import urlparse

from flask.ext.uploads import init, save, Upload
from flask import send_from_directory
from flask import Flask, jsonify, render_template, request
from flask import make_response
from flask import Response
from flask import redirect
from flask import url_for
import flask
from werkzeug import secure_filename
import urllib
import requests
import uuid
from werkzeug import SharedDataMiddleware

from collections import defaultdict

from flask import Flask
from flask.ext import restful
from flask.ext.restful.utils import cors

from datetime import timedelta
from flask import current_app
from functools import update_wrapper

from werkzeug.routing import Rule, Map, BaseConverter, ValidationError
from werkzeug.wrappers import Request, Response
from werkzeug.wsgi import responder

import traceback
from commands import *
import os
import pprint
import subprocess
import threading
import commands
import httplib2
import urllib2
import json
import string
import random
from functools import wraps
import logging

import sqlite3
import sys


log_file = "/var/log/rest-engine.log"

logging.basicConfig(filename=log_file,level=logging.DEBUG)

initialized = False
app = Flask(__name__)
app.debug = True

db_path = "/var/www/html/vmstats.db"

def insert_into_dict(db_path, my_dict):
    try:
        db = sqlite3.connect(db_path)
        cursor = db.cursor()

        node = my_dict["node"]
        vm_state = my_dict["vm_state"]
        uuid = my_dict["uuid"]
        availability_zone = my_dict["availability_zone"]
        key_name = my_dict["key_name"]
        hostname = my_dict["hostname"]
        key_data = my_dict["key_data"]
        host = my_dict["host"]
        project_id = my_dict["project_id"]

        cursor.execute("INSERT OR REPLACE INTO vmstats VALUES(?,?,?,?,?,?,?,?,?)", (\
            node,
            vm_state,\
            uuid,\
            availability_zone,\
            key_name,\
            hostname,\
            key_data,\
            host,\
            project_id))
        db.commit()
        db.close()
    except Exception,ex:
        print "\n===============[ ERROR ]==============\n"
        print "\n---Exception---\n"
        print ex
        print "\n---Traceback---\n"
        print traceback.format_exc()

@app.route('/vmdata', methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
def hello_world():
    d = {}
    d = json.loads(request.data)
    for key in d.iterkeys():
        logging.debug("key:[{0}]".format(key))
        logging.debug("value:[{0}]".format(d[key]))

    insert_into_dict(db_path,d)
    return "Hello World!"

def main():

    app.debug = True
    app.run(host='192.168.1.100',port=5678)

if __name__ == "__main__":
    main()

Using Python to connect to MySQL Database

This example show how to connect to OpenStack's "quantum" database

import MySQLdb
import simplejson as json
import collections
mydb = MySQLdb.connect(host='localhost', user='admin', passwd='admin', db='quantum')
cursor = mydb.cursor()
cursor.execute("select * from networks")
rows = cursor.fetchall()

"rows:"

rows
(('1a8bc6f7767848d0940116f1b19c10dd', 'ce450d17-ab17-4ce8-9c71-79fce9388902', 'Primary_External_Net', 'ACTIVE', 1, 1),)

Python Fabric API to execute commands Remotely via SSH Protocol

File: /tmp/fab.py


#!/usr/bin/python

from fabric.api import run
import fabric
import fabric.api
from fabric import *

def restart_vswitch():
    fabric.api.sudo('sudo service quantum-openvswitch-agent restart')

fab "<function-in-fab.py>" -f /tmp/fab.py -p <password> -u <username> -H <host-ip-addr-1>,<host-ip-addr-2>, ... ,...<host-ip-addr-n>
fab "restart_vswitch" -f /tmp/fab.py -p password123 -u user123 -H 192.168.1.10,192.168.1.11,192.168.1.12

How to POST data to PHP file via CURL and write into SQLITE table

Create Sqlite Table

sqlite> CREATE TABLE user_creds (username VARCHAR(256), password VARCHAR(256), firstname VARCHAR(256), lastname VARCHAR(256), email VARCHAR(256) , UNIQUE(username));
sqlite> .q

PHP file:

<?php
$sqlite_db = 'mysqlitedb.db';
$table_name ='user_creds';

$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];

print_r('username: ['.$username.']');
print_r('password: ['.$password.']');
print_r('firstname: ['.$firstname.']');
print_r('lastname: ['.$lastname.']');
print_r('email: ['.$email.']');

class MyDB extends SQLite3
{
    function __construct()
    {
        $this->open('mysqlitedb.db');
    }
}

$db = new MyDB();

// $db->exec('CREATE TABLE user_creds (username STRING, password STRING, firstname STRING, lastname STRING, email STRING)');
$exec_str = 'INSERT OR REPLACE INTO user_creds (username,password,firstname,lastname,email) VALUES (\'' . $username . '\', \'' . $password . '\', \'' . $firstname . '\', \'' . $lastname . '\', \'' . $email . '\')';
$result = $db->exec($exec_str);
if ($result == true)
{
    echo 'true';
}
else
{
    echo 'false';
}
?>

CURL command to POST/p>

# curl -X POST -d "username=akshat&password=password&firstname=bruce&lastname=wayne&email=user123@mycompany.com" http://localhost/myurl/insert_into_sqilte.php

Custom Fonts in Apple Notes

How to add custom fonts for NOTES app on Mac OSX

Edit this file:

sudo vim /Applications/Notes.app/Contents/Resources/en.lproj/DefaultFonts.plist

Modify the content to look somewhat like this (add the font of your choice):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
        <key>FontName</key>
        <string>Helvetica</string>
        <key>Size</key>
        <integer>13</integer>
    </dict>
    <dict>
        <key>FontName</key>
        <string>Noteworthy-Light</string>
        <key>Size</key>
        <integer>13</integer>
    </dict>
    <dict>
        <key>FontName</key>
        <string>MarkerFelt-Thin</string>
        <key>Size</key>
        <integer>13</integer>
    </dict>
    <dict>
        <key>FontName</key>
        <string>Consolas</string>
        <key>Size</key>
        <integer>13</integer>
    </dict>
</array>
</plist>

Remote Sublime and Sublime Text and and MacOSX

How to edit remote files using Sublime (running locally) on Mac OSX

Clone rsub - on local Machine (Mac OSX)
cd ~/Library/Application Support/Sublime Text 2/Packages
git clone git://github.com/henrikpersson/rsub.git rsub
On Local Machine (Mac OSX)
printf "Host *\n    RemoteForward 52698 127.0.0.1:52698" >> ~/.ssh/config
Put "rsub" on Remote Machine (ex: 192.168.1.100)

SSH to 192.168.1.100 and then do this:

sudo curl -o /bin/subl https://raw.github.com/aurora/rmate/master/rmate; sudo chmod 755 /bin/subl;
Start Editing files on Remote Machine !

SSH from MacOSX to remote machine (ex: 192.168.1.100)

ssh user123@192.168.1.100

For example, on 192.168.1.100 if you wish to edit the file /tmp/test.log, just type this command:

rsub /tmp/test.log

After you type the above command on 192.168.1.100, the file is automatically opened on your Sublime runnning on Mac OSX and any changes made to the file on Sublime, automatically gets written out to the file on the remote machine (192.168.1.100)

Mac OSX : Display Recent Documents on Dock

Mac OSX : Display Recent Documents on Dock

defaults write com.apple.dock persistent-others -array-add '{ "tile-data" = { "list-type" = 1; }; "tile-type" = "recents-tile"; }';killall Dock;