MySQL Can't start server: Bind on TCP/IP port: Cannot assign requested address 错误解决

昨天实验室的服务器挂了,重启后发现mysql死活不能启动,用命令
sudo tail -20 /var/log/syslog
查看发现如下报错:
Aug 13 05:32:00 ubuntu /etc/init.d/mysql[7460]: 0 processes alive and '/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf ping' resulted in
Aug 13 05:32:00 ubuntu /etc/init.d/mysql[7460]: Could not open required defaults file: /etc/mysql/debian.cnf
Aug 13 05:32:00 ubuntu /etc/init.d/mysql[7460]: Fatal error in defaults handling. Program aborted
Aug 13 05:32:00 ubuntu /etc/init.d/mysql[7460]:
Aug 13 05:33:22 ubuntu mysqld_safe[7556]: started
Aug 13 05:33:22 ubuntu mysqld[7559]: 090813  5:33:22  InnoDB: Started; log sequence number 0 2355725
Aug 13 05:33:22 ubuntu mysqld[7559]: 090813  5:33:22 [ERROR] Can't start server: Bind on TCP/IP port: Cannot assign requested address
Aug 13 05:33:22 ubuntu mysqld[7559]: 090813  5:33:22 [ERROR] Do you already have another mysqld server running on port: 3306 ?
Aug 13 05:33:22 ubuntu mysqld[7559]: 090813  5:33:22 [ERROR] Aborting
Aug 13 05:33:22 ubuntu mysqld[7559]:
Aug 13 05:33:22 ubuntu mysqld[7559]: 090813  5:33:22  InnoDB: Starting shutdown...
Aug 13 05:33:23 ubuntu mysqld[7559]: 090813  5:33:23  InnoDB: Shutdown completed; log sequence number 0 2355725
Aug 13 05:33:23 ubuntu mysqld[7559]: 090813  5:33:23 [Note] /usr/sbin/mysqld: Shutdown complete
Aug 13 05:33:23 ubuntu mysqld[7559]:
Aug 13 05:33:23 ubuntu mysqld_safe[7580]: ended
Aug 13 05:33:36 ubuntu /etc/init.d/mysql[7720]: 0 processes alive and '/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf ping' resulted in
Aug 13 05:33:36 ubuntu /etc/init.d/mysql[7720]: ^G/usr/bin/mysqladmin: connect to server at 'localhost' failed
Aug 13 05:33:36 ubuntu /etc/init.d/mysql[7720]: error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Aug 13 05:33:36 ubuntu /etc/init.d/mysql[7720]: Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!
Aug 13 05:33:36 ubuntu /etc/init.d/mysql[7720]:
看样子像是端口冲突了。可是用命令
sudo netstat -antup | grep '3306'
返回为空。
没办法,上google搜。
Google到下面这篇文章,原文在http://www.zhuoda.org/xiezhi/98178.html
mysql启动错误[Bind on TCP/IP port:...]

新装完的系统安装完mysql并且设置IP重启之后,mysql就怎么也启动不了,一直提示:

greatmoo:~# mysqld &
[1] 3527
greatmoo:~# 081021 11:02:51  InnoDB: Started; log sequence number 0 43655
081021 11:02:51 [ERROR] Can't start server: Bind on TCP/IP port: Cannot assign requested address
081021 11:02:51 [ERROR] Do you already have another mysqld server running on port: 3306 ?
081021 11:02:51 [ERROR] Aborting

081021 11:02:51  InnoDB: Starting shutdown...

greatmoo:~# 081021 11:02:54  InnoDB: Shutdown completed; log sequence number 0 43655
081021 11:02:54 [Note] mysqld: Shutdown complete

提示是 端口可能被占用,于是执行:

greatmoo:~# netstat -anp | grep "3306"

返回值为空,那么是IP错误~?感觉不太可能,于是上网查错误提示,到处都说是权限错误,但是却没有真正解决掉问题的,还是硬着头皮 chown mysql.myql N个文件,结果当然还是不行…

于是又把问题锁定在了IP和port上。

准备把port改成其它的例如3307之类的试一下,查看mysql设置:

greatmoo:~# vi /etc/mysql/my.cnf
[client]
port            = 3307
# …

# …

[mysqld]
# …
port            = 3307
# …

准备保存后启动mysql来着,却无意中发现了下面的设置:

# …
bind-address            = 127.0.0.1
# …

于是把 127.0.0.1 改为 192.168.1.10 后再启动 mysql 就成功了……哎~看来学习还是系统的学习比较好啊。

同样问题也得到了解决,看来学东西还真不能一知半解

Posted in MySQL, 技术 | Tagged , | Leave a comment

Python学习笔记-4

Lesson 4: Standard Types
Introduce standard data types
Numbers
Sequences
Hashing
Operators and built-in functions

Standard Types
Python Types
Standard Types
Numbers
Strings
Lists
Tuples
Dictionaries
Set

Other Types
None
Functions and Methods
Modules
Types/Classes
Iterators

http://docs.python.org/ref/types.html

Boolean Values
Every object has an intrinsic Boolean value
Any numeric zero or empty container is False
False        bool
0        int
0L        log-(2)
0.0        float
0.0+0.0j    complex
""         str
[]        list
()        tuple
{}        dict
None        None

All other values are True

Operators
Apply to most data types
Object Value Comparison
< <= > >= == !=
Object Identity Comparison
is is not
Boolean
not and or

Built-in Fucntions
Apply to most data types
dir()        object's arrtibutes
help()        show help text
type()        object type
isinstance()    check object type(isinstance(x,int))
cmp()        compare 2 objects
str()        string rep of object

Numbers
Integers(int)
No size limit (except VM)
Decimal, hexadecimal, octal, binary
42, 0xAE, 0237/0o237, 0b1110
Long integers(long)--(2)
Merged with and replaced by integers
42L, 0xDECADEDEADBEEFBADDEAL

Floating-Point Numbers(float)
IEEE 754 double-precision
3.14, -6e2, 0.1
1.1 == 1.1000000000000001
Bits do not like repeating fractions
Use round() + string formatting
Or use decimal.Decimal type(python 2.4 or uper)

http://docs.python.org/tut/node16.html

Other Numbers
Other numeric types
Complex(complex)
Boolean(bool)

Other numeric type modules
decimal
fractions
numbers

Numeric Operators
Arithmetic Operators
+ - * / // % **
/ in 2.x is classic division(e.g., 1/2 == 0)
/ in 3.x is true division(e.g., 1/2 == 0.5)
//in 3.x (e.g., 1/2 == 0, 1.0/2.0 == 0.0)
Positive and negative sign
+ -
Bit Operators(int only)
& | ^ << >> ~

Numeric Built-ins
Factory
int()
float()
complex()
Operational
abs()
pow()
round()
divmod()
chr() # change number to char(2.x return ASCII,3.x return unicode)
unichar() # change number to unicode char(2.x)
Not "casting", nor conversion*********************

>>> data = []
>>> if data:
print 'data has elements in it'
else:
print 'data is empty'

data is empty
>>> if len(data) > 0:
print 'data has stuff in it'
else:
print 'data is empty'

data is empty
>>> dir(data)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',

'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',

'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__',

'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> isinstance(data, list)
True
>>> isinstance(data, int)
False
>>> type(data)
<type 'list'>
>>> 1+ 2
3
>>> 5% 2
1
>>> 2 ** 3
8
>>> 9 ** 0.5
3.0
>>> 1 / 2
0
>>> 1.0 / 2
0.5
>>> 1.0 / 2.0
0.5
>>> 1.0 // 2.0
0.0
>>> from __ future__ import division
>>> 1 / 2
0.5
>>> int(3.4)
3
>>> float(1)
1.0
>>> round(1.185, 2)
1.189999999999999
>>> '%.2f' % round(1.185, 2)
'1.19'
>>> str(round(1.185, 2))
'1.19'

Sequences
String(str, unicode--(2))
Bytes(bytes, bytearray)
List(list)
Tuples(tuple)

Array-like collections/containers
Heterogeneous(except strings)
Accessed by index(starts at 0)

Slicing
Access element(s) by "slicing"
Single-element slice: seq[i]
Return item i for sequence seq
Where 0 <= i < len(seq)

Negative indices also allowed, so:
-len(seq) <= i < len(seq)

Slicing Example
s = "Python"
012345
-6-5-4-3-2-1
String example above
Works for all sequence types
s[2]==t
S[0]==P
s[-2]==o
s[len(s)]==ERROR

Multi-Element Slicing
Access multiple element(s) with ":"
Syntax: seq[i:j]
From i up to but not including j
Missing indices also allowed
Means from begining or to end
s = "Python"
012345
-6-5-4-3-2-1
s[2:5]==tho
s[3:}==hon
s[:2]==Py
s[-4:-1]==tho
s[:]==Python

Sequence Operators
Membership
in not in
Concatenation
+
Repetition/Duplication
*

Sequence Built-ins
Factory
Str()
list()
tuple()
unicode()--(2)
bytes()
bytearray()
Operational
len()
max()
min()

Strings
Like an array of characters...
No char(acter) type in Python
Immutable, as are numbers
Value cannot be changed
Flexible string formatting
% operator or format() method
Triple quotes allow special chars

>>> s = 'Python'
>>> s * 2
'PythonPython'
>>> s *= 2
>>> s
'PythonPython'
>>> s[1]
'y'
>>> s[-1]
'n'
>>> s[:4]
'Pyth'
>>> s[2:6]
'thon'
>>> s[-4:-1]
'tho'
>>> s[:6] + 'is cool'
'Pythonis cool'
>>> s[:6] + ' is cool'
'Python is cool'
>>> '-' * 20
'-------------------'
>>> 'ton' in s
False
>>> 'thon' in s
True
>>> 'thon' not in s
False
>>> hi = '''hi
there!'''
>>> hi
'hi\nthere!'
>>> print hi
hi
there!

String Formatting
>>> "Name: %s, age: %d" % ('John', 35)
'Name: John, age: 35'

>>> "Name: {0}, age: {1}".format('John', 35) #---------->(2.6 or upper)
'Name: John, age: 35'

>>> d = {'user': 'wes', 'page': 42}
>>> 'http://web/%(user)s/%(page)d.html' % d
'http://web/wes/42.html'

>>> 'http://web/{user}/{page}.html'.format(**d)
'http://web/wes/42.html'

String Methods
Built-in String Method Sampler
split()        split on dilimiter to list
join()        join list with delimiter
find()        substring search
strip()        remove leading/trailing whitespace
lower()        lowercased version of stirng
replace()    search and replace(not RE)
ljust()        create left-justified string

>>> s = 'Python is cool.'
>>> s
'Python is cool'
>>> s.find('is not')
-1
>>> s.find('is ')
7
>>> s.rfind('o')
12
>>> s.center(25)
'     Python is cool.     '
>>> s.center(25).strip()
'Python is cool.'
>>> s.split()
['Python', 'is', 'cool.']
>>> '::'.join(s.split())
'Python::is::cool.'
>>> '.'.join(reverse(s.split()))
'cool..is.Python'
>>> s.title()
'Python Is Cool'
>>> s.upper()
'PYTHON IS COOL.'
>>> s.title().swqpcase()
'pYTHON iS cOOL'
>>> s.isalpha()
False
>>> s.endswith('.')
True
>>>> s.replace('.', '!')
'Python is cool!'

String Miscellany
Operators and Operational Built-in Functions
raw_input()    user input
ord()        ASCII/Unicode value
r'c:\tmp\new'    raw string
u'n\xe9'    Unicode string ---------(2)
b'n\xc3\xa9'    bytes string------------(2.6 or 3.x)

String and Bytes
Unicode default string type in 3.x
Introduce byte types for 8-bit chars
2.x        3.x        *Mutable?
str("")        bytes(b"")    no
unicode(u"")    str("")        no
N/A        bytearray    yes
*-Ability to change its value

Lists and Tuples
Ordered heterogeneous containers
Lists
Mutable, resizable
Feature many helper methods
Tuples
Immutable
Transport data to/from functions
Not truly meant for user manipulation (no methods)

List Methods
Built-in Methods
append()    add object to end
insert()    add object anywhere
remove(),pop()    delete objects
reverse()    reverse in-place
sort()        sort in-place
extend()    merge another list
*count()    number of occurrences
*index()    first index of value

>>> m = ['Core', 'Programming', 9, 2006]
>>> m
['Core', 'Programming', 9, 2006]
>>> m.append('Prentice Hall')
>>> m
['Core', 'Programming', 9, 2006, 'Prentice Hall']
>>> m.insert(1, 'Pytho')
>>> m
['core', 'Pytho', 'Programming', 9, 2006, 'Prentice Hall']
>>> m[1] = 'Python'
['core', 'Python', 'Programming', 9, 2006, 'Prentice Hall']
>>> 2006 in m
True
>>> m.pop(3)
9
>>> m
['core', 'Python', 'Programming', 2006, 'Prentice Hall']
>>> m[2:4] = ['Fundamentals', 2008]
>>> m
['core', 'Python', 'Fundamentals', 2008, 'Prentice Hall']
>>> m.remove('Core')
>>> m
['Python', 'Fundamentals', 2008, 'Prentice Hall']
>>> m.remove('C')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

List Comprehensions
Lists:
Highly-used data type
Most common operations:
Choose elements that fit criteria
Apply function to each element
List Comprehensions("listcomps")
Construct lists using logic
Basic syntax:
[expr for var in iterable]

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [i*2 for i in range(10)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> [i for i in range(10) if i % 2 == 0]
[0, 2, 4, 6, 8]
>>> [i*3 for i in range(10) if i % 2 == 0]
[0, 6, 12, 18 ,24]
>>> [i//3 for i in range(10) if i % 2 == 0]
[0, 0, 1, 2, 2]
>>> f  = open(r'c:\autoexec.bat', 'r')
>>> data = [line.strip() for line in f]
>>> f.close()
>>> data
[]

Generator Expression
List Comprehension
Not as efficient with memory
Entire list must be created
Generator Expressions
Alternative to list comprehensions
"Generate" successive values
nearly identical basic syntax:
(expr for var in iterable)

Hashing Types
Dictionaries(dict)
Mutable Sets(set)
Immutable Sets(frozenset)

Hashed collection/container objects
Accessed by iterator(or key for dicts)
Heterogeneous
Unordered by definition

Dictionaries
Python's only mapping type
Map keys to values
Mutable, resizable hash tables
Heterogeneous
Values are arbitrary Python objects
Keys are scalar(must be hashable)
Strings, numbers, etc.
No(key) collisions allowed

Common Built-in Methods
get()        get value given key
update()    merge another dict
setdefault()    return value, set if necessary
pop()        remove & return value
items()        all key-value pairs
clear()        clear dictionary
fromkeys()    make new dict with keys

Dictionary Operations
General Usage
Number of key-value pairs:
len()
Key membership:
if k in d: # or not in
Loop through all keys:
for k in d:

>>> d = {'title': 'Core Python Programming'}
>>> d['title'] = 'Core Python Programming'
>>> d['year'] = 2006
{'year': 2006, 'title': 'Core Python Programming'}
>>> 'year' in d
True
>>> 'pub' in d
False
>>> d['title']
'Core Python Programming'
>>> d['pub']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pub'
>>> d.get('pub', 'N/A')
'N/A'
>>> d.setdefault('pub', 'Prentice Hall')
'Prentice Hall'
>>> d
{'year': 2006, 'pub': 'Prentice Hall', 'title': 'Core Python Programming'}
>>> d['pub']
'Prentice Hall'
>>> for k in d:
print k.ljust( 8) , d[k]

year     2006
pub      Prentice Hall
title    Core Python Programming
>>> for k, v in d.item():
print k.ljust( 8) , v

year     2006
pub      Prentice Hall
title    Core Python Programming
>>> d.items()
[('year', '2006'), ('pub', 'Prentice Hall'), ('title', 'Core Python Programming')]
>>> d.iteritems()
<dictionary-itemiterator object at 0x011ABFA0>

Sets and Frozensets
def: a set is a finite collection of objects
Mutable(set) or immutable(frozenset)
No key-value pairs, just values
Unordered and heterogeneous
Hashed, like dictionary keys
No collisions means no duplicates
Remember Venn diagrams?

>>> a = [1, 4, 6, 3]
>>> b = (9, 5, 2, 7, 5, 3)
>>> a, b
([1, 4, 6, 3],(9, 5, 2, 7, 5, 3))
>>> c = set(a)
>>> d = set(b)
>>> c
set([1, 3, 4, 6])
>>> d
set([9, 2, 3, 5, 7])
>>> c = {1, 3, 4, 6} # python 3.x set(())
>>> c.intersection(d)
set([3])
>>> c & d
set([3])
>>> c | d
set([1, 2, 3, 4, 5, 6, 7, 9])
>>> c |= d
>>> c
set([1, 2, 3, 4, 5, 6, 7, 9])
>>> c.add( 8)
>>> c
set[(1, 2, 3, 4, 5, 6, 7, 8, 9)]
>>> c - d
set([8, 1, 4, 6])

Posted in 未分类 | Leave a comment

Python学习笔记-3

Lesson 3: Syntax Basics

Introduce general syntax rules

Variable/identifier guidelines, gotchas

Introduce functions and modules

Obtaining command-line user input

General Rules

Use "#" to start a comment

One statement per line

Unless semicolon( ;) used (not recommended)

Code blocks delimited by indentation

Use "\" to break up long lines

Not (generally) required for comma-separated data

Block Delimitation

# foo() displays & logs its argument

def foo(x):

print "argument is", x

f = open('log.txt', 'w')

if isinstance(x, str):

f.write('%s\n' % x)

else:

f.write('%s\n' % str(x))

f.close()

Statements

Simple statements fit on one line

There is no code block following

Compound statements have code block

First line called a header

Indented sub-block of code called a suite

Header plus ':' followed by indented suite

Indentation allows any whitespace

Use spaces not TABs

Use same # of spaces for each line

Syntax Elements

# process weather check on multiple cities

checked = 0 # number of cities checked

cities = ('Huntington Beach', 'Santa Cruz',

'Haleiwa', 'Malibu', 'San Diego', 'Manteo')

for city in cities:

condition, wind, temp = get_weather(city)

print "Temp:", temp; checked += 1

if condition == WINDY and wind > 10 \

and temp > 72:

send_surfing_alert(city)

Variables

Variables and Assignment

Dynamic Typing... variables not declared

Type inferred on assignment

var = expression

Flexible assignment syntax

var1 = var2 = expression

var1, var2 = exp1, exp2

Assignment

Assignment operators

Primary assignment operator: =

Augmented assignment

+=, *=,...

No increment/decrement

++, -- are not permitted

Identifier Rules

Similar to other languages

First character must be alphabetic

Anay ohter can be alphanumeric

Treat underscores(_) as alphabetic

Case-sensitive: "None" is not "none"

Sytle

Variable naming guidelines

Similar to other language

Names loger than 1 character

Normal data in lowercase

Class names should be Titlecased

Constants should be in Catitalized

Python Gotchas

Special names begin/end with underscores

Avoid using until you know what ...

They are used for

You are doing

Do not use built-in function/data names

Reserved words, or keywords, can't be used

Python keywords

In practice... use about 60-75%

and  as*                    assert       break

class        continue  def   del

elif    else           except      exec*

finally        for             from          global

if       import               in      is

lambda     nonlocal* not   or

pass print*                 raise         return

try    while                  with*        yield

*-Keywords as, with new in 2.6; nonlocal new in 3.0;exec,print

become functions in 3.0. Constants: None(2.4), True, False(3.0)

"Built-In"s

A Built_In is a special predefined (pre-built) Python interpreter identifier

Built-ins are either data arributes or functions - usually the latter

Can be overridden (not keywords)

Comman Built-Ins

some useful built-in functions:

Informational:

dir(), help(), type()

Operational:

int(), str(), rang(), raw_input()[2.x] or input()[3.x]

Fuction Syntax

Introducing Functions

Declared using def keyword:

def func_name([arg1[,arg2[, ...arg[N]..]):

func_body

def add2tome(number):

return number + 2

Functions

Declarations:

Header line and at least one for body

Can have any number of arguments

If no value explicityly returned...

Python returns None

None: Python's NULL or void

None: constant Bollean False

Importing & Modules

What is Importing?

Allows use of outside code

What are Modules?

self-contained Python code

Bring in new functionality/objects

Import only features that you need

Import Syntax

Two different ways to access module attributes

Use module elements with name

>>> import os

>>> os.getcwd()

'/tmp'

Can import individual elements into "namespace"

>>> from os import getcwd

>>> getcwd()

'/tmp'

Keyboard Input

How to get keyboard input from user

Use Python's raw_input() function

Renamed to input() in Python 3.x

Syntax:

var = raw_input(prompt)

Example:

>>> name = raw_input('Enter name: ')

Enter name: Guido van Rossum

>>> name

'Guido van Rossum'

Summary

Syntax Basics

Variables, Assignment, Identifiers

Keywords and Built-ins

Functions and Modules

Next Lesson: Data Types

Posted in 未分类 | Leave a comment

Python学习笔记-2

Lesson 2: Getting Started
What is Python?
Background and philosophy
Language features and versions
Demonstrate language data types, syntax, and constructs

Background
What is Python?
Object-oriented programming language
can write scripts, applicaations, APIs

History
Invented in Holland(1989-1991)
C: too much, ABC: not enough
Named after British comedy troupe

Marketing/Executive Summary
Robust
Simple
Modular
Flexible
Intuitive

"Batteries Included"
Standard library provides core functionality
Obtain 3rd-part tools only as necessary

Execution Style
Interpreted but byte-compiled

Implementation(s)
Standard interpreter written in C(aka:CPython)
Alternatives in Java(aka:Jthon),.NET(aka:ironPython),etc

Technical Features
Rapid development
Multi-platform/OS
Exception handing
Memory management
Extensible
Multiple programming paradims
Excellent feature-rich library

Python 2.x vs. 3.x
Python 2.x vs. Python 3.x
This course version-independent
All about language itself
Not focused on syntax differences
Cannot ignore 3.x incompatible
Backwords-compatibility always top priority except this one time

Python 3.x
Fix early design flaws
Provide more universal data types
Clean up language and libarary

Plan
Timeline: 2.x will live on for some time
2.x and 3.x developed in parallel
Migration tools (i.e., 2to3, Python 2.6+)

2.x & 3.x Differences
Key 2.x and 3.x Differences:
print changed to function
Strings: Unicode; byte literals
One integer type; integer literals
Iteration upgrades
True division: 1/2 == 0.5 (1//2 == 0)
Look for (2) (only in 2.x)

Demo
Quick Demonstration
Starting up interactive interpreter

"Hello World" reprise
>>> print 'Hello World!'
Hello World!

Simple Arithmetic
>>> 4 + 5 * 6
34
>>> 5 % 2
1
>>> 2 ** 3
8

String, Lists, Dictionaries
>>> s = 'Python'
>>> t = 'is cool'
>>> s + ' ' + t
'Python is cool'
>>> s * 2
'PythonPython'
>>> '-' * 25
'-------------------------'
>>> s[0]
'p'
>>> s[1]
'y'
>>> s[-1]
'n'
>>> s[3:6]
'hon'
>>> data = [42, 'foo', 3.14]
>>> data.append('bar')
[42, 'foo', 3.1400000000000001, 'bar']
>>> str(data[2])
'3.14'
>>> d = {'title': 'Python fundamentals'}
>>> d['year'] = 2009
>>> d
{'year': 2009, 'title': 'Python fundamentals'}
>>> d['title'] = d['title'].title()
>>> d
{'year': 2009, 'title': 'Python Fundamentals'}

Loops and Conditionals
>>> for item in data:
print item

42
foo
3.14
bar
>>> for k in d:
print 'key:', k, 'Value:', d[k]

Key: year Value: 2009
Key: title Value: Python Fundamentals
>>> i = 0
>>> while i < 5:
print i
i += 1

0
1
2
3
4
>>> print i
5
>>> if i == 5:
print 'i is equal to five'

i is equal to five

File I/O
>>> f = open(r'c:\windows\temp\test.txt', 'w')
>>> f.write('line 1\n')
>>> f.write('last line\n')
>>> f.close()
>>> f.open(r'c:\windows\temp\test.txt', 'r')
>>> for line in f:
print line,  # print(line, end=' ')

line 1
last line

>>> f.close()

Functions
>>> def foo(x):
print 'called foo() with argument', x

>>> foo(123)
called foo() with argument 123
>>> foo('bar')
called foo() with argument bar

Classes
>>> class C(object):
def bar(self):
print 'bar() method called'

>>> c = C()
>>> c.bar()
bar() method called

Summary
For learning but has system capabilities
"Batteries Included", Plug-N_Play
Course focuses on core language
Demo/quick tour of language

Next Lesson: Syntax Basics

Posted in 未分类 | Leave a comment

Python学习笔记-1

Lession 1: Introduction

  • Administrivia
  • Installation
  • Development
  • "Hello World!" Example

Python Fundamentals

  • Comprehesive introduction to Python
  • Complements Core Python Programming

Target Audiecde

  • One high-level programming language
  • Download and install software
  • Use text editor or IDE
  • Run Programs on command-line or IDE

Goal: Python skills via self-paced instruction

Installation

Do you need to install Python? Mabe not!

  • Already available on Macs
  • Same goes for any Unix like Linux
  • Open terminal and type python
  • For Win32, check if there is C:\Python2x

If necessary, get stable release at:

  • http://python.org
  • http://corepython.com

For Windows, get .msi installer

  • Double-click to start install
  • "Extensions for Windows" not required

For Mac/Unix-based systems...

  • Use package installation tool
  • Otherwise obtain source, then
  • ./configure; make; make install

Source Code
source files with .py file extension

Editing source code

  • Text editor
  • IDe editor

Execution

  • command-line
  • IDE framework
  • Interactive Interpreter

IDEs

  • Integrated Development Environments (IDEs)
  • Provides source code editing
  • Execution framework
  • Tools such as debuggers, analyzers, etc.

Various IDEs available to download
Open source

  • IDLE, PythonWin, SPE, PyDev/Eclipse, etc.

Commercial

  • WingIDE, Komodo, etc.

Optional

Interactive Mode
Interactive Interpreter

  • Experiment, "hack", test, etc.
  • Comes with Python

Available via cmd-line or IDE

  • Also consider IPython

http://ipython.scipy.org

Running Interactive Interpreter from an IDE

Starting from cmd-line terminal or shell

Hello World!
"Hello world" example

Can use print...

  • print 'Hello World!' # (2.x)
  • print ('Hello World!') # (3.x)

Or output to stdout:

  • import sys
  • sys.stdout.write('Hello World!\n')

Interactive vs. Script

  • Interactive Mode
  • Start up your interpreter
  • Try "Hello World!"
  • Exit

Script Mode

  • Enable your OS to find Python
  • Edit hello.py
  • Execute script

Summary

  • Goal: provide a solid intro to Python
  • Check to see if download required
  • Installation and Starting Python
  • "Hello World" Example
  • Next Lession: Getting Started
Posted in Python | Tagged | Leave a comment

Ubuntu上用vsftpd架设ftp服务器

基本配置:

/etc/vsftpd.conf

listen=YES
write_enable=YES

anonymous_enable=NO
anon_upload_enable=NO
anon_mkdir_write_enable=NO
anon_other_write_enable=NO
anon_umask=022

local_enable=YES
local_umask=022

dirmessage_enable=YES
ftpd_banner=Welcome to ltlab FTP service.

connect_from_port_20=YES

chown_uploads=YES
chown_username=ltlab

xferlog_enable=YES
xferlog_file=/var/log/vsftpd.log
xferlog_std_format=YES

chroot_local_user=YES
idle_session_timeout=600

guest_enable=YES
guest_username=virtual
user_config_dir=/etc/vsftpd_user_conf
pam_service_name=vsftpd.vu
secure_chroot_dir=/var/run/vsftpd

创建一个loguser.txt文件
格式如下:
user_id
password

我们/home/loguser.txt文件内容为:
user
letmein

生成数据库
如果没有安装过libdb4.6-util,先使用以下命令进行安装
sudo apt-get install db4.6-util
然后执行
sudo db4.6_load -T -t hash -f /home/loguser.txt /etc/vsftpd_login.db
最后修改一下数据库文件的访问权限
sudo chmod 600 /etc/vsftpd_login.db

配置PAM文件
新建/etc/pam.d/vsftpd.vu内容如下
auth required /lib/security/pam_userdb.so db=/etc/vsftpd_login
account required /lib/security/pam_userdb.so db=/ect/vsftpd_login
上一步建立的数据库vsftpd_login在此处被使用
建立的虚拟用户将采用PAM进行验证,这就是通过/etc/vsftpd.conf文件中的语句pam_service_name=vsftpd.vu来启动的,稍后将会看到

为虚拟用户创建本地系统用户
新建一个系统用户virtual,用户家目录为/home/ftp,用户登录终端设为/bin/false(即使之不能登录系统)
sudo useradd virtual -d /home/ftp -s /bin/false
sudo chown virtual:virtual /home/ftp

/etc/vsftpd.conf
一般需要包含有以下一些设置:
isten=YES
anonymous_enable=NO
dirmessage_enable=YES
xferlog_enable=YES
xferlog_file=/var/log/vsftpd.log
xferlog_std_format=YES
chroot_local_user=YES
guest_enable=YES
guest_username=virtual
user_config_dir=/etc/vsftpd_user_conf
pam_service_name=vsftpd.vu
local_enable=YES
secure_chroot_dir=/var/run/vsftpd
现在usser该帐号已经可以使用了,其根目录为/home/ftp。

/etc/vsftpd_user_conf
user_config_dir=/etc/vsftpd_user_conf

现在,我们要把各个用户的配置文件放到目录/etc/vsftpd_user_conf中
sudo mkdir /etc/vsftpd_user_conf
cd /etc/vsftpd_user_conf
sudo touch user

user文件中的内容如下
write_enable=YES
anon_world_readable_only=NO
anon_upload_enable=YES
anon_mkdir_write_enable=YES
anon_other_write_enable=YES
local_root=/home/ftp/dbzh1

重启vsftpd我们就可以看到效果了^_^
/etc/init.d/vsftpd start|restart

Posted in 未分类 | Tagged | Leave a comment

用Synergy共享鼠标键盘——让偶也双屏一把

今天Google一个好东东,让偶也用上双屏了,不敢独享,发出来跟大家分享~

先说一下情况吧,在实验室有一台Dell台式机装的是Ubuntu,然后本人自己有一台笔记本装的Vista。因为在实验室里有时候两个系统要交替使用,由于本人还是喜欢外置的全尺寸键盘打字,所以每次都要来回拔插键盘和鼠标,甚是麻烦。

今天突然发现一个软件名字叫synergy,这是一个sourceforge上的开源项目,可以运行在Windows,Linux和Mac下。可以使多台机子共享一副键盘和鼠标。直接可以把鼠标从台式机的Ubuntu上拖到笔记本的Vista上来,而且还可以在两个机子之间直接共享剪切板,实在是太方便了。

现在把我这边的配置发上来给大家做一个参考。
我用实验室的台式机做Server(这里的Server是指鼠标和键盘所连接的那台机子),本人的笔记本做Client。
首先在Server上安装Synergy,可以从下面的链接的页面中下载:

http://sourceforge.net/project/showfiles.php?group_id=59275&package_id=58013

我的Server是Ubuntu,所以也可以直接用sudo apt-get install synergy安装就可以了。
可能源里面的不是最新的,需要最新的请到上面的链接中下载rpm包安装。
安装完以后,如果你想方便操作,可以直接用sudo apt-get install quicksynergy再安装一个quicksynergy,的GUI界面。

使用quicksynergy启动图形界面,由于我的笔记本在台式机显示器的左边,所以在quicksynergy图形界面的左侧输入我的笔记本电脑的名字Wenson-PC,点击下方的start。

然后在我的笔记本上安装windows版本的Synergy,选择Use another computer's shared keyboard and mouse。输入Server的IP。点击Start就可以连接上Server了。呵呵,很简单吧。

如果你想让Synergy开机就自动连接的话,那么选择AutoStart...,再选择When Computer Starts,点击install。

Server端如果想开机让他自动启动,那么需要在用户主目录下先创建一个文件名为.synergy.conf的文件。
输入以下内容:
section: screens
wenson-desktop:
Wenson-PC:
end

section: links
wenson-desktop:
left = Wenson-PC
Wenson-PC:
right = wenson-desktop
end

然后在系统的session中添加synergys --daemon --config ~/.synergy.conf 即可实现开机启动。

具体的配置的含义请参考这篇文章:

http://harmony.relax.blogbus.com/logs/16919739.html

Linux服务器端的配置有点复杂,要自己写一个配置文件synergy.conf,用于告诉synergy有哪些主机,各个主机的位置关系等信 息。并且如果要实现自动运行synergy,要修改三个文件,这三个文件在不同的发行版位置不同,名字大致差不多,比如:Ubuntu中,这三个文件是:

/etc/gdm/Init/Default   :登陆界面出现以前,系统加载的程序,我们要在这个文件里添加运行synergy的命令。

/etc/gdm/PostLogin/Default.sample    : 定义了登录过程中要做的事情,这里我们要暂时关闭synergy服务。

/etc/gdm/PreSession/Default :定义了登录后加载的程序,这里我们要重新开启synergy服务。

Fedora一般是在/etc/X11/gdm

第一步,在当前用户目录下新建一个文件命名为:synergy.conf。打开,参考下面的例子,根据实际情况修改一下写入synergy.conf。

section: screens
wisper-desktop:
wisper2-desktop:
end
section: links
wisper-desktop:
left = wisper2-desktop
wisper2-desktop:
right = wisper-desktop
end

其中:wisper-desktop是右边电脑也即服务器端电脑的名字,wisper2-desktop是左边电脑的名字,果你使用双系统,最好将两个系统的电脑名字都修改成一样

第二步,修改/etc/gdm/Init/Default 和 /etc/gdm/PreSession/Default 在它们的最前面添加下面这三行:

/usr/bin/killall synergys
sleep 1
/usr/bin/synergys –config synergy.conf

第三步,在/etc/gdm/PostLogin/Default.sample   中添加下面2行

/usr/bin/killall synergys
sleep 1

第四步,重启。

Posted in 未分类 | Leave a comment

Bash学习笔记-3

bash为用户定制环境提供了4个重要的特性。
特殊文件(Special files ):单用户登录和退出或是启动一个新的shell时,文件.bash_profie,.bash_logout,.bashrc被bash所读取
别名(Aliases):为方便起见,用户对命令或命令字符串所定义的同义词。
选项(Options):对用户环境各方面的控制,可以打开和关闭它们。
变量(Variables):用名字引用的可变值。shell和其他程序可依据保存在变量中的值修改其行为。

.bash_profile、.bash_logout和.bashrc文件
用户主目录下的这些文件对bash有特殊的含义。它们在用户登录或调用另一bash shell时给出了一种自动建立起登录帐号环境的方式,并允许退出时执行各种命令。这些文件可能已经存在于用户主目录下,其依赖于你的系统管理员是如何设置你的帐号的。如果它们不存在,你的帐号就只能使用系统默认文件/etc/profile.

最重要的bash文件是.bash_profile,他在用户每次登录到系统时被读取,其中包含的命令被bash执行。如果你查看一下自己的.bash_profile,可能会发现类似于下面的行:
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
SHELL=/bin/bash
MANPATH=/usr/man:/usr/X11/man
EDITOR=/usr/bin/vi

PS1='\h:\w\$ '
PS2='> '
export EDITOR

我们可以编辑自己的.bash_profile。
注意,直到退出并再次登录,该文件被重新读取后,你向.bash_profile键入的内容才会生效。
或者,可以使用source命令,如:source .bash_profile。
source执行指定文件里的命令,这里是.bash_profile,包括加入的任意命令。
你还可以使用同义命令点(.)

bash允许有.bash_profile的两个同义文件:来源于C Shell的文件.login的.bash_login,和来源于Bourne Shell和Korn Shell的文件.profile的.profile。
登录时,三者中只有一个被读取,如果用户根目录下.bash_profile不存在,则bash查找.bash_login,如果它也不存在,则查找.profile。

bash查找这些同义文件的好处是,如果曾使用过Bourne shell,你可以保留它。如果需要加入特定的bash命令,可以将它们放入.bash_profile中并在后面跟一条命令source .profile。登录时,所有特定的bash命令均被执行,然后bash将会调用.profile,执行其保留的命令。及时决定仍使用Bourne shell,也不必修改已存在的文件。类似方法也可用于.bash_login和C shell的.login,但由于这些shell基本语法的差异性,这不是一个好主意。

.bash_profile只被登录shell读取并执行。如果你通过在命令行上键入bash启动一个新的shell,它就会试图读取.bashrc中的命令。这种策略给出将登录时需要的启动命令和运行一个子shell所需要的命令分离开的灵活性。如果你需要在登录shell和启动一个子shell命令时进行一样的操作,可以在.bahs_profile中使用source命令执行.bashrc。如果.bashrc不存在,那么启动一个子shell时就没有命令被执行。

文件.bash_logout在每次登录shell退出时被读取并执行。它提供了定制用户环境的功能。如果要执行注入删除帐号内临时文件或记录登录系统所花时间等命令,则可将这些命令放在.bash_logout内。该文件不必一定存在于帐号内——如果不存在,则退出时不再执行其他命令。

Posted in 未分类 | Leave a comment

Bash学习笔记-2

启用命令行编辑(Enabling Command-Line Editing)
就是使你在终端中使用交互式shell的操作中,使用vi或是emacs方式,有两种方式进入编辑状态
1.使用set命令
如:set -o emacs
set -o vi
2.在.inputrc中设置readline变量

历史文件(The History File)
所有的bash命令历史设施都依赖于命令列表。当你登录或是启动一个新的交互式shell时,bash就从用户主目录下读取.bash_history文件来初始化历史列表。
从这个角度看,每一个bash的交互式session都维护一个自己的命令列表。当你推出shell的时候,就将自己维护的命令列表存储在.bash_history中。
.bash_shitory的名字是你可以通过设置环境变量HISTFILE来设置任何你喜欢的名字。下一章中我们将更进一步的研究HISTFILE和其他相关的命令历史变量。

这里我使用vi模式,vi是最标准的UNIX编辑器。
vi模式有两种模式:输入模式控制模式
输入模式主要用于键入命令
控制模式主要用于在命令行和历史文件中移动。

vi
输入模式下的编辑命令
命令    说明
DEL    删除前面的字符
CTRL-W    删除前面的单词(即删除至空格)
CTRL-V    引用下一个字符(CTRL-V使得命令行中的出现的下一字符不再具有特殊含义。)
ESC    进入控制模式(见下文)

简单控制模式命令(Simple Control Mode Commands)
vi模式包含两种“单词”概念。最简单的一种是任意非空(non-blank)字符序列,这里称之为非空单词。另一种是字母数字序列(字母和数字)加上下划线(_)或任意非字母数字序列;这里称为单词

基本vi控制模式命令
命令    说明
h    向左移动一个字符
l    向右移动一个字符
w    向右移动一个单词
b    向左移动一个单词
W    移到下一个非空字符的开始
B    移到上一个非空字符的开始
e    移到当前单词的结尾
E    移到当前非空单词的结尾
0    移到行首
^    移到行内第一个非空字符
$    移到行尾

除了最后3个命令之外,所有的这些命令前面都可以加上数字表示重复次数。输入重复次数数值是,其数值在重复命令执行过程中替代了命令提示符。如果键盘有光标移动键(“箭头”键),可以使用左右键来代替h和l键在字符间移动。重复次数对光标移动键也起作用。

输入文本和改变文本(Entering and Changing Text)
命令    说明
i    在当前字符前插入文本(插入)
a    在当前字符后插入文本(附加)
I    在行首插入文本
A    在行尾插入文本
R    用文本覆盖已存在的文本
最常用的是i和a,偶尔会用到R。I和A分别是0i和$a的简写。
注意这里的R是大写的,而不是小写。小写的r是另一个不同的命令,它只替换一个字符,并不进入输入模式。使用r后,输入的字符将覆盖光标所在的字符。如果在r前加数字N,则允许你用“同一个字符”替换该行光标后N个存在的字符,但仍未进入输入模式。

删除命令(Deletion Commands)
vi模式中的基本删除命令是d后跟一个其他字母。该字母决定删除方向和删除单元。
常用的一些删除例子
命令    描述
dh    反向删除一个字符
dl    正向删除一个字符
db    反向删除一个单词
dw    正向删除一个单词
dB    反向删除一个非空单词(向左)
dW    正向删除一个非空单词(向右)
d$    删除到行尾
d0    删除到行首
这些命令有一些变体和缩写。如果你使用c而不是d,则删除后进入输入模式。在d(或c)前或后可以加上数字重复计数。
vi模式删除命令缩写
命令 说明
命令    说明
D    等价于d$(删除到行尾)
dd    等价于0d$(删除整行)
C    等价于c$(删除到行尾,进入输入模式)
cc    等价于0c$(删除整行,进入输入模式)
X    等价于dl(向后删除字符)
x    等价于dh(向前删除字符)
大多数人使用D来删除到行尾,dd删除整行,x(作为“回退”)删除单个字符。

vi模式包含一个删除缓冲器,,保存对当前行文本的所有改动(注意,这和完全vi编辑器不同)。
命令u取消前面对文本的修改。如果键入u,将会取消最后的改动,再次键入会取消之前的改动,当没有可以取消的操作是,bash响铃。
于此相关的命令是(.),它重复最后对文本进行操作的命令。

还有一种将文本保存到删除缓冲器里而不必先执行删除操作的方式:输入删除命令y(yank,移除),而不是d。这样不会改动任何文本,当允许你以后随意检索移出的文本。检索移出文本的命令是p以及P,前者会在当前行光标右边插入文本。后者可在光标左边插入文本。

在历史文件中移动(Moving Around in the History File)
vi控制模式搜索命令历史的命令
命令        说明
k或-        反向移动一行
j或+        正向移动一行
G        移动到重复计数给定的行
/string        反向搜索给定的字符串
?string        正向搜索给定的字符串
n        在与上一次搜索同一方向上重复搜索
N        在于上一次搜索相反方向上重复搜索

如果键盘上有方向键,可用左右方向键完成前两个命令。前三个命令前面均可以加上重复数字计数(如:3k或3-,表示在命令历史中反向移动三行)

字符查找命令(Character-Finding Commands)
命令    说明
fx    向右移到x下一次出现的位置
Fx    向左移到x前一次出现的位置
tx    向右移到x下一次出现的位置,并后退一格
Tx    向左移到x前一次出现的位置,并前进一格
;    重复上一次字符查询命令
,    以相反方向重复上一次字符查询命令

文字完成(Textual Completion)
文字完成的原理很简单:你只需要键入一个文件名、用户名、函数等的部分文字。反斜线命令告诉bash执行vi模式中的完成操作。如果键入一个档次,按ESC进入控制模式,然后键入(\),这是发生下面4个操作中的1中,它们与emacs模式中的TAB键功能相同:
1. 如果没有以该名字开始的文本,shell将响铃并且不做任何事。
2. 如果在搜索路径下存在唯一匹配该字符串的命令名、函数名或文件名,shell就会打印其余部分,后跟空格,以便你键入其他的命令参数。只有在单词位于一行的命令位置时系统才会尝试命令完成(如:一行的开始)。
3. 如果存在唯一匹配字符串的一个目录,shell会完成其文件名,后跟一个斜线。
4. 如果有完成名字的多种结构,shell会给出所有候选的最长公共前缀。搜索路径下的命令名和函数名优先于文件名。

于此相关的一个命令是*。其功能类似于emacs里的ESC-\,如果有多个完成记过匹配(前面列出的第四种情况)。则全部列出,并允许你进一步键入。因而,它类似于shell通配符*。
=命令很少用到,它也是*功能的扩充,但方式不同。它不将名字扩展到命令行,而是打印他们,然后返回shell提示符,再次键入=前命令行上的内容。

还可以扩展其他环境实体,如果被扩展的文本前面是符号$,shell会试图将其扩展成shell变量名。如果文本前面是符号~,会扩展成用户名;如果前面是符号@,则扩展为主机名。

杂项命令(Miscellaneous Commands)
命令        说明
~        转换当前字符大小写
-        扩充前面命令最后一个档次,进入输入模式
CTRL-L        清楚屏幕,在顶部重写当前行号;这在屏幕很乱时很有用
#        给当前行前面加#符号(注释符),并将其发送到历史文件;可用于保存命令以便以后运行,那是就不需要在次键入了。

第一个命令前可以加重复计数。重复计数n加上符号~将改变接下来n个字符的大小写,光标也会相应的向前移动。
重复计数加上_使得前面命令中的第n个单词被插入到当前行;没有技术,则最后一个档次被使用。省略计数也很有用,因此一个文件名通常是UNIX命令行的最后一个参数,用户常常会在一个操作序列中运行几个针对同一个文件的命令。有了此特性,就可以键入所有命令(除了第一个),后跟ESC_,shell就会将文件名插入。

Posted in 未分类 | Leave a comment

Bash学习笔记-1

使用的教材是O'Reilly - Learning the Bash Shell, 2nd Edition

查看当前所使用的shell
echo $SHELL

使用bash
bash

退出bash(结束session)
exit
logout
CTRL-D

查看bash在系统的哪里
whereis bash
如果以上代码不起作用
whence bash
which bash

还不起作用就是用以下这条复杂的代码
grep bash /etc/passwd | awk -F: '{print $7}' | sort -u

将bash安装成你登录时使用的bash,其中的bash-name是你上面查看bash在系统中的位置是得到的,如:/usr/local/bin/bash
chsh bash-name

一条shell命令(shell command)由一个或多个词(world)组成,词与词之间用空格或TAB相隔,第一个词是命令(command)。剩下的是命令的参数(argument或parameter)。
如:lp myfile 由命令lp(打印一个文件)和一个参数myfile组成。lp将myfile作为要打印的文件的名字。
mail cam 命令将cam作为要信息要发送到的用户名

一个选项(option)是一个特殊的参数类型,将要如何处理的特殊信息传递给命令。选项通常由一个短线(dash)跟随着一个字母组成。
如:lp -h myfile 包含一个选项-h,告诉lp在打印文件前不要打印“banner page”

有时候选项也有自己的参数(argument)
如:lp -d lp1 -h myfile 有两个选项和一个参数,其中第一个选项-d lp1 表示发送输出到名字叫lp1的打印机。

文件
文件是UNIX上最重要的东东,事实上有很多不同的文件类型,这里介绍3中最重要的3种:
普通文件(Regular files):又称为文本文件(text file)。这类文件包含刻度的字符。
可执行文件(Executable files):又称为程序(programs)。这类文件可以作为命令调用。一些是不能被人类阅读的,其他的如shell脚本是一些特殊的文本文件。
目录(Directories):这类文件像是文件夹一样包含其他的文件和目录(称为子目录subdirectories)。

目录

在UNIX系统中目录结构是一棵树,树的最顶层称为根(root)。所有的文件都可以通过与根的相对位置来表示。从根开始依次列出每个目录,用(/)隔开,最后跟上文件名。这称为全路径(full pathname)或是绝对路径(absolute pathname)

工作目录(working directory)
为了简化文件的定位,可以使用当前所在的工作目录进行相对定位。
如:当前工作目录为/home/cam
使用命令lp memo 命令将会在/home/cam目录下寻找memo文件.
如果cam目录下有个名为hatter的目录,其中包含一个文件叫teatime。可以使用以下命令对其进行打印。
lp hatter/teatime

波浪号标记
bash对用户主目录(home directories)的缩写可以用(~)加上用户名。
如:可以用~alice/story 来引用用户alice主目录下的story文件
注意这是一个绝对路径,所以使用的时候可以不管你在哪个工作目录下。
如果访问的是用户自己的主目录,则可以使用更简单的方式(~),直接表示当前用户的主目录
如:~/adventure/notes

改变工作目录
cd 目录路径
到用户主目录使用
cd
或是
cd ~
切换到父目录
cd ..
切换到上次工作的目录
cd -

显示当前工作目录
pwd

文件名,通配符,路径名扩展
ls列出文件的信息。
在最简单的形式下,没有选项,没有参数,列出工作目录下的非隐藏文件的文件名
隐藏文件是指命名以(.)开始的文件

如果你给ls一个文件名参数(看起来有点silly^_^),比如说当前工作目录下有文件duchess 和 queen
ls duchess queen 系统将简单的打印这两个文件名。
(本人注:如果给定的文件名是一个目录,则就没那么silly了,系统将列出给定的目录下的所有非隐藏文件的文件名)
ls 命令更多的时候是和选项一起使用的。
如:ls -l 将列出文件的所有者,文件大小,最后修改时间还有其他信息
ls -a 将列出包括隐藏文件在内的所有文件

有时候,我们不知道文件的全名,但是想知道是否存在指定的某类文件,如想知道当前目录下时候有以.txt结尾的文件。这时候就要用到通配符。
你可以使用在文件名中使用称为通配符的特殊字符,在不知道文件全名的情况下,指定文件名集合的模式。
基本的通配符如下表:
通配符        匹配
?        任意单个字符
*        任意字符串(可以表示空字符串)
[set]        任意在集合中的字符
[!set]        任意不在集合中的字符

注意这里的通配符和在MS-DOS中的通配符(.)是一样的,但是在MS-DOS中你需要用*.*来匹配所有的文件,而在UNIX中你只需要使用*就可以匹配所有的文件。而使用*.*只能匹配到那些文件名中包含有一个(.)的文件名

注意集合表示中
[!0-9] 所有的非数字
[0-9!] 所有的数字和感叹号
为了匹配感叹号,需要将其放在其他字符集后或是在其前面加上反斜杠(\),如[\!]
对小写字符,大写字符,数字使用范围(range)是安全的,但是不要对标点符号或是大小写混合的字符使用范围。
如:[a-Z]和[A-z]。不能被确保包含了素有的字符而没有多余的字符。问题在于这样的范围在不同类型的计算机上是不可整体移植的。范围依赖于字符编码表。

匹配包含通配符的表达式的过程被称为通配符扩展或文件名扩展。
比如:使用ls fr* 命令时,shell将命令扩展成 ls fred frank,然后用参数fred 和 frank调用命令ls。如果使用ls g*命令,由于没有匹配的文件,ls将会给予一个字符串g*,所以会

报g*: No such file or directory。

到目前为止我们所看到的关于通配符的例子是一个称为路径名扩展的一部分,这是一个更广的概念
如:ls /usr*
ls /usr*/[be]*

大括号扩展(Brace Expansion)
大括号扩展是一个与路径扩展相近的概念。
路径扩展后的最终结果是那些存在的文件和目录。而大括号扩展将产生生任意的字符串。
如:echo b{ed,olt,ar}s, 将会打印 beds, bolts, 和 bars
这里的b称为前文(preamble),s称为后记(postscript),大括号中的元素用逗号(,)隔开

还可以使用大括号嵌套。
如:{ar{d,n,k},ed}s 将为产生 bards, barns, barks, 和 beds

大括号扩展也可以用到通配符扩展中。
如:ls *.{c,h,o}

注意:bash要求在花括号中至少要有一个(,)来执行扩展,否之整个词(word)将会原封不动。e.g., b{0}lt将仍然是b{o}lt。
注意:
echo P{i} #原封不动
P{i}

echo P{i,} #花括号中其实有两个元素i和空字符串
Pi P

echo P{i,}* #当时用通配符时就成了路径扩展,只能产生存在的文件或是目录名
Pictures Pictures Public

输入和输出
UNIX文件I/O采用任意的长字符(字节)序列的形式。

标准I/O

传统上,每个UNIX程序有一个单一的方法接收输入称为标准输入(standard input),一个单一的方法产生输出称为标准输出(standard output)和一个单一的方法产生错误消息,称为标准错误输出(standard error output)通常简称为标准错误(standard error)。当然,一个程序也可以有其他的输入和输出源。

所有的sell大致上以相同的方式处理标准I/O。每个你调用的程序都有上述3种标准I/O通道,已经在你的终端和工作站上设置好了。键盘是标准输入,屏幕或窗体(window)是标准输出和标准错误输出。

如果必要,你可以重定向你的输入来自于和输出到一个文件。
你也可以通过管道线(pipleline)将程序连接(hook)起来。这是一个程序的标准输出直接提供给另一个程序的标准输入。

这样就可以使用UNIX工具(utilities)作为更大程序的模块。常常每个工具对输入的文本做特定的过滤操作。
常见的过滤工具如下:
工具        目的
cat          拷贝输入到输出
grep       在输入中搜索给定的字符串
sort        对输入中的行进行排序
cut         从输入中提取列
sed         对输入进行编辑操作
tr            将输入中的字符转换成另外的字符
这些工具通常接受一个文件名作为参数并将结果输出到标准输出。上述6种工具和大多数的UNIX工具在不指定参数的情况下,接受标准输入作为输入。
如果UNIX工具在不给定文件名的情况下不接受标准输入,可以试着以(-)作为参数。

I/O重定向
command < filename
这样command就把文件作为标准输入,而不是将终端作为标准输入
如:cat < cheshire 将打印文件cheshire的内容
sort < cheshire 将对cheshire文件的行进行排序

同样,command > filename将使得command的标准输出被重定向到给定的命名文件。
如:date > now 该命令中,date命令将打印当前日期和时间到标准输出,然后被重定向到文件now中保存

输入、输出重定向可以合起来使用
如:cat < file1 > file2 该命令完成了file1到file2的拷贝任务,同命令cp file1 file2

管道线(pipelines)
也可以将一个命令的输出重定向后作为另一个命令的标准输入。完成这样任务的设施称为管道(pipe),记号为(|)。
一个命令行包含两个或两个以上的由管道连接起来的命令称为管道线(pipleline)

管道经常与more命令一起使用。
如:ls -l | more 该命令将一屏一屏的现实文件信息。当用户输入SPACE时,显示下一屏,输入RETURN,显示下一行。
sort < cheshire | lp 该命令将cheshire文件的行排序后直接送到打印机打印,而不是在屏幕上显示。

下面举一个稍微复杂点的例子。在UNIX系统中/etc/passwd文件存储了用户帐户的信息,没一行文件包含一个用户登录名,用户ID号,加密后的密码,主目录,登录的shell和其他信息。每一行的第一个

域是用户的登录名,域和域之间用冒号分隔(:)。下面是一个示例行:
cam:LM1c7GhNesD4GhF3iEHrH4FeCKB/:501:100:Cameron Newham:/home/cam:/bin/bash
为了得到排序后的系统用户表,我们只需要执行以下命令:
cut -d: -f1 < /etc/passwd | sort
事实上cut命令是可以接受文件名作为参数的,所以可以省略 < ,cut命令从输入中提取出第一个域(-f1),域的分隔符为冒号(-d :) 。整个管道线将会打印出类似如下的内容:
adm
bin
cam
daemon
davidqc
ftp
games
gonzo
...

如果你想将结果自己打印出来,你可以扩展管道线成如下所示:
cut -d: -f1 < /etc/passwd | sort | lp
通过使用管道,我们可以减少不必要的临时文件,直接将前一条命令的输出作为后一条命令的输入。

后台作业(Background Jobs)
管道其实是一个更广的特性:在同一时间做多件事情的一个特例。

shell也允许你在一个Session中在同一时间运行多个命令,一般情况下,当你输入一条命令并敲RETURN后,shell将让这些命令控制你的终端直至运行完毕。在此期间你你不能输入新的命令。但是如果你

运行的是一个不需要用户输入,并且在其运行期间,你想运行其他命令,那么在该命令后加上(&)符号。这称为在后台运行命令。以此方式运行的命令称为后台作业。于此对应的,一个作业在一般情况下运行称为前台作业。
如:uncompress gcc.tar & 诸如sort和uncompress命令在操作大型文件时,需要花费很长的时间,这时你就可以将该命令在后台运行。
如果你想查看后台运行的任务,需要输入命令jobs

后台I/O(Background I/O)
在后台运行的作业不应该在你的终端上操作I/O
如果一个后台作业需要键盘输入,那么它常常会停在那什么也不做,知道你对其进行处理。
如果一个后台作业产生屏幕输出,那么这些输出将会直接出现在屏幕上,如果你在前台运行的程序也产生屏幕输出,那么两者的输出将会随机的交叉。
如果你想运行的后台作业需要标准输入和标准输出,那么你通常需要重定向I/O使其输入自和输出到一个文件。如果程序产生的输出很少,则可以不用将输出重定向到一个文件。
如:diff warandpeace.txt warandpeace.txt.old & 当两个文件的差别非常小的时候,产生的输出很少,可以直接使用标准输出到终端
diff warandpeace.txt warandpeace.txt.old > txtdiff & 当两个文件的差别很大的时候,产生的额输出就很多了,这时需要将输出重定向到一个文件。

后台任务和优先级(Background Jobs and Priorities)
记住,这些后台运行的任务会吃掉很多系统的资源,如内存和CPU。你同时运行多个任务并不意味着它将比顺序执行这些任务更快——事实上,性能上会稍微差一点。
每个作业在系统中都会给予一个优先级(priority),这是一个数字告诉操作系统当分配资源的时候给予一个任务以多大的优先级。(这个数字越大,优先级越低)。
在shell中输入的命令,不管是前台还是后台任务,通常具有相同的优先级。系统管理员通常比普通用户以更高的优先级执行任务。
在共享资源的UNIX系统中,做一个好的“公民”是很有必要的,UNIX提供了一条命令,可以降低你的任务的优先级,该命令的名称也很有意思,称为nice
如:nice command 该命令中的command可以是具有管道或是重定向的非常复杂的shell命令行。你还可以通过给nice命令一个数字参数控制降低多少优先级。详细情况请查询nice的manpage。

特殊字符和引用(Special Characters and Quoting)
字符<,>,|,和 &以及前面我们见到过的通配符(*, ?, and [...]) 都是对shell有特殊意义的特殊字符(special characters)
下表给出了,所有的在shell命令中使用的特殊字符。其他的在特定情况下,如在正则表达式或字符串操作中具有特殊含义的特殊字符,将会在后面介绍:
字符            含义                    参见章节
~            主目录                    1
`            命令替换 (已废弃)            4
#            注释                    4
$            变量表达式                3
&            后台任务                1
*            字符串通配符                1
(            子shell开始标记                8
)            子shell结束标记                8
\            引用下一个字符                1
|            管道                    1
[            字符集通配符开始标记            1
]            字符集通配符结束标记            1
{            命令块开始标记                7
}            命令块结束标记                7
;            shell命令分隔符                3
'            强引用                    1
<">            弱引用                    1
<            输入重定向                1
>            输出重定向                1
/            路径名分隔符                1
?            单字符通配符                1
!            管道逻辑非                5

引用(Quoting)
有时候我们想使用特殊字符的字面意思,而不是其特殊的含义,这称为引用(quoting)。如果你用单引号将一个字符串括起来,你就除去了引号中所有字符的特殊含义。
如:echo 2 * 3 > 5 is a valid inequality. 该命令创建一个文件名为5,里面的内容为 2 * 3 is a valid inequality
echo '2 * 3 > 5 is a valid inequality.' 该命令的结果是一个字符串
echo '2 * 3 > 5' is a valid inequality. 该命令的结果同上

反斜线转义(Backslash-Escaping)
另一种改变字符含义的方法是使用反斜线(\)。这称为反斜线转义(backslash-escaping)字符。大多数情况下,当你反斜线转义一个字符是,你引用(quote)它。
如:echo 2 \* 3 \> 5 is a valid inequality. 该命令产生的结果和上面的单引号引用是一样的。
为了使用反斜线的字面意思,也同样可以使用单引号引用('\'),或者更好的是使用反斜线转义(\\)。

有些UNIX命令需要的参数包含需要转义的通配符,从而使得shell不预先处理,而留给command去处理,最常见的例子是find命令,用来在整个目录树中寻找文件。
使用find,你需要提供一个目录树的节点作为查询的根,然后提供参数描述你所需要的找到的文件的特征。
如:find . -name string 该命令在当前目录,包括子目录下寻找文件名满足字符串string的所有文件。
find . -name '*.c' 该命令在当前目录,包括子目录下寻找文件名以.c结尾的所有文件。

引用引用标记(Quoting Quotation Marks)
你也可以使用反斜线来引用双引号使其包含在一个应用字符串中。
如:echo \"2 \* 3 \> 5\" is a valid inequality. 该命令输出为"2 * 3 > 5" is a valid inequality.

然而,这对引用字符串中的单引号并不起作用。
如:echo 'Hatter\'s tea party' 该命令将不会输出Hatter's tea party
我们可以有多种方式绕过该限制。
首先,我们可以去掉引号:echo Hatter\'s tea party
或者,可以使用如下命令:echo 'Hatter'\''s tea party'
注意这里的'\''并不是一个单引号在一个引用字符串中,而是前面的单引号',结束了前面的引用字符串,然后\'添加了'的字面意思,后面的'开始新的一个引用字符串。

续行(Continuing Lines)
在shell中如何续行很简单,只需要引用RETURN键(quote the RETURN key)。
你可以通过两种方式做到这一点:
用反斜线结束一行。如果使用这种方式,则在反斜线和行末尾之间不能有任何东西,甚至不能有space和TAB
如:
echo The Caterpillar and Alice looked at each other for some \
> time in silence: at last Caterpillar took the hookah out of its \
> mouth, and addressed her in a languid, sleepy voice.

或是通过不结束一个引用(如,在引用字符串中包含RETURN)
如:
echo 'The Caterpillar and Alice looked at each other for some
> time in silence: at last Caterpillar took the hookah out of its
> mouth, and addressed her in a languid, sleepy voice.'

控制键(Control Keys)
RETURN = CTRL-M
DEL = CTRL-?
你可以通过stty命令来查看系统的控制键设置,如果系统是UNIX是从BSD发展而来的(如:SunOS和Ultrix),输入stty all,将会看到如下输出;
erase kill werase rprnt flush lnext susp intr quit stop eof
^? ^U ^W ^R ^O ^V ^Z/^Y ^C ^\ ^S/^Q ^D

如果系统是从System III或是System V发展而来的(如,AIX,HP/UX,SCO,Linux和Xenix),输入stty -a,将会看到如下输出:
intr = ^c; quit = ^|; erase = DEL; kill = ^u; eof = ^d; eol = ^`; swtch = ^`; susp = ^z; dsusp ;

控制键            stty中的名字        函数描述
CTRL-C            intr            停止当前命令
CTRL-D            eof            结束输入
CTRL-\            quit            停止当前命令, 如果 CTRL-C 不能凑效
CTRL-S            stop            暂停到屏幕的输出
CTRL-Q                        重启到屏幕的输出
DEL or CTRL-?        erase            擦除最后一个字符
CTRL-U            kill            擦除整个命令行
CTRL-Z            susp            暂停当前命令 (see Chapter 8)

在一般情况下,我们优先使用CTRL-C来停止当前命令,只有当其不凑效时,才使用CTRL-\,因为CTRL-C在停止命令的时候允许命令在推出前做一些清理工作。不至于是文件和其他资源出现可笑的状态。

帮助(Help)
bash区别于其他shell的一个重要特点是其帮助系统。help命令给出bash中的命令信息。
如果你仅仅输入help,则会得到一个shell内建命令包括选项的列表
如果你给help一个shell命令作为参数,将会给你一个命令的详细的描述

你也可以给help提供部分名字。将返回所有匹配的命令的详细信息。
如:help re 该命令将给出read,readonly和return的详细信息。
部分名字也可以包含通配符。你需要对通配符进行引用,防止其扩展成文件名。
如:help 're*' 该命令将返回read,readonly和return的详细信息。
help 're??' 该命令将只返回read的详细信息。

如果help命令返回的内容多于一屏,则可以使用
help command | more

Posted in 未分类 | Leave a comment