Oct 21, 2008

C# 读取gb2312文本文件

StreamReader objReader = new StreamReader(strFilename,System.Text.Encoding.GetEncoding("gb2312"));

如果不加第二个参数,读出来的中文是乱码

Python 自动搜索可用ip并设置

Python设置IP Address,用的是 qujinlong123@gmail.com 的,详见:用Python 干实事(一)自动修改Windows的IP、网关和DNS设置


我添加了搜索功能

# -*- coding: GB2312 -*-

# FileName: modify_ip.py
# Author  : ox0spy
# Email   : ossteerer@gmail.com
# Date    : 2008-10-21

# 程序的前两个函数是qujinlong123@gmail.com实现的,这里借用下


import _winreg
from ctypes import *

def    ModifyIpAddress(ipAddress, subnetMask, gateway, dnsServer):
    netCfgInstanceID = None
   
    hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \
                           r'System\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}')
   
    keyInfo = _winreg.QueryInfoKey(hkey)
   
    # 寻找网卡对应的适配器名称 netCfgInstanceID
    for index in range(keyInfo[0]):
        hSubKeyName = _winreg.EnumKey(hkey, index)
        hSubKey = _winreg.OpenKey(hkey, hSubKeyName)
   
        try:
            hNdiInfKey = _winreg.OpenKey(hSubKey, r'Ndi\Interfaces')
            lowerRange = _winreg.QueryValueEx(hNdiInfKey, 'LowerRange')
   
            # 检查是否是以太网
            if lowerRange[0] == 'ethernet':
                driverDesc = _winreg.QueryValueEx(hSubKey, 'DriverDesc')[0]
                # print 'DriverDesc: ', driverDesc
                netCfgInstanceID = _winreg.QueryValueEx(hSubKey, 'NetCfgInstanceID')[0]
                # print 'NetCfgInstanceID: ', netCfgInstanceID
                break
   
            _winreg.CloseKey(hNdiInfKey) # 关闭 RegKey
        except WindowsError, e:
                            pass
                # print r'Message: No Ndi\Interfaces Key'
           
        # 循环结束,目前只提供修改一个网卡IP的功能
        _winreg.CloseKey(hSubKey)
   
    _winreg.CloseKey(hkey)
   
    if netCfgInstanceID == None:
        print '修改IP失败 - 没有找到网络适配器'   
        exit()
   
    # print netCfgInstanceID
   
    # 通过修改注册表设置IP
    strKeyName = 'System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\' + netCfgInstanceID
   
    # print strKeyName
   
    hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \
                           strKeyName, \
                           0, \
                           _winreg.KEY_WRITE)
   
    try:
        _winreg.SetValueEx(hkey, 'IPAddress', None, _winreg.REG_MULTI_SZ, ipAddress)
        _winreg.SetValueEx(hkey, 'SubnetMask', None, _winreg.REG_MULTI_SZ, subnetMask)
        _winreg.SetValueEx(hkey, 'DefaultGateway', None, _winreg.REG_MULTI_SZ, gateway)
        _winreg.SetValueEx(hkey, 'NameServer', None, _winreg.REG_SZ, ','.join(dnsServer))
    except WindowsError:
        print 'Set IP Error'
        exit()
   
    _winreg.CloseKey(hkey)
    return netCfgInstanceID
   
# 调用DhcpNotifyConfigChange函数通知IP被修改
def Notify(netCfgInstanceID, ipAddress, subnetMask):
    DhcpNotifyConfigChange = windll.dhcpcsvc.DhcpNotifyConfigChange

    inet_addr = windll.Ws2_32.inet_addr

    # DhcpNotifyConfigChange 函数参数列表:
    # LPWSTR lpwszServerName,  本地机器为None
    # LPWSTR lpwszAdapterName, 网络适配器名称
    # BOOL bNewIpAddress,      True表示修改IP
    # DWORD dwIpIndex,         表示修改第几个IP, 从0开始
    # DWORD dwIpAddress,       修改后的IP地址
    # DWORD dwSubNetMask,      修改后的子码掩码
    # int nDhcpAction          对DHCP的操作, 0 - 不修改, 1 - 启用, 2 - 禁用
    DhcpNotifyConfigChange(None, \
                       netCfgInstanceID, \
                       True, \
                       0, \
                       inet_addr(ipAddress[0]), \
                       inet_addr(subnetMask[0]), \
                       0)


def Pin(ip = '192.168.1.1'):
    """ ping -n 1 ip"""
   
    import os
    if os.system("ping -n 1 %s >nul" % ip) == 0:
        return True
   
    return False   
               
def GetConfInfo(filename = 'conf.ini'):
        import re, sys
        try:
                f = open(filename, 'r')
                lines = [line.split('#')[0].strip() for line in f.readlines()]
                f.close()

                if len(lines) >= 6:
                        # ip网段
                        network = lines[0]
                        pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
                        if not re.search(pattern, network):
                                print '网段设置错误,请修改配置文件网段信息'
                                sys.exit(2)
                        network = network.split('.')
                        network.pop()
                        network = '.'.join(network)
                        # print 'network : ', network
                        # 开始ip
                        startIp = int(lines[1])
                        if (startIp < 1 or startIp > 254):
                                print '开始ip设置错误, ip :', startIp
                                sys.exit(3)
                        # 结束ip
                        endIp = int(lines[2])
                        if endIp < 2 or startIp > 255:
                                print '结束ip设置错误'
                                sys.exit(4)
                        # 子网掩码
                        subnetMask = lines[3]
                        # 默认网关
                        gateway = lines[4]
                        if not re.search(pattern, gateway):
                                print '默认网关设置错误'
                                sys.exit(5)
                        # dns
                        dnsServ = lines[5]
                        if not re.search(pattern, dnsServ):
                                print 'dns服务器设置错误'
                                sys.exit(6)
                else:
                        print '配置文件有误,请修正后重试'
                        sys.exit(1)
                     
        except IOError, e:
                print '确定配置文件名为 : %s' % filename
                sys.exit(7)

        return [network, startIp, endIp, subnetMask, gateway, dnsServ]

Info = GetConfInfo()
if not Info:
        sys.exit()

network, startIp, endIp, subnetMask, gateway, dnsServ = Info
if startIp == endIp:
        endIp += 1
       
ipAddress = ['%s.%s' % (network, i) for i in range(startIp, endIp)]
subnetMask = [subnetMask]
gateway = [gateway]
dnsServer = [dnsServ]
url = 'http://ox0spy.blogspot.com'

MessageBox = windll.user32.MessageBoxA

for ip in ipAddress:
    ip = [ip]
    # print 'IP Address : ', ip
    netCfgInstanceID = ModifyIpAddress(ip, subnetMask, gateway, dnsServer)
    Notify(netCfgInstanceID, ip, subnetMask)
    if Pin(url):
        # print '可用Ip地址 :', ip[0]
        msg = '可用Ip地址 : %s o(∩_∩)o...' % ip[0]
        MessageBox(0, msg, 'Good luck', 0)
        break;
else:
        msg = '没有可用ip,换个网段试试 ^_^'
        MessageBox(0, msg, 'sorry', 0)

ttylinux Tips

1. ttylinux 引导程序安装
环境:vmware平台上装ttylinux
以前用vmware装完redhat等其他linux后,安装程序会自动把引导程序装好的,但ttylinux不同,它的引导程序必须自己手动 安装。
其实,非常简单
#installer mbr /dev/hdc /dev/hda
注:我只虚拟出一个硬盘,没有任何分区。
更多可以参考:http://www.minimalinux.org/ttylinux/docs/user_multi/node16.html

2. ttylinux 联网
///这完全是我的机器配置,不同isp提供的很多东西都是不一样的
 
I、设置ip addr、netmask、BROADCAST (我用的是静态ip)
#cp /etc/network.d/sample  /etc/network.d/interface.eth0
#vi /etc/network.d/interface.eth0
内容如下:
# network interface configuration file sample
# change settings and rename to interface.devname, i.e. interface.eth0
# network device name
INTERFACE="eth0"
# set to "yes" to use DHCP instead of the settings below
DHCP="no"
# interface settings
# IP address
IPADDRESS="192.168.18.18"
# netmask
NETMASK="255.255.255.0"
# gate way
#GATEWAY=192.168.18.1
# broadcast address
BROADCAST="192.168.18.255"
 
II、添加默认网关
#route add default gw 192.168.18.1
 
III、设置DNS 
#vi etc/resolv.conf
内容如下:
nameserver      219.146.0.130
nameserver      61.233.154.33
search localdomain
 
IV、编辑/etc/hosts,便于和我的win 2003、redhat互联
 
V、ttylinux不支持ftp,不过文件传输可以使用scp,tftp
  
     scp命令格式:
     scp local_files username@hostname:path/to/file
     scp username@hostname:path/to/file local_file
     例如:
     scp ./*.html jhou@www.nctu.edu.tw:www/portfolio/2005/
     就是将本地目前所在目录中的所有 .html 文件拷贝到 athena 的个人网页空间的 portfolio/2005/ 次目录中。
     tftp命令格式:
     tftp -i ip put/get files
     注:put 上传;get 下载
          files就是你要传输的文件