Skip to content

Running a python script with sudo from PHP script remotely

When trying to execute a python script from a PHP script with sudo, error is returned:
sudo: no tty present and no askpass program specified

Add the following to sudoers file (visudo) to fix the issue:

%www-data ALL=(ALL) NOPASSWD: /usr/bin/python /path/to/scripts/*

SailsJS on Apache : Crib Notes

To forward a URL to a specific port on machine (ie. the Sails default is 1337), create a conf file under sites-available with the following:

<VirtualHost *:80>

ServerName [DOMAINNAME].com
ServerAlias www.[DOMAINNAME].com

ServerAdmin admin@[ADMINEMAIL].com

#this handles forwarding of the socket connection
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/socket.io [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /(.*) ws://localhost:1337/$1 [P,L]

#this is the port forwarding magic
ProxyRequests off
ProxyPass / http://127.0.0.1:1337/
ProxyPassReverse / http://127.0.0.1:1337/

#debugging settings
LogLevel debug
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

 

Then from CLI, enable the following mods:

sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_wstunnel

 

And restart apache:

sudo apache2ctl restart

 

Next, install forever:

sudo npm install -g forever

 

And, in the root directory of the Sails app, to run in production (as opposed to

sails lift

) run:

forever start app.js --prod

 

Make sure the migrate option has been defined, or the application will not run (it hangs in memory waiting for a migrate selection). So in config/models.js:

module.exports.models = {
 ...
 migrate: 'safe',
 ...
};

Blocking (and Unblocking) IP address in Ubuntu

//this ADDS the rule to iptables to block ip address
iptables -A INPUT -s ipa.ddr.ess -j DROP

//this DELETES the rule from iptables
iptables -D INPUT -s ipa.ddr.ess -j DROP

Symfony2 404 file not found SOLVED /web/app_dev.php/

My intial problem was that while /web/app_dev.php would load (without a trailing slash), the trailing slash produced:

Not Found
The requested URL /web/app_dev.php/ was not found on this server.

This was a functioning Symfony2 install I’d successfully migrated between local servers, so I knew the code was correct.

It turns out the issue was with apache2filter – or more specifically: libapache2-mod-php5filter

I uninstalled libapache2-mod-php5filter – the systmn automatically replaced it with libapache2-mod-php5 – and /etc/php5/apache2filter was repalced with /etc/php5/apache2

Suddenly my install worked!!!!
Thank you interwebz.

Dump and Restore (Export and Import) MongoDB Data

VERY simple. Assuming you have MongoDB running…

From shell, the following will dump the entire mongo contents into a directory ‘dump’ in the current directory

mongodump

Then, simply rsync the dump dir to the target machine

rsync -azvv [localpath] [user]@[remotehost]:[remotepath]

SSH into the remote machine, navigate to the dump’s parent directory, and run:

mongorestore

MongoDB AJAX User Authentication in Symfony2 (2.1)

This was a pain to figure out… in the end the solution was pretty simple, but the dang interwebz have a bunch of old information!!!!

There’s a thread about defining DocumentUserProvider as a service… but in 2.1m with mongodb-odm Doctrine 3.0.* configured in composer (as outlined in the docs on installing mongo) there IS NO DocumentUserProvider.

The following goes in app/config/security.yml


# this calls my custom encoder (see below)
encoders:
    MyProject\MyBundle\Document\User:
            id: security.custom_encoder

# this implements the User document, matching against email
providers:
    default:
        mongodb: {class: MyProjectMyBundle:User, property: email }

The custom encoder id is defined under my SecurityBundle services.yml, as well as a customized authentication handler


parameters:
    security.authentication_handler: MyProject\SecurityBundle\Handler\AuthenticationHandler
    security.custom_encoder: MyProject\SecurityBundle\Service\CustomPasswordEncoder

services:
    authentication_handler:
        class:  %security.authentication_handler%
        arguments:  [@router]
        tags:
            - { name: 'monolog.logger', channel: 'security' }

    security.custom_encoder:
        class: %security.custom_encoder%

The authentication handler service leads to a custom handler to handle AJAX requests specially – returning a success string in JSON format. You can see more about that here. It’s a bit outdated, but you can likely figure out the implementation.

Here’s the custom encoder – with help I got from here. I simplified the encoding… you can use any method to create $encodedPassword:

namespace MyProject\SecurityBundle\Service;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
 
class CustomPasswordEncoder implements PasswordEncoderInterface {
 
    public function encodePassword( $raw, $salt ) {
        $encodedPassword = $raw.$salt;
        return $encodedPassword;
    }
 
    public function isPasswordValid( $encoded, $raw, $salt ) {
        return $encoded === $this->encodePassword( $raw, $salt );
    }
 
}

So with all this figured out, my default login functionality WORKS!
WOO HOO!!!!

MySQL CLI SELECT into file

SELECT first, middle, last, designation, membertype, practicestatus, address, city, province, education, employment, company_1, position_1, company_2, position_2, company_3, position_3, company_4, position_4, company_5, position_5, company_6, position_6, scope FROM apega INTO OUTFILE '/tmp/apega.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

Move WordPress site to new server through command line

This is a VERY short synopsis for experienced administrators. There are no examples, just a quick outline.

– On current (old) server, mysqldump the WP db (tip: create the dump in the root of the site)

– On new server, create a new virtual host and enable it via a2ensite
– Navigate to the new site’s root (should be empty!)
– scp (or rsync?) the old server WordPress to the new site directory (will include the mysql dump if it’s in the site’s root!)
– scp the .htaccess file explicitly (rsync does this natively?)
– sed the WP db dump to replace the old absolute path entries (if applicable)
– sed the WP db dump to replace the URL with the new URL
– Create the MySQL db, and import the dump
– chown the site directory to user managing site
– chmod the entire site recursively 0755
– chmod wp-content/uploads to 0777 [IMPORTANT!!!]

That’s it!

Using sed to search and replace text inline

sed -i -e ‘s/[searchtext]/[replacetext]/g’ [filename]

selenium 2.2 for python 2.7 on ubuntu server 11.04 using webdriver REMOTELY!!!

After much trial and error, I created a very simple but powerful scraper using selenium webdriver, using the Ubuntu command-line, after having installed Selenium for Ubuntu. I probably could have figured out RemoteWebDriver, but this solution worked pretty awesome.

The key to my success was pyvirtualdisplay!

Prior to discovering pyvirtualdisplay, I kept receiving the following error:
‘The browser appears to have exited before we could connect. The output was: Error: no display specified\n’

This was incredibly frustrating. It turns out, because I was working remotely, I couldn’t ‘fire up’ Firefox on the remote machine. I discovered this because I tried running the script locally on the remote machine, and it worked. But SSH into the server and it didn’t work – ERROR!

pyvirtualdisplay allows the Selenium script to suppress the browser from displaying and averts the error from command line.

Try it! :


from pyvirtualdisplay import Display
from selenium import webdriver

#initialize HIDDEN display
display = Display(visible=0, size=(800, 600))
display.start()

#initialize webdriver
browser = webdriver.Firefox()

browser.get('http://www.google.com')
print browser.title

browser.quit() #important, or else loaded browser will remain running as a bg proc!
display.stop()

Create your own website, free on WordPress.com.Create your own website.
Start free