Sam's Notes | Sam Blog

梦想还是要有的,万一实现了呢

0%

Spring MVC Test Framework建立在Servlet API mock objects基础上,他不需要一个运行的Servlet容器,
不需要,不需要,不需要!
他使用DispatcherServlet来提供完整Spring MVC的支持,使用TestContext framework来加载实际的Spring各个配置。

Server-Side Tests

Spring MVC Test的目的:提供一种有效的利用DispatcherServlet所伴生的requests和responses来测试controller的方式。
例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("test-servlet-context.xml")
public class ExampleTests {

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}

@Test
public void getAccount() throws Exception {
this.mockMvc.perform(get("/accounts/1").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$.name").value("Lee"));
}

}

Setup Options

  • webAppContextSetup

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration("my-servlet-context.xml")
    public class MyWebTests {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    // ...

    }
  • standaloneSetup(简单controller实例)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public class MyWebTests {

    private MockMvc mockMvc;

    @Before
    public void setup() {
    this.mockMvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
    }

    // ...

    }

如何选择?
webAppContextSetup 方式:加载并缓存完整的Spring MVC配置,

standaloneSetup 方式:更像一个单元测试

他们就像集成测试Vs单元测试。

Performing Requests

1
2
3
4
5
6
7
8
9
mockMvc.perform(post("/hotels/{id}", 42).accept(MediaType.APPLICATION_JSON));

mockMvc.perform(fileUpload("/doc").file("a1", "ABC".getBytes("UTF-8")));

mockMvc.perform(get("/hotels?foo={foo}", "bar"));

mockMvc.perform(get("/hotels").param("foo", "bar"));

mockMvc.perform(get("/app/main/hotels/{id}").contextPath("/app").servletPath("/main"))

测试预期

测试预期结果可以在Requests后面加一个或多个 .andExpect(..)

1
2
3
4
mockMvc.perform(post("/persons"))
.andDo(print()) // static import from MockMvcResultHandlers, can print all the available result data
.andExpect(status().isOk())
.andExpect(model().attributeHasErrors("person"));

如果需要直接访问结果来验证一些其他数据,在测试预期最后加上 .andReturn()

1
MvcResult mvcResult = mockMvc.perform(post("/persons")).andExpect(status().isOk()).andReturn();

HtmlUnit Integration TODO

Client-Side REST Tests

使用RestTemplate进行客户端的REST测试。

1
2
3
4
5
6
7
8
RestTemplate restTemplate = new RestTemplate();

MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
mockServer.expect(requestTo("/greeting")).andRespond(withSuccess("Hello world", MediaType.TEXT_PLAIN));

// use RestTemplate ...

mockServer.verify();

PetClinic Example

Spring官方提供的完整案例Github

Spring TestContext Framework

TODO 设计原理和实现

TestContextManager : Spring TestContext Framework的主入口,管理单例的TestContext和所有注册的TestExecutionListeners。
TestContext
TestExecutionListener
ContextLoader

Context management

每个TestContext提供 context 管理, 测试实例无权配置ApplicationContext, 实例仅能获得一个ApplicationContext的引用。特别的是AbstractJUnit4SpringContextTests和AbstractTestNGSpringContextTests实现了ApplicationContextAware而且有权修改ApplicationContext。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {

@Autowired
private ApplicationContext applicationContext;

// class body...
}


@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class MyWebAppTest {
@Autowired
private WebApplicationContext wac;

// class body...
}

注入mocks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@WebAppConfiguration
@ContextConfiguration
public class WacTests {

@Autowired
WebApplicationContext wac; // cached

@Autowired
MockServletContext servletContext; // cached

@Autowired
MockHttpSession session;

@Autowired
MockHttpServletRequest request;

@Autowired
MockHttpServletResponse response;

@Autowired
ServletWebRequest webRequest;

//...
}

执行SQL scripts

  • 代码
    下列都可以用来执行
    org.springframework.jdbc.datasource.init.ScriptUtils
    org.springframework.jdbc.datasource.init.ResourceDatabasePopulator
    org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests
    org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @Test
    public void databaseTest {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScripts(
    new ClassPathResource("test-schema.sql"),
    new ClassPathResource("test-data.sql"));
    populator.setSeparator("@@");
    populator.execute(this.dataSource);
    // execute code that uses the test schema and data
    }
  • @Sql

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    //1
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    @Sql("/test-schema.sql")
    public class DatabaseTests {

    @Test
    public void emptySchemaTest {
    // execute code that uses the test schema without any test data
    }

    @Test
    @Sql({"/test-schema.sql", "/test-user-data.sql"})
    public void userTest {
    // execute code that uses the test schema and test data
    }
    }



    //1
    @Test
    @Sql(scripts = "/test-schema.sql", config = @SqlConfig(commentPrefix = "`"))
    @Sql("/test-user-data.sql")
    public void userTest {
    // execute code that uses the test schema and test data
    }


    //3
    @Test
    @SqlGroup({
    @Sql(scripts = "/test-schema.sql", config = @SqlConfig(commentPrefix = "`")),
    @Sql("/test-user-data.sql")
    )}
    public void userTest {
    // execute code that uses the test schema and test data
    }


    //4
    @Test
    @Sql(
    scripts = "create-test-data.sql",
    config = @SqlConfig(transactionMode = ISOLATED)
    )
    @Sql(
    scripts = "delete-test-data.sql",
    config = @SqlConfig(transactionMode = ISOLATED),
    executionPhase = AFTER_TEST_METHOD
    )
    public void userTest {
    // execute code that needs the test data to be committed
    // to the database outside of the test's transaction
    }

TestContext Framework支持类

Spring JUnit Runner

1
2
3
4
5
6
7
8
9
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({})
public class SimpleTest {

@Test
public void testMethod() {
// execute test logic...
}
}

如果要使用MockitoJUnitRunner等第三方runners, 可以使用Spring JUnit Rules。

Spring JUnit Rules

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Optionally specify a non-Spring Runner via @RunWith(...)
@ContextConfiguration
public class IntegrationTest {

@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();

@Test
public void testMethod() {
// execute test logic...
}
}

Annotations

Spring Testing Annotations

  • @ContextConfiguration
    类级别注解,用来声明如何加载和配置ApplicationContext。可以使用XML配置文件和被@Configuration注解的类。
    例如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    // 1) xml
    @ContextConfiguration("/test-config.xml")
    public class XmlApplicationContextTests {
    // class body...
    }

    // 2) @Configuration Class
    @ContextConfiguration(classes = TestConfig.class)
    public class ConfigClassApplicationContextTests {
    // class body...
    }

    // 3) `ApplicationContextInitializer` Class
    @ContextConfiguration(initializers = CustomContextIntializer.class)
    public class ContextInitializerTests {
    // class body...
    }

    // 4) ContextLoader
    @ContextConfiguration(locations = "/test-context.xml", loader = CustomContextLoader.class)
    public class CustomLoaderXmlApplicationContextTests {
    // class body...
    }
  • @WebAppConfiguration
    类级别注解,用来声明如何加载WebApplicationContext。默认"file:src/main/webapp"为web App根目录。必须协同 @ContextConfiguration才生效

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @ContextConfiguration
    @WebAppConfiguration
    public class WebAppTests {
    // class body...
    }




    @ContextConfiguration
    @WebAppConfiguration("classpath:test-web-resources")
    public class WebAppTests {
    // class body...
    }
  • @ContextHierarchy
    类级别注解,声明多层级的@ContextConfiguration

    1
    2
    3
    4
    5
    6
    7
    @ContextHierarchy({
    @ContextConfiguration("/parent-config.xml"),
    @ContextConfiguration("/child-config.xml")
    })
    public class ContextHierarchyTests {
    // class body...
    }
    1
    2
    3
    4
    5
    6
    7
    8
    @WebAppConfiguration
    @ContextHierarchy({
    @ContextConfiguration(classes = AppConfig.class),
    @ContextConfiguration(classes = WebConfig.class)
    })
    public class WebIntegrationTests {
    // class body...
    }
  • @ActiveProfiles
    类级别注解,声明ApplicationContext使用哪些profiles。

    1
    2
    3
    4
    5
    @ContextConfiguration
    @ActiveProfiles("dev")
    public class DeveloperTests {
    // class body...
    }
    1
    2
    3
    4
    5
    @ContextConfiguration
    @ActiveProfiles({"dev", "integration"})
    public class DeveloperIntegrationTests {
    // class body...
    }
  • @TestPropertySource
    类级别注解,指定加载properties文件或手动增加PropertySources的内容

    1
    2
    3
    4
    5
    @ContextConfiguration
    @TestPropertySource("/test.properties")
    public class MyIntegrationTests {
    // class body...
    }
    1
    2
    3
    4
    5
    @ContextConfiguration
    @TestPropertySource(properties = { "timezone = GMT", "port: 4242" })
    public class MyIntegrationTests {
    // class body...
    }
  • @DirtiesContext
    类或方法级别注解,根据不同策略,Spring TestContext会刷新Spring的上下文(就是重新创建ApplicationContext)
    有各种策略

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    // BEFORE_CLASS
    @DirtiesContext(classMode = BEFORE_CLASS)
    public class FreshContextTests {
    // some tests that require a new Spring container
    }



    //default class mode : `AFTER_CLASS`
    @DirtiesContext
    public class ContextDirtyingTests {
    // some tests that result in the Spring container being dirtied
    }



    // BEFORE_EACH_TEST_METHOD
    @DirtiesContext(classMode = BEFORE_EACH_TEST_METHOD)
    public class FreshContextTests {
    // some tests that require a new Spring container
    }



    // AFTER_EACH_TEST_METHOD
    @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
    public class ContextDirtyingTests {
    // some tests that result in the Spring container being dirtied
    }



    // BEFORE_METHOD
    @DirtiesContext(methodMode = BEFORE_METHOD)
    @Test
    public void testProcessWhichRequiresFreshAppCtx() {
    // some logic that requires a new Spring container
    }



    //default method mode `AFTER_METHOD`
    @DirtiesContext
    @Test
    public void testProcessWhichDirtiesAppCtx() {
    // some logic that results in the Spring container being dirtied
    }
  • @TestExecutionListeners

  • @Commit

  • @Rollback

  • @BeforeTransaction

  • @AfterTransaction

  • @Sql

  • @SqlConfig

  • @SqlGroup

Standard Annotation Support

Spring TestContext Framework 支持下列标准的注解

  • @Autowired
    
  • @Qualifier
  • @Resource (javax.annotation) if JSR-250 is present
  • @Inject (javax.inject) if JSR-330 is present
  • @Named (javax.inject) if JSR-330 is present
  • @PersistenceContext (javax.persistence) if JPA is present
  • @PersistenceUnit (javax.persistence) if JPA is present
  • @Required
  • @Transactional

Spring JUnit Testing Annotations

组合SpringJUnit4ClassRunner, Spring’s JUnit rules, 或 Spring’s JUnit support classes使用的时候,Spring TestContext Framework 还支持下列标准的注解:

  • @IfProfileValue
    类级别或方法级别注解,校验具体的环境变量,匹配才进行测试,否则就会忽略。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @IfProfileValue(name="java.vendor", value="Oracle Corporation")
    @Test
    public void testProcessWhichRunsOnlyOnOracleJvm() {
    // some logic that should run only on Java VMs from Oracle Corporation
    }


    @IfProfileValue(name="test-groups", values={"unit-tests", "integration-tests"})
    @Test
    public void testProcessWhichRunsForUnitOrIntegrationTestGroups() {
    // some logic that should run only for unit and integration test groups
    }
  • @ProfileValueSourceConfiguration

  • @Timed

    1
    2
    3
    4
    @Timed(millis=1000)
    public void testProcessWithOneSecondTimeout() {
    // some logic that should not take longer than 1 second to execute
    }
  • @Repeat

    1
    2
    3
    4
    5
    @Repeat(10)
    @Test
    public void testProcessRepeatedly() {
    // ...
    }

Spring MVC 的配置 Configuring Spring MVC

* 开启Spring MVC默认配置

Java Config: 加入 @EnableWebMvc 到 某个有 @Configuration 注解的类头。

1
2
3
4
5
@Configuration
@EnableWebMvc
public class WebConfig {

}

XML方式: 增加mvc:annotation-driven 到 DispatcherServlet 的context里面。

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<mvc:annotation-driven />

</beans>

* 自定义Spring MVC配置

Java Config: 加入 @EnableWebMvc 到 某个有 @Configuration 注解的类头。自己实现 WebMvcConfigurer, 更多是继承 WebMvcConfigurerAdapter并重写你自己需要的方法。

1
2
3
4
5
6
7
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

// Override configuration methods...

}

XML方式: 增加mvc:annotation-driven 到 DispatcherServlet 的context里面。设置自己需要Spring MVC XML schema里面的元素值。

* 高级自定义Spring MVC配置

Java Config: 去掉 @EnableWebMvc@Configuration 注解类头,自己实现 WebMvcConfigurationSupport., 更多是继承 DelegatingWebMvcConfiguration并重写你自己需要的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
public class WebConfig extends DelegatingWebMvcConfiguration {

@Override
public void addInterceptors(InterceptorRegistry registry){
// ...
}

@Override
@Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
// Create or let "super" create the adapter
// Then customize one of its properties
}

}

具体内容看头部的官方文档

springmvc一

@RequestMapping URI

URI Template Patterns

spring doc

如何匹配这个url "/spring-web/spring-web-3.0.5.jar"

@RequestMapping 支持正则表达式, 语法就是 {varName:regex}

比如上面那个url就可以这样

1
2
3
4
5
@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
public void handle(@PathVariable String version, @PathVariable String extension) {
// ...
}
}

Path Pattern Comparison

多重匹配优先规则:

  • 越少数量URI variables 和 wild cards 的表达式越优先;例如/hotels/{hotel}/*/hotels/{hotel}/** 优先
  • 数量一致,越长的表达式越优先;例如/foo/bar*/foo/* 优先
  • 数量和长度一致, 越少wild cards的表达式越优先;例如/hotels/{hotel}/hotels/* 优先
  • 例外的 /api/{a}/{b}/{c/** 优先

Path Pattern Matching By Suffix

默认Spring MVC会自动增加后缀 ".*" 来匹配URI。比如 /person 会自动映射成 /person.* , 可以自动匹配文件类型,如/person.pdf, /person.xml,不能匹配 /person.com
.com 不是文件类型。

Matrix Variables

需要修改下默认配置 ,,,,就可以使用 “Matrix URIs”

1
2
3
4
5
6
7
8
9
// GET /pets/42;q=11;r=22

@RequestMapping(path = "/pets/{petId}", method = RequestMethod.GET)
public void findPet(@PathVariable String petId, @MatrixVariable int q) {

// petId == 42
// q == 11

}
1
2
3
4
5
6
7
8
9
10
11
// GET /owners/42;q=11/pets/21;q=22

@RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET)
public void findPet(
@MatrixVariable(name="q", pathVar="ownerId") int q1,
@MatrixVariable(name="q", pathVar="petId") int q2) {

// q1 == 11
// q2 == 22

}
1
2
3
4
5
6
7
8
// GET /pets/42

@RequestMapping(path = "/pets/{petId}", method = RequestMethod.GET)
public void findPet(@MatrixVariable(required=false, defaultValue="1") int q) {

// q == 1

}
1
2
3
4
5
6
7
8
9
10
11
// GET /owners/42;q=11;r=12/pets/21;q=22;s=23

@RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET)
public void findPet(
@MatrixVariable Map<String, String> matrixVars,
@MatrixVariable(pathVar="petId"") Map<String, String> petMatrixVars) {

// matrixVars: ["q" : [11,22], "r" : 12, "s" : 23]
// petMatrixVars: ["q" : 11, "s" : 23]

}

BindingResult and @ModelAttribute

BindingResult必须直接跟在@ModelAttribute后面

1
2
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, Model model) { ... }

各种参数绑定

@PathVariable

  • 绑定URI的参数,若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable(“name”)指定uri template中的名称。

@RequestHeader

  • 可以把Request请求header部分的值绑定到方法的参数
    1
    2
    3
    4
    5
    6
    7
    @RequestMapping("/displayHeaderInfo.do")  
    public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
    @RequestHeader("Keep-Alive") long keepAlive) {

    //...

    }

@CookieValue

  • 把Request header中关于cookie的值绑定到方法的参数

@RequestParam

  • 常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String–> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;
  • 用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;
  • 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定

@RequestBody

  • 该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;
  • 它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。
  • 因为配置有FormHttpMessageConverter,所以也可以用来处理 application/x-www-form-urlencoded的内容,处理完的结果放在一个MultiValueMap<String, String>里,这种情况在某些特殊需求下使用,详情查看FormHttpMessageConverter api;

@SessionAttributes

  • 绑定HttpSession中的attribute对象的值

@ModelAttribute

该注解有两个用法,一个是用于方法上,一个是用于参数上;
用于方法上时: 通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;
用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:

  • @SessionAttributes 启用的attribute 对象上;
  • @ModelAttribute 用于方法上时指定的model对象;
  • 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。

HttpPutFormContentFilter

支持PUT方法

@InitBinder

在controller里面配置web数据绑定

1
2
3
4
5
6
7
8
9
10
11
12
@Controller
public class MyFormController {

@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}

// ...
}

最新的Spring 4.2 里面

1
2
3
4
5
6
7
8
9
10
@Controller
public class MyFormController {

@InitBinder
public void initBinder(WebDataBinder binder) {
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
}

// ...
}

@ControllerAdvice

被注解的类可以搭配 @ExceptionHandler, @InitBinder, and @ModelAttribute,全局处理

Resolving views

Spring Doc : Resolving views

Spring’s multipart (file upload) support

Handling exceptions

  • HandlerExceptionResolver
  • @ExceptionHandler

Standard Spring MVC Exceptions

主要内容

jenkins-2.235.3-1.1 安装 使用

更新历史
2020-08-04 增加jenkins的清华镜像设置
2020-11-14 国内镜像源设置
2025-03-22 增加脚本样例

阅读全文 »

和开发比运维,和运维比开发

服务器监控

命令

  • 查看整体空间 (-h 按M单位)

    1
    $ df -h
  • 查看输出当前目录下各个子目录所使用的空间(-h 按M单位), 从大到小排列

    1
    $ du --max-depth=2 -h | sort -rh

排序

1
$ du  --max-depth=1 |sort -rn
  • 手动清空缓存

    1
    2
    $ sync
    $ echo 3 > /proc/sys/vm/drop_caches
  • 查找以前用过的命令
    ctrl + r

  • Netstat
    Netstat 命令用于显示各种网络相关信息,如网络连接,路由表,接口状态 (Interface Statistics),masquerade 连接,多播成员 (Multicast Memberships) 等等。
    Linux netstat命令详解 链接
    程序端口占用情况

    1
    2
    3
    4
    5
    $ netstat –apn 

    $ netstat -anp | grep portno

    $ ps -aux | grep java
  • 抓包 tcpdump / wireshark

  • rsync 增量备份,保持原有属性
    -a
    -z
    -p
    –delete

  • inotify + rsync 实时备份
    inotify 安装

inotifywait
-e 监控事件
-m 持续监控
-r 递归
-q 简化信息

  • ctrl + r 查找历史命令

  • rs 上传

  • waf : web application firewall
    modsecurity

  • Linux下高效数据恢复软件extundelete

  • curl wget lynx
    curl

    1
    2
    3
    4
    $ curl -I ip/domain #查看web服务器类型和版本
    $ wget -C URL #断点续传 -t 重试次数 -T 超时时间
    $ wget --user username --password pass URL #认证
    $ curl -C URL #断点续传

常用技巧

特殊变量

变量 含义
$0 当前脚本的文件名
$n 传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2。
!$ 上个命令最后一个参数
$# 传递给脚本或函数的参数个数。
$* 传递给脚本或函数的所有参数。
$@ 传递给脚本或函数的所有参数。被双引号(“ “)包含时,与 $* 稍有不同,下面将会讲到。
$? 上个命令的退出状态,或函数的返回值。
$$ 当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID。
$! 执行上一个后台程序的PID
$*$@ 都表示传递给函数或脚本的所有参数,不被双引号(“ “)包含时,都以”$1” “$2” … “$n” 的形式输出所有参数。
但是当它们被双引号(“ “)包含时,$* 会将所有的参数作为一个整体,以”$1 $2 … $n”的形式输出所有参数;$@ 会将各个参数分开,以”$1” “$2” … “$n” 的形式输出所有参数。

常用PATTERN:

`^#`:   以#开头
`#$`:   以#结尾
`^$`:   空行

知乎

基础知识

最小存储单位

名称 最小存储单位
硬盘 扇区(512B)
文件系统 block(1K,4K)
RAID chunk (512) mdadm -c
LVM PE (16M 自定义)

调教 kaffeine 播放各类媒体格式

kaffeine 是基于 libxine2, openSUSE 官方提供的 libxine2 缺少一些插件,那用户要怎么安装这些编解码器呢? 我们先说安装 mkv, mp4, wmv, m4v, mov, 3gp, 3g2 等视频文件的编解码器,这些可以很方便的从 packman 安装。核心的包是 libxine2-codecs ,我以 openSUSE 13.2 为例进行讲解:

1
2
3
sudo zypper ar -f http://packman.inode.at/suse/openSUSE_13.2/ packman
sudo zypper update
sudo zypper install libxine2-codecs

安全相关

last
lastb
lastlog
history
/var/log/secure : 登录的ssh公钥签名可以通过 ssh-keygen -l -f xxx.pub 获得 远程日志服务

网络实时流量监测 iftop

单服务器

网络流量监控与分析 Ntop 和 Ntopng

网络性能评估 iperf

rootkit 检测工具

  • chkrootkit
  • RKHunter