Setup development environment on OSX
Setup development environment on OSX
Install Homebrew on your laptop
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Install some packages you like
cat > Caskfile
Initialize virtual machine
boot2docker init
boot2docker start
A demonstration for build rpm in container
cat > Dockerfile
RUN yum clean all
RUN yum -y update && yum install -y \
ruby-devel.x86_64 \
ruby.x86_64 \
rubygems.noarch \
gcc.x86_64 \
rpm-build.x86_64
RUN gem install fpm --no-rdoc --no-ri
VOLUME /data
WORKDIR /data
CMD ["/bin/bash"]
EOF
$(boot2docker shellinit)
docker build -t mlf4aiur/fpm_rpm .
Put your package into data/ directory and run following command, then you’ll get the rpm file in you data directory.
docker run -it --rm -v pwd
/data:/data mlf4aiur/fpm_rpm fpm \
--verbose \
-f \
-s dir \
-t rpm \
--name hello_world \
-v 0.9.0 \
--config-files opt/hello_world/ \
--exclude "*/*.pyc" \
--depends python \
opt/hello_world
Introduction to Ansible
Introduction to Ansible
Installation
I don’t want input password every time when I run ansible
, so prepare ssh key authentication agent for auto login.
# Generate ssh public private key pair
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa
ssh-agent | head -2 > ~/.ssh/.agent.env
source ~/.ssh/.agent.env
ssh-add ~/.ssh/id_rsa
Install Ansible on a isolation environment.
mkdir ~/Ansible
cd ~/Ansible # or press Escape + .
sudo easy_install pip
pip install virtualenv
virtualenv .venv
source .venv/bin/activate
pip install ansible
Setup autoenv
for load ansible
environment automatically.
git clone git://github.com/kennethreitz/autoenv.git ~/.autoenv
echo "source ~/.autoenv/activate.sh" >> ~/.bash_profile
source ~/.autoenv/activate.sh
cat > ~/Ansible/.active_ansible <<\EOF
source ~/Ansible/.venv/bin/activate # Activeate virtualenv
source ~/.ssh/.agent.env # Load ssh-agent env
# or use private key file
# export ANSIBLE_PRIVATE_KEY_FILE=~/.ssh/id_rsa
export ANSIBLE_HOSTS=~/Ansible/inventory
export ANSIBLE_HOST_KEY_CHECKING=False # Set ansible config
export ANSIBLE_FORKS=20 # Specify ansible parallel processes
EOF
echo "source ~/Ansible/.active_ansible" > .env
Usage examples
Inventory file
cat ~/Ansible/inventory
[web]
web1.example.com
web2.example.com
[db]
db1.example.com
db2.example.com
Run some ad-hoc commands
ansible web -m shell -a "uptime"
File Transfer
ansible web -m copy -a "src=foo dest=/tmp/foo"
Gathering Facts
ansible web -m setup
Playbook
Distribute the public_key to remote hosts with playbook
cat > playbook.yaml <
Write a customize playbook
Here is a Ansbile playbook example.
Playbook directory structure.
$ tree
|-roles
|---example # Role name
|-----files # Statistic files
|-----tasks # Put tasks here
|-----templates # Template files
|-----vars # Variabals
# roles/example/vars/main.yml
---
authorized_keys: id_rsa.pub
ssh_dir: /home/mlf4aiur/.ssh
owner: mlf4aiur
group: mlf4aiur
# roles/example/files/id_rsa.pub
# roles/example/tasks/main.yml
---
- name: set attributes of .ssh
action: file path={{ ssh_dir }} owner={{ owner }} group={{ group }} mode=0700 state=directory
- name: put public key in ~/.ssh/
action: copy src={{ authorized_keys }} dest={{ ssh_dir }}/authorized_keys owner={{ owner }} group={{ group }} mode=0600
Apply this playbook to distribute public_key.
# distribute_public_key.yml
---
- hosts: all
gather_facts: False
roles:
- example
ansible-playbook distribute_public_key.yml
Related links:
Getting Started with Vagrant
Getting Started with Vagrant
Installation
Install VirtualBox or VMware first, and download the latest from Vagrant download page.
Launch a instance
cd ~/.vagrant.d/tmp/
wget http://developer.nrel.gov/downloads/vagrant-boxes/CentOS-6.4-x86_64-v20130731.box
vagrant box add CentOS-6.4-x86_64 CentOS-6.4-x86_64-v20130731.box
mkdir -p ~/.vagrant.d/init/myvm
cd ~/.vagrant.d/init/myvm
vagrant init CentOS-6.4-x86_64
vagrant up
vagrant ssh
Provisioning
# install rvm
\curl -sSL https://get.rvm.io | bash -s stable
source "$HOME/.rvm/scripts/rvm
gem install chef
mkdir -p ~/.vagrant.d/init/my-recipes/cookbooks
cd ~/.vagrant.d/init/my-recipes/cookbooks
for cookbook in yum mysql apache2
do
knife cookbook site download $cookbook
done
# untar the cookbook tar file
Vagrantfile
config.vm.provision :chef_solo do |chef|
chef.cookbooks_path = "../my-recipes/cookbooks"
chef.add_recipe "yum"
chef.add_recipe "yum::epel"
chef.add_recipe "mysql"
chef.add_recipe "apache2"
# You may also specify custom JSON attributes:
chef.json.merge!({
:mysql => {
"server_root_password" => "yourmysqlpassword",
"server_repl_password" => "yourmysqlpassword",
"server_debian_password" => "yourmysqlpassword"
},
:apache2 => {
"listen_address" => "0.0.0.0"
}
})
end
config.vm.provision :shell, :path => "provision.sh"
provision.sh
#!/usr/bin/env bash
sudo iptables -I INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -I INPUT -p tcp --dport 8080 -j ACCEPT
sudo yum -y update
Run a specific provisioner
vagrant provision --provision-with chef_solo
Run chef-solo
on VM
sudo chef-solo -c /tmp/vagrant-chef-1/solo.rb -j /vagrant/chef_solo.json
/vagrant/chef_solo.json
{
"mysql": {
"server_root_password": "yourmysqlpassword",
"server_repl_password": "yourmysqlpassword",
"server_debian_password": "yourmysqlpassword"
},
"apache2": {
"listen_address": "0.0.0.0"
},
"run_list": [
"recipe[yum]",
"recipe[yum::epel]",
"recipe[mysql]",
"recipe[apache2]"
]
}
Packaging
Creating the Vagrantfile
Name the file Vagrantfile.pkg
Vagrant::Config.run do |config|
# Forward apache
config.vm.forward_port 80, 8080
end
Packaging the Project
$ vagrant package --vagrantfile Vagrantfile.pkg
Distributing the Box
$ vagrant box add my_box /path/to/the/package.box
$ vagrant init my_box
$ vagrant up
Troubleshooting
Enable debug:
VAGRANT_LOG=info vagrant up
set VAGRANT_LOG=info
vagrant up
VAGRANT_LOG=debug vagrant provision
Insecure world writable dir /Applications in PATH, mode 040777
Vagrant::Errors::VMBootBadState: The guest machine entered an invalid state while waiting for it
to boot. Valid states are 'starting, running'. The machine is in the
'poweroff' state. Please verify everything is configured
properly and try again.
If the provider you're using has a GUI that comes with it,
it is often helpful to open that and watch the machine, since the
GUI often has more helpful error messages than Vagrant can retrieve.
For example, if you're using VirtualBox, run vagrant up
while the
VirtualBox GUI is open.
Run this to fix it:
sudo chmod 755 /Applications/
Mount error on v-root: /vagrant
When you start up your guest, you may get the following message unexpectedly:
[default] -- v-root: /vagrant
The following SSH command responded with a non-zero exit status.
Vagrant assumes that this means the command failed!
mount -t vboxsf -o uid=id -u vagrant
,gid=id -g vagrant
v-root /vagrant
This is usually a result of the guest’s package manager upgrading the kernel
without rebuilding the VirtualBox Guest Additions.
To double-check that this is the issue,
connect to the guest and issue the following command:
lsmod | grep vboxsf
If that command does not return any output, it means that the VirtualBox
Guest Additions are not loaded. If the VirtualBox Guest Additions were
previously installed on the machine, you will more than likely be able to
rebuild them for the new kernel through the vboxadd initscript
, like so:
sudo /etc/init.d/vboxadd setup
Upgrade VirtualBox Guest Additions https://gist.github.com/fernandoaleman/5083680
[default] The guest additions on this VM do not match the installed version of
VirtualBox! In most cases this is fine, but in rare cases it can
cause things such as shared folders to not work properly. If you see
shared folder errors, please update the guest additions within the
virtual machine and reload your VM.
Guest Additions Version: 4.2.8
VirtualBox Version: 4.3
Solution:
Attach VBoxGuestAdditions.iso(can be found /Applications/VirtualBox.app/Contents/MacOS/VBoxGuestAdditions.iso) in VirtualBox manually.
For Ubuntu should run next commands:
sudo apt-get update -q
sudo apt-get install -q -y dkms
# Install linux-headers
sudo apt-get install -q -y linux-headers-3.2.0-23-generic
sudo mount -o loop,ro /dev/sr0 /mnt
For CentOS just need to run next command:
sudo mount -t iso9660 -o loop,ro /dev/cdrom /mnt/
Upgrade VirtualBox Guest Additions:
sudo sh /mnt/VBoxLinuxAdditions.run --nox11
exit
vagrant reload
Fix Vagrant Box Hanging at Boot(grub menu)
Use VirtualBox to boot this VM, and run command: sudo update-grub
Related links:
Daemon Skeleton introduction
Daemon Skeleton introduction
Past couple of days, i’ve builded some daemon tools, tired to do the same thing again and again, i think i need a template, to create python project with daemon easy and fast. So created this template Daemon Skeleton.
In this template i used python-daemon as the daemonizer, and did some tweak, add SIGQUIT signal catching in this module, and reformat the source code according to PEP8.
Daemon Skeleton Quick start
Clone the git repository, remove folder .git, create isolated Python environment with virturalenv, install dependencies:
git clone https://github.com/mlf4aiur/daemon-skeleton.git
rm -rf .git
sudo pip install virtuall
virtualenv .venv
. .venv/bin/activate
pip install -r requirements.txt
Then, done. You can continue your daemon project now.
Another things for build good Python project
Automation
- Create your own requirements.txt, when you need
pip freeze | awk -F = '{print $1}' > requirements.txt
- Upgrade the packages to latest version
pip install -U -r requirements.txt
- create a new source distribution as tarball
python setup.py sdist --formats=gztar
# Fabric
fab pack
- Deploying your code automatically
fab pack deploy
- Testing code
# nose
nosetests
# Fabric
fab test
# setuptools
python setup.py test
Good Documentation
pip install Sphinx
sphinx-quickstart
# Build docs
python setup.py build_sphinx
Related links
Ship access log to ElasticSearch
Ship access log to ElasticSearch
This article introduce how to use a custom python script to parse Apache access log and shipping it to ElasticSearch.
If you wan’t store the huge log to ElasticSearch, you should read Using Elasticsearch for logs, Using some popular OpenSource software, like Graylog2, Logstash, Apache Flume.
System basic setup
# Raise the nofiles limit on Linux
if ! grep "\* *soft *nofile *65535" /etc/security/limits.conf; then
cat >> /etc/security/limits.conf > /etc/profile
echo "export PATH=$JAVA_HOME/bin:$PATH" >> /etc/profile
. /etc/profile
Installation and Configuration ElasticSearch
Deploying ElasticSearch on a Cluster(EC2)
cd /opt/
wget -O elasticsearch-0.19.8.tar.gz https://github.com/downloads/elasticsearch/elasticsearch/elasticsearch-0.19.8.tar.gz
tar zxf elasticsearch-0.19.8.tar.gz
mkdir -p /var/log/elasticsearch /var/data/elasticsearch
cd /opt/elasticsearch-0.19.8/
cat >> config/elasticsearch.yml elasticsearch.sh
. /opt/elasticsearch-0.19.8/bin/elasticsearch.sh
# Install plugin elasticsearch-head
/opt/elasticsearch-0.19.8/bin/plugin -install mobz/elasticsearch-head
# Start ElasticSearch
/opt/elasticsearch-0.19.8/bin/elasticsearch
Cluster status
curl -XGET 'http://*.*.*.*:9200/_cluster/health?pretty=true'; echo
curl -XGET 'http://*.*.*.*:9200/_cluster/state?pretty=true'; echo
curl -XGET 'http://*.*.*.*:9200/_cluster/nodes?pretty=true'; echo
curl -XGET 'http://*.*.*.*:9200/_cluster/nodes/stats?pretty=true'; echo
Schema Mapping
curl -XPUT http://localhost:9200/_template/template_access/ -d '{
"template": "access-*",
"settings": { "number_of_replicas": 1, "number_of_shards": 5 },
"mappings": {
"access": {
"_all": { "enabled": false },
"_source": { "compress": true },
"properties": {
"bytes": { "index": "not_analyzed", "store": "yes", "type": "integer" },
"host": { "index": "analyzed", "store": "yes", "type": "ip" },
"method": { "index": "not_analyzed", "store": "yes", "type": "string" },
"protocol": { "index": "not_analyzed", "store": "yes", "type": "string" },
"referrer": { "index": "not_analyzed", "store": "yes", "type": "string" },
"status": { "index": "analyzed", "store": "yes", "type": "string" },
"timestamp": { "index": "analyzed", "store": "yes", "type": "date" },
"uri": { "index": "not_analyzed", "store": "yes", "type": "string" },
"user-agent": { "index": "not_analyzed", "store": "yes", "type": "string" }
}
}
}
}'
Ship log script
I have put this code on the github source code.
Usage:
cat /var/log/httpd/access_log | python ship_log_into_elasticsearch.py
or
logtail /var/log/httpd/access_log | python ship_log_into_elasticsearch.py
config file:
cat conf/main.cfg
[elasticsearch]
host = localhost:9200
bulk_size = 5000
doc_type = access
code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
abspath = os.path.abspath(os.path.dirname(__file__))
os.chdir(abspath)
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import pyes
import ConfigParser
import time
import datetime
import re
import inspect
import logging
import logging.config
import traceback
# init logging facility
logconf = "conf/logging.cfg"
logging.config.fileConfig(logconf)
# 66.249.73.69 - - [08/Aug/2012:12:10:10 +0400] "GET / HTTP/1.1" 200 23920 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
access_log_pattern = re.compile(
r"(?P[\d\.]+)\s"
r"(?P\S*)\s"
r"(?P\S*)\s"
r"(?P
Related links:
- elasticsearch, ElasticSearch is an Open Source (Apache 2), Distributed, RESTful, Search Engine built on top of Apache Lucene.
- elasticsearch-head, elasticsearch-head is a web front end for browsing and interacting with an Elastic Search cluster.
- pyes, pyes is a connector to use elasticsearch from python.
OpenShift Command Line Interface
OpenShift Command Line Interface
-
Working With Domains
-
Creating a Domain
rhc domain create -n DomainName -l rhlogin -p password [OptionalParameters]
-
Deleting a Domain
rhc domain show -l rhlogin rhc app destroy -a
-l rhlogin rhc domain destroy -n -l rhlogin
-
-
Viewing User Information
rhc domain show -l rhloging
-
Creating Applications
Supported app types:
- nodejs-0.6
- jbossas-7
- python-2.6
- jenkins-1.4
- ruby-1.8
- diy-0.1
- php-5.3
-
perl-5.10
rhc app create -a appName -t appType
Using Arbitrary DNS Names
rhc app add-alias -a racer --alias "racer.indy.com" rhc app remove-alias -a racer --alias "racer.indy.com"
-
Managing Applications
rhc app
-a ApplicationName [Optional Arguments] Table Application management command argument options
Option Details start Start an application in the cloud. stop Stop an application that is currently running in the cloud. restart Restart an application in the cloud. reload Reload an application in the cloud. status Display the current status of an application in the cloud. destroy Remove an application from the cloud. -
Using Cartridges
rhc-ctl-app -L
Database Cartridges
- MySQL Database 5.1 — MySQL is a multi-user, multi-threaded SQL database server
- MongoDB NoSQL Database 2.0 — MongoDB is a scalable, high-performance, open source NoSQL database
- PostgreSQL Database 8.4 — PostgreSQL is an advanced Object-Relational database management system
Management Cartridges
- phpMyAdmin 3.4 — phpMyAdmin is a web-based MySQL administration tool
- RockMongo 1.1 — RockMongo is a web-based MongoDB administration tool
- Jenkins Client 1.4 — a client for managing Jenkins-enabled applications
- Cron 1.4 — Cron is a daemon that runs specified programs at scheduled times
- OpenShift Metrics 0.1 — OpenShift Metrics is an experimental cartridge for monitoring applications
-
Managing Applications in a Shell Environment
Viewing Application Information
$ rhc domain show Password: Application Info ================ racer Framework: php-5.3 Creation: 2011-12-07T01:07:33-05:00 UUID: 0bd9d81bfe0a4def9de47b89fe1d3543 Git URL: ssh://0bd9d81bfe0a4def9de47b89fe1d3543@racer-ecs.rhcloud.com/~/git/racer.git/ Public URL: http://racer-ecs.rhcloud.com/
Opening a Shell Environment for an Application Node
$ ssh 0bd9d81bfe0a4def9de47b89fe1d3543@racer-ecs.rhcloud.com Warning: Permanently added 'racer-ecs.rhcloud.com,174.129.154.20' (RSA) to the list of known hosts. Welcome to OpenShift shell This shell will assist you in managing openshift applications. type "help" for more info. [racer-ecs.rhcloud.com ~]\>
Deploy web.py application on OpenShift
Deploy web.py application on OpenShift
Prepare environment
Install OpenShift client command line tool
gem install rhc
Generate a new SSH key
ssh-keygen -t rsa -f ~/.ssh/rhcloud -C "your_email@youremail.com"
edit ~/.ssh/config
Host *.rhcloud.com
IdentityFile ~/.ssh/rhcloud
Create a Namespace
rhc-create-domain -n namespace -a ~/.ssh/rhcloud -l rhlogin
Create a application, and clone the git reposity
rhc-create-app -a webpy -t python-2.6 -l rhlogin
Write your application
edit setup.py
install_requires=['web.py>=0.36'],
edit wsgi/application
#!/usr/bin/python
import os
virtenv = os.environ['APPDIR'] + '/virtenv/'
os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib/python2.6/site-packages')
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
pass
import web
urls = (
'/', 'index',
'/hello/(.*)', 'hello'
)
class index:
def GET(self):
return 'Welcome to my web site!'
class hello:
def GET(self, name):
if not name:
name = 'World'
return 'Hello, ' + name + '!'
application = web.application(urls, globals()).wsgifunc()
#
# Below for testing only
#
if __name__ == '__main__':
from wsgiref.simple_server import make_server
httpd = make_server('localhost', 8080, application)
# Wait for a single request, serve it and quit.
httpd.handle_request()
# app = web.application(urls, globals())
# app.run()
Commit and push your code
git status
git add setup.py wsgi/application
git commit -m "first commit"
git push
Bind your Domain
rhc-ctl-app -a webpy -l rhlogin -c add-alias --alias yourdomain
Using browser access your web site, Enjoy!
Variable scope in subshell
Variable scope in subshell
functions
[mlf4aiur@4aiur Shell]$ cat function_return.sh
subshell () {
# pipeline will generate subshell
echo 1 2 3 | while read line
do
echo "subshell: inside 1"; var=1; return 1
done
echo "subshell: inside 0"; var=0; return 0
}
subshell
echo "subshell: outside return $? var=$var"
foo () {
for line in $(echo 1 2 3)
do
echo "foo: inside 1"; var=1; return 1
done
echo "foo: inside 0"; var=0; return 0
}
foo
echo "foo: outside return $? var=$var"
bar () {
while read line
do
echo "bar: inside 1"; var=1; return 1
# Bash Process Substitution, original shell doesn't work
done
using shell run it
[mlf4aiur@4aiur Shell]$ sh function_return.sh
subshell: inside 1
subshell: inside 0
subshell: outside return 0 var=0
foo: inside 1
foo: outside return 1 var=1
function_return.sh: line 28: syntax error near unexpected token `
using bash run it
[mlf4aiur@4aiur Shell]$ bash function_return.sh
subshell: inside 1
subshell: inside 0
subshell: outside return 0 var=0
foo: inside 1
foo: outside return 1 var=1
bar: inside 1
bar: outside return 1 var=1
[mlf4aiur@4aiur Shell]$
Mac OS X 贴士汇聚
Mac OS X tips
Find & Scan Wireless Networks from the Command Line in Mac OS X
sudo ln -s /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport /usr/sbin/airport
airport -s
Reindexing Spotlight from the Command Line
Reindexing Spotlight from the command line is done with the mdutil tool, first launch Terminal and then type:
sudo mdutil -E /
This will reindex every mounted volume on the Mac, including hard drives, disk images, external drives, etc. Specific drives can be chosen by pointing to them in /Volumes/, to only rebuild the primary Macintosh HD:
sudo mdutil -E /Volumes/Macintosh\ HD/
To reindex an external drive named “External” the command would be:
sudo mdutil -E /Volumes/External/
Use of the mdutil command will spin up mds and mdworker processes as Spotlight goes to work.
Individually Reindexing Selected Files
In rare cases, Spotlight can miss a file during index, so rather than reindex an entire drive you can also manually add an individual file to the search index with the mdimport command:
mdimport /path/to/file
The mdimport command can be used on directories as well.
Convert a DMG file to ISO
hdiutil convert /path/imagefile.dmg -format UDTO -o /path/convertedimage.iso
Convert an ISO file to DMG format
hdiutil convert /path/imagefile.iso -format UDRW -o /path/convertedimage.dmg
Set a Zip Password in Mac OS X
zip -e archivename.zip filetoprotect.txt
unzip filename.zip
How to Remove Apps from Launchpad in Mac OS X
-
Using Launchpad — Mac App Store apps only
Hold down the Option key, and once the icons start jiggling click the “X” shown in the corner of icons that you want to delete. This removes the app from Launchpad, and does not uninstall them, but this is limited to apps installed from the Mac App Store. If you want to remove an app not installed through the Mac App Store, you have to use the method below: -
Using the Terminal — removes any application
Launch the Terminal and enter the following command, replacing “APPNAME” with the name of the application you want to remove from Launchpad:
run command:
sqlite3 ~/Library/Application\ Support/Dock/*.db "DELETE from apps WHERE title='APPNAME';" && killall Dock
files system usage
sudo fs_usage -f filesys | grep -vE 'iTerm|X11|Xquartz|grep|syslogd'
Mac OS X 系统更新升级包下载后的存储位置,避免多台苹果电脑重复下载
打开 Finder,在顶部菜单栏点击 “前往”,在下拉菜单里选择 “前往文件夹…”,粘入下面这个路径,回车。
看到苹果电脑 Mac OS X 系统更新升级包了吧。
/library/updates
注意,上面这些操作的前提是:下载完系统升级包后别立刻安装,否则安装、重启后,Mac 会自动删除它们。
Stop Lion from Re-Opening Old Windows with Command+Option+Q
chflags nohidden ~/Library/
defaults write com.macromates.textmate NSQuitAlwaysKeepsWindows -bool NO
Access and Use Emoji in Mac OS X Lion
From almost any Mac OS X Lion app, select the “Edit” menu and pull down to “Special Characters”, or hit Command+Option+T
Turn web proxy on/off in Mac OS X Terminal
To turn the proxy off, use:
alias proxyon='networksetup -setwebproxystate Airport on; networksetup -setsecurewebproxystate Airport on'
alias proxyoff='networksetup -setwebproxystate Airport off; networksetup -setsecurewebproxystate Airport off'
You may need change Airport to the appropriate network service. To list the available network services, use this command:
networksetup -listallnetworkservices
Get CPU Info via Command Line in Mac OS X
system_profiler | grep Processor
sysctl -n machdep.cpu.brand_string
Change the terminal window title
name=hostname
echo -n -e "\033]0;$name\007"
title () { title=$1; echo -n -e "\033]0;$title\007" }
Convert a Text File to RTF, HTML, DOC, and more via Command Line
textutil -convert filetype filename
textutil -cat rtf file1.txt file2.txt file3.txt -output combinedFiles.rtf
Renewing a DHCP lease
sudo ipconfig set en0 DHCP
sudo ifconfig en0 down ; sudo ifconfig en0 up
easily strace all your apache processes
ps -C apache o pid= | sed 's/^/-p /' | xargs strace
ps auxw | grep sbin/apache | awk '{print"-p " $2}' | xargs strace
ps auxw|grep bin/apache | awk '{print $2":"$10}'|awk -F ':' ' {print "-p "$1}'|xargs strace
a simple interactive tool to convert Simplified Chinese (typed by pinyin) to Traditional Chinese 简繁中文转换
echo "Simplied Chinese:"; while read -r line; do echo "Traditional Chinese:"; echo $line | iconv -f utf8 -t gb2312 | iconv -f gb2312 -t big5 | iconv -f big5 -t utf8; done
Changing Hostname on Mac OS X
sudo scutil --set HostName MY_NEW_HOSTNAME
keep ssh conniction alive
/private/etc/ssh_config
ServerAliveInterval 60
ServerAliveCountMax 3
/private/etc/sshd_config
ClientAliveInterval 60
ClientAliveCountMax 3
Flush DNS cache
dscacheutil -flushcache
Get DNS Server IP Addresses from the Command Line in Mac OS X
networksetup -getdnsservers airport
Command line MP3 player in Mac OS X
afplay audiofile.mp3
Take a Screenshot with iPhone
Taking a screenshot using an iPhone, iPod touch, or iPad is really easy. All you need to do is:
Hold down the Power button and Home button simultaneously
When the screen flashes, a screenshot has taken
隐藏文件的不同方式
有如其他Unix,你可以在文件名前加上"."来使其隐藏,例如 /.vol。
这在Finder中是有效的,不过在"ls -a"时却会显示出来。
Mac OS X使用根目录的 .hidden 文件管理需要在Finder中隐藏的文件列表。
同样,HFS+(Mac OS的文件系统)文件和目录可以有一个隐藏属性,通过SetFile命令来设置,SetFile -a V <filename>
。
你也可以关闭隐藏 属性,通过SetFile -a v <filename>
。
查看SetFile的man手册了解更多,注意拥有隐藏属性的文件只是在Finder中隐藏,而ls命令仍然可以看到。
设置自动代理
设置Network Preference中AirPort中的Automatic Proxy Configuration
选择proxy.pac后restart AirPort。
命令行打开关闭网卡命令
networksetup -setairportpower en1 off
networksetup -setairportpower en1 on
Twitter for Mac RT
defaults write com.twitter.twitter-mac QuoteTweetSyntax -string 'RT @{USERNAME}: {TEXT}'
Lock the Mac OS X Desktop
- shift+ctrl+reject
- via Menu Bar
Launch “Keychain Access”, open Preferences, Select the checkbox next to “Show Status in Menu Bar” - 另外一个方法就是设置Expose属性,在Active Screen Corners中找一个顺手的位置选择Put Display to Sleep,以后鼠标移动到那个角落就可以锁定屏幕了
删除菜单栏的图标
我们精彩会发现菜单栏右上角有些图标是我们用不到的,那些可能是系统自带的,也可能是一些安装程序的默认设置,
按住command直接用鼠标把上面的图标从菜单栏拖下来即可。
How to Remove Icons from the Menu Bar in Mac OS X
holding down the Command key and dragging items out of the menu
快速使用Google搜索
只要是Cocoa程序, 你都可以选择一些文字然后按Shift+Command+L快速以Google搜索。(在Safari中试试看)
quickly access System Preferences
If you want to quickly access the Mac OS X System Preferences,
you can do so by holding down the Option key and then hitting various function keys.
Option+Brightness pulls up the Display preference pane, Option+Expose brings up the Expose preferences,
Option+Volume controls bring up the Sound preferences, and so on.
Mac OS X keyboard shortcuts
-
关机、重启、休眠
- Command+Control+Eject – 重启
- Control+Optionion+苹果键+Eject – 关机
- Optionion+苹果键+Eject – 休眠
- Control+Eject – 提示关机、重启或者休眠
-
Startup keyboard shortcuts
- Option – Display all bootable volumes (Startup Manager)
- Shift – Perform Safe Boot (start up in Safe Mode)
- C – Start from a bootable disc (DVD, CD)
- T – Start in FireWire target disk mode
- N – Start from NetBoot server
- X – Force Mac OS X startup (if non-Mac OS X startup volumes are present)
- Command-V – Start in Verbose Mode
- Command-S – Start in Single User Mode
-
截屏
- Command (⌘)-Shift-3 – 抓取全部屏幕
- Command (⌘)-Shift-4 – 抓取部分屏幕
-
Optionion+Command (⌘)+D – 隐藏DOCK
-
Optionion+Command (⌘)+Escape – 强制退出应用程序
-
shift+alt+音量调控键 – 微调音量。
-
文本编辑选中不连贯部分
快捷键:Shift-Command-拖拽
在文本编辑中,有一个非常有用的技巧,可以让你同时选中文本中多个不连接的部分
实现这个功能其实很简单,只要在选择文本的时候按住Shift-Command进行拖拽就可以了。
通过这个功能,我们可以对文本中多个不连接的部分同时进行操作,大大节省了我们的时间。
通过试验,这个功能不仅仅只在“文本编辑”应用中可以使用,在Pages,Smultron等文本编辑器中都有这个功能。
所以,下次你用在编辑文本的时候,可以试试这个小功能,看它能不能帮助你提高效率 🙂
References
Setup Workspace On Mac OS X Lion
Setup Workspace On Mac OS X Lion
Software Update
Click Apple () menu, choose Software Update
Change System Preferences
Click Apple () menu, choose System Preferences
- Trackpad
Tap to click
Scroll direction: natural - Mouse
Adjust Tracking Speed to max - Keyboard
Keyboard Shortcuts
Full Keyboard Access: In windows and dialogs, press Tab to move keybiard focus between: –> select "All controls" - Dock
Magnification
Change Size and Magnification
Automatically hide and show the Dock - Mission Control
Show Dashboard as a space
Change Show Dashboard shortcut to F4 - Language & Text
Input Sources –> Chinese – Simplified –> Pinyin – Simplified
Change Input source shortcuts to ^Space - Sound
Remove "Show volume in menu bar" - Security & Privacy
Choose "Disable restarting to Safari when screen is locked" - Sharing
Change your "Computer Name" - Time Machine
Remove "Show Time Machine status in menu bar"
Dashboard Widgets
- Dictionary
For Chinese:
Install DictUnifier, and import dictionary: stardict-langdao-ec-gb-2.4.2.tar.gz, and drag "stardict-langdao-ec-gb-2.4.2.tar.bz2" into DictUnifier.
Now setup Dictionary Preferences, change the dicionary order. - iSTAT NANO
An advanced system monitor in a tiny package. iStat nano is a stunning system monitor widget with beautifly animated menus and transitions.
Download Page - To Do
A lightweight and fast widget to manage tasks. Thanks to Mac OS X Leopard it integrates with iCal and Mail. The big advantage: to manage your tasks you don’t have to leave these applications open.
Download Page
Adjust System
- Finder
View –> Show Path Bar, Show Status Bar
Press "CMD + ," setup Finder Preferences.
General –> "New Finder windows show:" –> User’s Home Directory
Sidebar –> Add your home dir, and remove "All My Files", "Music", "Pictures", "Hard disks"…
Advanced –> unselect "Empty Trash securely", When performing a search –> Search the Current Folder - Safari
Goto YouTuBe, Click "Download Adobe Flash Player from Adobe", and install it.
View –> Show Path Bar, Show Status Bar
Press "CMD + ," setup Finder Preferences.
Tabs –> Open pages in tabs instead of windows: Always
Extensions –> Get Extensions –> Install "AdBlock", "ClickToFlash"
Advanced –> "Never use font sizes smaller than: 12" - Mail
Add new account, and add yourself rules in Mail’s Preferences. - sudoers
$ sudo visudo
# Uncomment to allow people in group wheel to run all commands
%wheel ALL=(ALL) ALL
Install Software
- App Store
- Manually
From App Store
Sign in
Using Apple ID sign in, or create new Apple ID.
Install Software
- Xcode
- Caffeine
- Skitch
- Evernote
- TextWrangler
- Opus Domini
- Window Tidy
- The Unarchiver
- MindNode
- SketchBook Express
- 1Password
Manually
- Adium
Adium is a free instant messaging application for Mac OS X that can connect to AIM, MSN, Jabber, Yahoo, and more.
WebSite - AppCleaner
AppCleaner is a small application which allows you to thoroughly uninstall unwanted apps.
WebSite - GitHub
GitHub is the best way to collaborate with others. Fork, send pull requests and manage all your public and private git repositories.
Download page - iTerm2
iTerm2 is a replacement for Terminal and the successor to iTerm. It works on Macs with Leopard, Snow Leopard, or Lion. Its focus is on performance, internationalization, and supporting innovative features that make your life better.
Download page - MPlayer OSX Extended
MPlayer OSX Extended is the future of MPlayer OSX. Leveraging the power of the MPlayer and FFmpeg open source projects, MPlayer OSX Extended aims to deliver a powerful, functional and no frills video player for OSX.
Download page - Sequel Pro
Sequel Pro is a fast, easy-to-use Mac database management application for working with MySQL databases.
Download page - FireFox
Download page - TextMate2
TextMate brings Apple’s approach to operating systems into the world of text editors. By bridging UNIX underpinnings and GUI, TextMate cherry-picks the best of both worlds to the benefit of expert scripters and novice users alike.
WebSite - Sublime Text 2
Sublime Text is a sophisticated text editor for code, html and prose. You’ll love the slick user interface and extraordinary features.
WebSite - Skype
WebSite - Chicken of the VNC
Chicken of the VNC is a VNC client for Mac OS X. A VNC client allows one to display and interact with a remote computer screen. In other words, you can use Chicken of the VNC to interact with a remote computer as though it’s right next to you.
Download page - MacPorts
The MacPorts Project is an open-source community initiative to design an easy-to-use system for compiling, installing, and upgrading either command-line, X11 or Aqua based open-source software on the Mac OS X operating system.
Download page
Command Line
vim
curl -O "ftp://ftp.vim.org/pub/vim/unix/vim-7.3.tar.bz2"
tar jxf vim-7.3.tar.bz2
cd vim73
./configure --enable-pythoninterp --enable-rubyinterp --enable-multibyte
make && sudo make install
port
sudo port selfupdate
sudo port -c install wget@ssl
sudo port -c install axel
sudo port -c install gsed
sudo port -c install nmap
pip
# Install pip
sudo easy_install-2.7 pip
# Install python libraries
# ipython - IPython: Productive Interactive Computing
sudo pip-2.7 install ipython
# Mercurial - Fast scalable distributed SCM (revision control, version control) system
sudo pip-2.7 install Mercurial
# pep8 - Python style guide checker
sudo pip-2.7 install pep8
# flake8 - code checking using pep8 and pyflakes
sudo pip-2.7 install flake8
# pyflakes - passive checker of Python programs
sudo pip-2.7 install pyflakes
# ropevim- A vim plugin for using rope python refactoring library
sudo pip-2.7 install ropevim
# paramiko - SSH2 protocol library
sudo pip-2.7 install paramiko
RVM
bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer )
# Load RVM by appending the rvm function sourcing to your .bash_profile:
echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function' >> ~/.bash_profile
.bash_profile
cat >> ~/.bash_profile <<\EOF
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
alias ls='ls -G'
alias ll='ls -lG'
alias vi='/usr/local/bin/vim'
alias grep='grep --color'
alias Github='cd ~/Documents/workspace/Github/'
alias cgiserver="ifconfig | grep --color -o "inet 1[079][^ ]*"; python -m CGIHTTPServer 8000" # cgi_directories ['/cgi-bin', '/htbin']
alias webshare='share () { port=$1; ifconfig | grep --color -o "inet 1[079][^ ]*"; python -m SimpleHTTPServer ${port:-8000} ;}; share'
title () { title=$@; echo -n -e "\033]0;${title}\007"; }
export LSCOLORS=ExGxCxDxCxEgEdAbAgAcAd
export PS1='[\u@\h \W]\$ '
export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
shopt -s histappend
PROMPT_COMMAND="history -a; "
HISTTIMEFORMAT="%F %T "
HISTSIZE=2000
export HISTTIMEFORMAT
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
EOF
Adjust your Dock
Remove your application not very often, and add your favorite applications into Dock.
Applications Tips
MacPorts
# Search software
port search vim
# Install software
port install wget@ssl
sudo port -d selfupdate
sudo port -v selfupdate
port outdate
sudo port -c -u upgrade outdated
port installed
pip
# search: Search PyPI
pip search pep8
#install: Install packages
pip install pep8
#uninstall: Uninstall packages
pip uninstall pep8
RVM
# Display a list of all "known" rubies. NOTE: RVM can install many more Rubies not listed.
rvm list known
# Install a version of Ruby (eg 1.9.3):
rvm install 1.9.3
# Use the newly installed Ruby:
rvm use 1.9.3
# Check this worked correctly:
ruby -v
which ruby
# Optionally, you can set a version of Ruby to use as the default for new shells. Note that this overrides the 'system' ruby:
rvm use 1.9.3 --default