paypal plugin
quinta-feira, 11 de dezembro de 2014
segunda-feira, 27 de outubro de 2014
sábado, 17 de maio de 2014
ubuntu 14.04 web2py sh
https://code.google.com/p/web2py/source/browse/scripts/setup-web2py-nginx-uwsgi-ubuntu.sh
quinta-feira, 13 de fevereiro de 2014
nginx config
cat /etc/nginx/nginx.conf
user www-data;
worker_processes 4;
pid /var/run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
uwsgi_read_timeout 60000;
proxy_connect_timeout 60000;
proxy_send_timeout 60000;
proxy_read_timeout 60000;
send_timeout 60000;
client_max_body_size 50M;
##
# Basic Settings
##
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
##
# nginx-naxsi config
##
# Uncomment it if you installed nginx-naxsi
##
#include /etc/nginx/naxsi_core.rules;
##
# nginx-passenger config
##
# Uncomment it if you installed nginx-passenger
##
#passenger_root /usr;
#passenger_ruby /usr/bin/ruby;
##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
#mail {
# # See sample authentication script at:
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
# # auth_http localhost/auth.php;
# # pop3_capabilities "TOP" "USER";
# # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
# server {
# listen localhost:110;
# protocol pop3;
# proxy on;
# }
#
# server {
# listen localhost:143;
# protocol imap;
# proxy on;
# }
#}
user www-data;
worker_processes 4;
pid /var/run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
uwsgi_read_timeout 60000;
proxy_connect_timeout 60000;
proxy_send_timeout 60000;
proxy_read_timeout 60000;
send_timeout 60000;
client_max_body_size 50M;
##
# Basic Settings
##
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
##
# nginx-naxsi config
##
# Uncomment it if you installed nginx-naxsi
##
#include /etc/nginx/naxsi_core.rules;
##
# nginx-passenger config
##
# Uncomment it if you installed nginx-passenger
##
#passenger_root /usr;
#passenger_ruby /usr/bin/ruby;
##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
#mail {
# # See sample authentication script at:
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
# # auth_http localhost/auth.php;
# # pop3_capabilities "TOP" "USER";
# # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
# server {
# listen localhost:110;
# protocol pop3;
# proxy on;
# }
#
# server {
# listen localhost:143;
# protocol imap;
# proxy on;
# }
#}
segunda-feira, 10 de fevereiro de 2014
function SMTPLIB playground
def sendEmail(TO = "sharkguto@localhost",FROM="sharkguto@localhost",CC="sharkguto@localhost",filePath=r"",nome=""):
diadasemana={"Monday":"Segunda-Feira",
"Tuesday":"Terça-Feira",
"Wednesday":"Quarta-Feira",
"Thursday":"Quinta-Feira",
"Friday":"Sexta-Feira",
"Saturday":"Sabado",
"Sunday":"Domingo"}
HOST = "localhost"
filePathass= "/home/www-data/web2py/applications/testing/static/temp/assinatura.jpg"
msg = MIMEMultipart()
msg["From"] = FROM
msg["To"] = TO
msg["Cc"] = CC
dday = datetime.now()
subval= "[Nice]spreedsheet %s - %s" % (dday.strftime('%Y-%m'),nome)
msg["Subject"] = subval
msg['Date'] = formatdate(localtime=True)
dday = date(dday.year,dday.month,14)
html1 = """<p>Aooooo silver</p><br />"""
html3 = """<br /><p style="color:red">%s %s</p><br /><br /><br />""" % (dday,diadasemana[dday.strftime('%A')])
html2 = """<br /><br /><table border="1">
<tr>
<th>test 1</th>
<th>test 2</th>
</tr>
<tr>
<td style="text-align: center;"><b style="color:red">A pagar</b></td>
<td style="text-align: center;"><b style="color:red">%s</b></td>
</tr>
<tr>
<td style="text-align: center;"><b style="color:blue">A compensar</b></td>
<td style="text-align: center;"><b style="color:blue">%s</b></td>
</tr>
""" % (400,500)
part1 = MIMEText(html1, 'html')
part2 = MIMEText(html2, 'html')
part3 = MIMEText(html3, 'html')
# attach a file
part = MIMEBase('application', "octet-stream")
part.set_payload( open(filePath,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filePath))
img_data = open(filePathass, 'rb').read()
img = MIMEImage(img_data, 'jpeg')
img.add_header('Content-Id', '<myimage>') # angle brackets are important
msg.attach(part1)
msg.attach(part)
msg.attach(part2)
msg.attach(part3)
msg.attach(img)
server = smtplib.SMTP(HOST)
# server.login(username, password) # optional
try:
toaddr = TO
cc = [CC]
bcc = ['']
toaddrs = [toaddr] + cc + bcc
failed = server.sendmail(FROM, toaddrs, msg.as_string())
server.close()
statusemail= "Email enviado com sucesso para %s" % TO
print statusemail
return statusemail
except Exception, e:
errorMsg = "Unable to send email. Error: %s" % str(e)
return errorMsg
diadasemana={"Monday":"Segunda-Feira",
"Tuesday":"Terça-Feira",
"Wednesday":"Quarta-Feira",
"Thursday":"Quinta-Feira",
"Friday":"Sexta-Feira",
"Saturday":"Sabado",
"Sunday":"Domingo"}
HOST = "localhost"
filePathass= "/home/www-data/web2py/applications/testing/static/temp/assinatura.jpg"
msg = MIMEMultipart()
msg["From"] = FROM
msg["To"] = TO
msg["Cc"] = CC
dday = datetime.now()
subval= "[Nice]spreedsheet %s - %s" % (dday.strftime('%Y-%m'),nome)
msg["Subject"] = subval
msg['Date'] = formatdate(localtime=True)
dday = date(dday.year,dday.month,14)
html1 = """<p>Aooooo silver</p><br />"""
html3 = """<br /><p style="color:red">%s %s</p><br /><br /><br />""" % (dday,diadasemana[dday.strftime('%A')])
html2 = """<br /><br /><table border="1">
<tr>
<th>test 1</th>
<th>test 2</th>
</tr>
<tr>
<td style="text-align: center;"><b style="color:red">A pagar</b></td>
<td style="text-align: center;"><b style="color:red">%s</b></td>
</tr>
<tr>
<td style="text-align: center;"><b style="color:blue">A compensar</b></td>
<td style="text-align: center;"><b style="color:blue">%s</b></td>
</tr>
""" % (400,500)
part1 = MIMEText(html1, 'html')
part2 = MIMEText(html2, 'html')
part3 = MIMEText(html3, 'html')
# attach a file
part = MIMEBase('application', "octet-stream")
part.set_payload( open(filePath,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filePath))
img_data = open(filePathass, 'rb').read()
img = MIMEImage(img_data, 'jpeg')
img.add_header('Content-Id', '<myimage>') # angle brackets are important
msg.attach(part1)
msg.attach(part)
msg.attach(part2)
msg.attach(part3)
msg.attach(img)
server = smtplib.SMTP(HOST)
# server.login(username, password) # optional
try:
toaddr = TO
cc = [CC]
bcc = ['']
toaddrs = [toaddr] + cc + bcc
failed = server.sendmail(FROM, toaddrs, msg.as_string())
server.close()
statusemail= "Email enviado com sucesso para %s" % TO
print statusemail
return statusemail
except Exception, e:
errorMsg = "Unable to send email. Error: %s" % str(e)
return errorMsg
terça-feira, 4 de fevereiro de 2014
export html data to txt file
$(document).ready(function () {
function export_html_txt($table, filename) {
var codevaltxt = $table.html();
// Data URI
var codetxt = codevaltxt.replace(/\<br\>/g, '\r\n');
txt_data = 'data:application/text;charset=utf-8,' + encodeURIComponent(codetxt);
$(this)
.attr({
'download': filename,
'href': txt_data,
'target': '_blank'
});
}
$("#down-hosts").on('click', function (event) {
// txt
export_html_txt.apply(this, [$("#codeval"), 'mars.txt']);
});
});
function export_html_txt($table, filename) {
var codevaltxt = $table.html();
// Data URI
var codetxt = codevaltxt.replace(/\<br\>/g, '\r\n');
txt_data = 'data:application/text;charset=utf-8,' + encodeURIComponent(codetxt);
$(this)
.attr({
'download': filename,
'href': txt_data,
'target': '_blank'
});
}
$("#down-hosts").on('click', function (event) {
// txt
export_html_txt.apply(this, [$("#codeval"), 'mars.txt']);
});
});
quinta-feira, 30 de janeiro de 2014
web2py install ubuntu sh
#!/bin/bash
echo 'setup-web2py-nginx-uwsgi-ubuntu-precise.sh'
echo 'Requires Ubuntu > 12.04 and installs Nginx + uWSGI + Web2py'
# Check if user has root privileges
if [[ $EUID -ne 0 ]]; then
echo "You must run the script as root or using sudo"
exit 1
fi
# Get Web2py Admin Password
echo -e "Web2py Admin Password: \c "
read PW
# Upgrade and install needed software
apt-get update
apt-get -y upgrade
apt-get autoremove
apt-get autoclean
apt-get -y install nginx-full
apt-get -y install build-essential python-dev libxml2-dev python-pip unzip
pip install --upgrade pip
PIPPATH=`which pip`
$PIPPATH install --upgrade uwsgi
# Create configuration file /etc/nginx/sites-available/web2py
echo 'server {
listen 80;
server_name $hostname;
#to enable correct use of response.static_version
#location ~* /(\w+)/static(?:/_[\d]+\.[\d]+\.[\d]+)?/(.*)$ {
# alias /home/www-data/web2py/applications/$1/static/$2;
# expires max;
#}
location ~* /(\w+)/static/ {
root /home/www-data/web2py/applications/;
#remove next comment on production
#expires max;
}
location / {
#uwsgi_pass 127.0.0.1:9001;
uwsgi_pass unix:///tmp/web2py.socket;
include uwsgi_params;
uwsgi_param UWSGI_SCHEME $scheme;
uwsgi_param SERVER_SOFTWARE nginx/$nginx_version;
}
}
server {
listen 443 default_server ssl;
server_name $hostname;
ssl_certificate /etc/nginx/ssl/web2py.crt;
ssl_certificate_key /etc/nginx/ssl/web2py.key;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_ciphers ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA;
ssl_protocols SSLv3 TLSv1;
keepalive_timeout 70;
location / {
#uwsgi_pass 127.0.0.1:9001;
uwsgi_pass unix:///tmp/web2py.socket;
include uwsgi_params;
uwsgi_param UWSGI_SCHEME $scheme;
uwsgi_param SERVER_SOFTWARE nginx/$nginx_version;
}
}' >/etc/nginx/sites-available/web2py
ln -s /etc/nginx/sites-available/web2py /etc/nginx/sites-enabled/web2py
rm /etc/nginx/sites-enabled/default
mkdir /etc/nginx/ssl
cd /etc/nginx/ssl
openssl genrsa 1024 > web2py.key
chmod 400 web2py.key
openssl req -new -x509 -nodes -sha1 -days 1780 -key web2py.key > web2py.crt
openssl x509 -noout -fingerprint -text < web2py.crt > web2py.info
# Prepare folders for uwsgi
sudo mkdir /etc/uwsgi
sudo mkdir /var/log/uwsgi
# Create configuration file /etc/uwsgi/web2py.xml
echo '<uwsgi>
<socket>/tmp/web2py.socket</socket>
<pythonpath>/home/www-data/web2py/</pythonpath>
<mount>/=wsgihandler:application</mount>
<master/>
<processes>4</processes>
<harakiri>60</harakiri>
<reload-mercy>8</reload-mercy>
<cpu-affinity>1</cpu-affinity>
<stats>/tmp/stats.socket</stats>
<max-requests>2000</max-requests>
<limit-as>512</limit-as>
<reload-on-as>256</reload-on-as>
<reload-on-rss>192</reload-on-rss>
<uid>www-data</uid>
<gid>www-data</gid>
<cron>0 0 -1 -1 -1 python /home/www-data/web2py/web2py.py -Q -S welcome -M -R scripts/sessions2trash.py -A -o</cron>
<no-orphans/>
</uwsgi>' >/etc/uwsgi/web2py.xml
#Create a configuration file for uwsgi in emperor-mode
#for Upstart in /etc/init/uwsgi-emperor.conf
echo '# Emperor uWSGI script
description "uWSGI Emperor"
start on runlevel [2345]
stop on runlevel [06]
##
#remove the comments in the next section to enable static file compression for the welcome app
#in that case, turn on gzip_static on; on /etc/nginx/nginx.conf
##
#pre-start script
# python /home/www-data/web2py/web2py.py -S welcome -R scripts/zip_static_files.py
# chown -R www-data:www-data /home/www-data/web2py/*
#end script
respawn
exec uwsgi --master --die-on-term --emperor /etc/uwsgi --logto /var/log/uwsgi/uwsgi.log
' > /etc/init/uwsgi-emperor.conf
# Install Web2py
mkdir /home/www-data
cd /home/www-data
wget http://web2py.com/examples/static/web2py_src.zip
unzip web2py_src.zip
rm web2py_src.zip
# Download latest version of sessions2trash.py
wget http://web2py.googlecode.com/hg/scripts/sessions2trash.py -O /home/www-data/web2py/scripts/sessions2trash.py
chown -R www-data:www-data web2py
cd /home/www-data/web2py
sudo -u www-data python -c "from gluon.main import save_password; save_password('$PW',443)"
start uwsgi-emperor
/etc/init.d/nginx restart
## you can reload uwsgi with
# restart uwsgi-emperor
## and stop it with
# stop uwsgi-emperor
## to reload web2py only (without restarting uwsgi)
# touch /etc/uwsgi/web2py.xml
echo 'setup-web2py-nginx-uwsgi-ubuntu-precise.sh'
echo 'Requires Ubuntu > 12.04 and installs Nginx + uWSGI + Web2py'
# Check if user has root privileges
if [[ $EUID -ne 0 ]]; then
echo "You must run the script as root or using sudo"
exit 1
fi
# Get Web2py Admin Password
echo -e "Web2py Admin Password: \c "
read PW
# Upgrade and install needed software
apt-get update
apt-get -y upgrade
apt-get autoremove
apt-get autoclean
apt-get -y install nginx-full
apt-get -y install build-essential python-dev libxml2-dev python-pip unzip
pip install --upgrade pip
PIPPATH=`which pip`
$PIPPATH install --upgrade uwsgi
# Create configuration file /etc/nginx/sites-available/web2py
echo 'server {
listen 80;
server_name $hostname;
#to enable correct use of response.static_version
#location ~* /(\w+)/static(?:/_[\d]+\.[\d]+\.[\d]+)?/(.*)$ {
# alias /home/www-data/web2py/applications/$1/static/$2;
# expires max;
#}
location ~* /(\w+)/static/ {
root /home/www-data/web2py/applications/;
#remove next comment on production
#expires max;
}
location / {
#uwsgi_pass 127.0.0.1:9001;
uwsgi_pass unix:///tmp/web2py.socket;
include uwsgi_params;
uwsgi_param UWSGI_SCHEME $scheme;
uwsgi_param SERVER_SOFTWARE nginx/$nginx_version;
}
}
server {
listen 443 default_server ssl;
server_name $hostname;
ssl_certificate /etc/nginx/ssl/web2py.crt;
ssl_certificate_key /etc/nginx/ssl/web2py.key;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_ciphers ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA;
ssl_protocols SSLv3 TLSv1;
keepalive_timeout 70;
location / {
#uwsgi_pass 127.0.0.1:9001;
uwsgi_pass unix:///tmp/web2py.socket;
include uwsgi_params;
uwsgi_param UWSGI_SCHEME $scheme;
uwsgi_param SERVER_SOFTWARE nginx/$nginx_version;
}
}' >/etc/nginx/sites-available/web2py
ln -s /etc/nginx/sites-available/web2py /etc/nginx/sites-enabled/web2py
rm /etc/nginx/sites-enabled/default
mkdir /etc/nginx/ssl
cd /etc/nginx/ssl
openssl genrsa 1024 > web2py.key
chmod 400 web2py.key
openssl req -new -x509 -nodes -sha1 -days 1780 -key web2py.key > web2py.crt
openssl x509 -noout -fingerprint -text < web2py.crt > web2py.info
# Prepare folders for uwsgi
sudo mkdir /etc/uwsgi
sudo mkdir /var/log/uwsgi
# Create configuration file /etc/uwsgi/web2py.xml
echo '<uwsgi>
<socket>/tmp/web2py.socket</socket>
<pythonpath>/home/www-data/web2py/</pythonpath>
<mount>/=wsgihandler:application</mount>
<master/>
<processes>4</processes>
<harakiri>60</harakiri>
<reload-mercy>8</reload-mercy>
<cpu-affinity>1</cpu-affinity>
<stats>/tmp/stats.socket</stats>
<max-requests>2000</max-requests>
<limit-as>512</limit-as>
<reload-on-as>256</reload-on-as>
<reload-on-rss>192</reload-on-rss>
<uid>www-data</uid>
<gid>www-data</gid>
<cron>0 0 -1 -1 -1 python /home/www-data/web2py/web2py.py -Q -S welcome -M -R scripts/sessions2trash.py -A -o</cron>
<no-orphans/>
</uwsgi>' >/etc/uwsgi/web2py.xml
#Create a configuration file for uwsgi in emperor-mode
#for Upstart in /etc/init/uwsgi-emperor.conf
echo '# Emperor uWSGI script
description "uWSGI Emperor"
start on runlevel [2345]
stop on runlevel [06]
##
#remove the comments in the next section to enable static file compression for the welcome app
#in that case, turn on gzip_static on; on /etc/nginx/nginx.conf
##
#pre-start script
# python /home/www-data/web2py/web2py.py -S welcome -R scripts/zip_static_files.py
# chown -R www-data:www-data /home/www-data/web2py/*
#end script
respawn
exec uwsgi --master --die-on-term --emperor /etc/uwsgi --logto /var/log/uwsgi/uwsgi.log
' > /etc/init/uwsgi-emperor.conf
# Install Web2py
mkdir /home/www-data
cd /home/www-data
wget http://web2py.com/examples/static/web2py_src.zip
unzip web2py_src.zip
rm web2py_src.zip
# Download latest version of sessions2trash.py
wget http://web2py.googlecode.com/hg/scripts/sessions2trash.py -O /home/www-data/web2py/scripts/sessions2trash.py
chown -R www-data:www-data web2py
cd /home/www-data/web2py
sudo -u www-data python -c "from gluon.main import save_password; save_password('$PW',443)"
start uwsgi-emperor
/etc/init.d/nginx restart
## you can reload uwsgi with
# restart uwsgi-emperor
## and stop it with
# stop uwsgi-emperor
## to reload web2py only (without restarting uwsgi)
# touch /etc/uwsgi/web2py.xml
requests python session with change headers
s = requests.Session()
if not os.path.exists("templates"):
os.makedirs("templates")
for i in dict_accounts.keys():
os.makedirs("templates/%s" % i)
for key,val in dict_accounts.iteritems():
print key
urlfinal = "https:urlmaneira"
r = s.get(urlfinal, verify=False,stream=True,headers={'User-Agent':"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0"})
print urlfinal
print r.request.headers
print r.text
break
if not os.path.exists("templates"):
os.makedirs("templates")
for i in dict_accounts.keys():
os.makedirs("templates/%s" % i)
for key,val in dict_accounts.iteritems():
print key
urlfinal = "https:urlmaneira"
r = s.get(urlfinal, verify=False,stream=True,headers={'User-Agent':"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0"})
print urlfinal
print r.request.headers
print r.text
break
segunda-feira, 27 de janeiro de 2014
web2py - nginx fix
#!/bin/bash
echo 'setup-web2py-nginx-uwsgi-ubuntu-precise.sh'
echo 'Requires Ubuntu > 12.04 and installs Nginx + uWSGI + Web2py'
# Check if user has root privileges
if [[ $EUID -ne 0 ]]; then
echo "You must run the script as root or using sudo"
exit 1
fi
# Get Web2py Admin Password
echo -e "Web2py Admin Password: \c "
read PW
# Upgrade and install needed software
apt-get update
apt-get -y upgrade
apt-get autoremove
apt-get autoclean
apt-get -y install nginx-full
apt-get -y install build-essential python-dev libxml2-dev python-pip unzip
pip install --upgrade pip
PIPPATH=`which pip`
$PIPPATH install --upgrade uwsgi
# Create configuration file /etc/nginx/sites-available/web2py
echo 'server {
listen 80;
server_name $hostname;
#to enable correct use of response.static_version
#location ~* /(\w+)/static(?:/_[\d]+\.[\d]+\.[\d]+)?/(.*)$ {
# alias /home/www-data/web2py/applications/$1/static/$2;
# expires max;
#}
location ~* /(\w+)/static/ {
root /home/www-data/web2py/applications/;
#remove next comment on production
#expires max;
}
location / {
#uwsgi_pass 127.0.0.1:9001;
uwsgi_pass unix:///tmp/web2py.socket;
include uwsgi_params;
uwsgi_param UWSGI_SCHEME $scheme;
uwsgi_param SERVER_SOFTWARE nginx/$nginx_version;
}
}
server {
listen 443 default_server ssl;
server_name $hostname;
ssl_certificate /etc/nginx/ssl/web2py.crt;
ssl_certificate_key /etc/nginx/ssl/web2py.key;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_ciphers ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA;
ssl_protocols SSLv3 TLSv1;
keepalive_timeout 70;
location / {
#uwsgi_pass 127.0.0.1:9001;
uwsgi_pass unix:///tmp/web2py.socket;
include uwsgi_params;
uwsgi_param UWSGI_SCHEME $scheme;
uwsgi_param SERVER_SOFTWARE nginx/$nginx_version;
}
}' >/etc/nginx/sites-available/web2py
ln -s /etc/nginx/sites-available/web2py /etc/nginx/sites-enabled/web2py
rm /etc/nginx/sites-enabled/default
mkdir /etc/nginx/ssl
cd /etc/nginx/ssl
openssl genrsa 1024 > web2py.key
chmod 400 web2py.key
openssl req -new -x509 -nodes -sha1 -days 1780 -key web2py.key > web2py.crt
openssl x509 -noout -fingerprint -text < web2py.crt > web2py.info
# Prepare folders for uwsgi
sudo mkdir /etc/uwsgi
sudo mkdir /var/log/uwsgi
# Create configuration file /etc/uwsgi/web2py.xml
echo '<uwsgi>
<socket>/tmp/web2py.socket</socket>
<pythonpath>/home/www-data/web2py/</pythonpath>
<mount>/=wsgihandler:application</mount>
<master/>
<processes>4</processes>
<harakiri>60</harakiri>
<reload-mercy>8</reload-mercy>
<cpu-affinity>1</cpu-affinity>
<stats>/tmp/stats.socket</stats>
<max-requests>2000</max-requests>
<limit-as>512</limit-as>
<reload-on-as>256</reload-on-as>
<reload-on-rss>192</reload-on-rss>
<uid>www-data</uid>
<gid>www-data</gid>
<cron>0 0 -1 -1 -1 python /home/www-data/web2py/web2py.py -Q -S welcome -M -R scripts/sessions2trash.py -A -o</cron>
<no-orphans/>
</uwsgi>' >/etc/uwsgi/web2py.xml
#Create a configuration file for uwsgi in emperor-mode
#for Upstart in /etc/init/uwsgi-emperor.conf
echo '# Emperor uWSGI script
description "uWSGI Emperor"
start on runlevel [2345]
stop on runlevel [06]
##
#remove the comments in the next section to enable static file compression for the welcome app
#in that case, turn on gzip_static on; on /etc/nginx/nginx.conf
##
#pre-start script
# python /home/www-data/web2py/web2py.py -S welcome -R scripts/zip_static_files.py
# chown -R www-data:www-data /home/www-data/web2py/*
#end script
respawn
exec uwsgi --master --die-on-term --emperor /etc/uwsgi --logto /var/log/uwsgi/uwsgi.log
' > /etc/init/uwsgi-emperor.conf
# Install Web2py
mkdir /home/www-data
cd /home/www-data
wget http://web2py.com/examples/static/web2py_src.zip
unzip web2py_src.zip
rm web2py_src.zip
# Download latest version of sessions2trash.py
wget http://web2py.googlecode.com/hg/scripts/sessions2trash.py -O /home/www-data/web2py/scripts/sessions2trash.py
chown -R www-data:www-data web2py
cd /home/www-data/web2py
sudo -u www-data python -c "from gluon.main import save_password; save_password('$PW',443)"
start uwsgi-emperor
/etc/init.d/nginx restart
## you can reload uwsgi with
# restart uwsgi-emperor
## and stop it with
# stop uwsgi-emperor
## to reload web2py only (without restarting uwsgi)
# touch /etc/uwsgi/web2py.xml
xdotool and python
import subprocess,time
import datetime
def run_command(cmdstr="getactivewindow",windowpid=None,xcheck=True):
outputs=""
errors=""
try:
if xcheck:
if not windowpid:
command = 'xdotool %s' % (cmdstr)
else:
command = 'xdotool %s %s' % (cmdstr,windowpid)
else:
command=cmdstr
p = subprocess.Popen(command,
shell=True,stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
p.wait()
outputs=str(out)
errors=str(err)
if p.stdin:
p.stdin.close()
if p.stdout:
p.stdout.close()
if p.stderr:
p.stderr.close()
try:
p.kill()
except OSError:
# can't kill a dead proc
pass
return outputs,errors
except Exception, e:
print "command: %s" % cmdstr
print '*** Caught exception: %s: %s' % (e.__class__, e)
print "command done for system: %s" % accsys.split("_")[1]
lastapp=""
lastwindow=""
dict_apptime = {}
while 1:
out,err = run_command()
wid = out.replace("\n","")
out,err = run_command("getwindowname",wid)
windowname=out.replace("\n","")
if not windowname in lastwindow:
rundate=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
out,err = run_command("getwindowpid",wid)
pid= out.replace("\n","")
finalcmd = "ps aux | grep %s | awk {'print $11'} | grep -Ev 'grep|/bin/sh|/bin/bash|cat'" % pid
out,err = run_command(finalcmd,xcheck=False)
application = out.split("\n")
lastapp=application
lastwindow=windowname
#print dict_apptime
print "windowname:'%s' wid: %s\ncollected time: %s\napplication name: %s" % (windowname,wid,rundate,application)
time.sleep(2)
quinta-feira, 23 de janeiro de 2014
copy and editing an spreedsheet in python
planilha_nome = 'template.xls'
book = xlrd.open_workbook(planilha_nome,on_demand=True,formatting_info=True)
sh = book.sheet_by_index(0)
total_rows= sh.nrows
w = xlwt.Workbook()
newbook = copy(book)
sheetdetails=newbook.get_sheet(0)
style = xlwt.XFStyle()
style_book= Styles(book)
style1 = xlwt.easyxf('font: height 200, name Arial, colour_index black, bold off, italic off; align: wrap on, vert centre, horiz left;' "borders: top thin, bottom thin , left thin, right thin;" '')
style2 = xlwt.easyxf('font: height 200, name Arial, colour_index black, bold off, italic off; align: wrap on, vert centre, horiz left;' "borders: top thin, bottom thin , left thin, right thin;" 'pattern: pattern solid, fore_colour green;')
style3 = xlwt.easyxf('font: height 200, name Arial, colour_index black, bold off, italic off; align: wrap on, vert centre, horiz left;' "borders: top thin, bottom thin , left thin, right thin;" 'pattern: pattern solid, fore_colour gray40;')
sheetdetails.write(1,2,"coluna1",style1)
sheetdetails.write(2,2,host,style1)
sheetdetails.write(10,2,"coluna2",style1)
sheetdetails.write(11,2,datetime.datetime.now().strftime("%Y-%m-%d"),style1)
for i in xrange(total_rows):
rowdata = sh.row(i)
print rowdata
finaldate_xls=datetime.datetime.now().strftime("%Y%m%d")
strfile = "output/%s.xls" % (finaldate_xls)
newbook.save(strfile)
terça-feira, 14 de janeiro de 2014
web2py - sqlform.grid oncreate,delete,update
create your on sqlform.grid action triggers
# coding: utf8
import datetime
def log_update(formval):
strdate=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
action_log = "usuario %s atualizou o registro %s em %s" % (session.uid,str(formval.vars.id),strdate)
dbsec.log_security.insert(action_log=action_log,intranet=session.email,action_desc="update",action_url_from=request.env.path_info)
def log_create(formval):
strdate=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
action_log = "usuario %s criou o registro %s em %s" % (session.uid,str(formval.vars.id),strdate)
dbsec.log_security.insert(action_log=action_log,intranet=session.email,action_desc="create",action_url_from=request.env.path_info)
def log_delete(table,record_id):
strdate=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
action_log = "usuario %s deletou o registro %s da tabela %s em %s" % (session.uid,record_id,table,strdate)
dbsec.log_security.insert(action_log=action_log,intranet=session.email,action_desc="delete",action_url_from=request.env.path_info)
query_f = (db.table)
fields = [db.table.id,db.table.comments]
datasource = SQLFORM.grid(query=query_f,fields=fields,orderby=[db.table.id],
user_signature=False,create=False,details=False,editable=False,deletable=True,oncreate=log_create,onupdate=log_update,ondelete=log_delete)
quinta-feira, 9 de janeiro de 2014
How to auth on a https webpage and save session using requests
# -*- coding: utf-8 -*-
import urllib
import urllib2
import os,sys
import re,base64
import requests
import time
password_final = base64.b64decode('senha64')
user_final = base64.b64decode('user64')
s = requests.Session()
s.get('https://...', verify=False)
def auth_html(passwd,userid):
url = 'https://...'
#create form to request
submitVars = {'strUserid': userid,
'strPasswd': passwd,
}
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = s.post(url, data=submitVars, headers=headers, verify=False)
data = r.text
regex = re.compile('.*(Logged).*')
rg = regex.findall(data)
if len(rg)>0:
return True
else:
print "erro na autenticacao"
return False
def load_html(opt_platform='1'):
#url
url = 'https://...'
#create form to request
submitVars = {
"search_id":opt_platform,
}
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = s.post(url, data=submitVars, headers=headers, verify=False)
data = r.text
#print(data)
regex = re.compile('<tr class="(white|gray)"\s*>\s+<td.*>\s+([a-zA-Z0-9_\.\- ]+)\s*</td>\s+<td.*>\s+([a-zA-Z0-9_\.\- ]+)\s*</td>\s+<td.*>\s+([a-zA-Z0-9_\.\- ]+)\s*</td>\s+<td.*>\s+([a-zA-Z0-9_\.\- ]+)\s*</td>',
re.MULTILINE)
r = regex.findall(data)
return r
dict_OS={"DOTA":["1","445","9","401","426","503",],
"DOTA2":["2","5","7","402","431",],
"HON":["3","6","8","434",],}
isauth = auth_html(password_final,user_final)
if isauth:
dota2=[]
hon=[]
dota=[]
for i in dict_OS["DOTA"]:
resp= load_html(i)
dota.extend(resp)
for i in dict_OS["HON"]:
resp= load_html(i)
hon.extend(resp)
for i in dict_OS["DOTA2"]:
resp= load_html(i)
dota2.extend(resp)
Assinar:
Postagens (Atom)