kk Blog —— 通用基础


date [-d @int|str] [+%s|"+%F %T"]
netstat -ltunp
sar -n DEV 1

DNS示例

https://gist.github.com/fffaraz/9d9170b57791c28ccda9255b48315168

DNS 示例

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// gcc dns.c -lpthread

#include <stdio.h>  //printf
#include <string.h> //strlen
#include <stdlib.h> //malloc
#include <sys/socket.h> //you know what this is for
#include <arpa/inet.h>  //inet_addr, inet_ntoa, ntohs etc
#include <netinet/in.h>
#include <unistd.h> //getpid
#include <pthread.h>
#include <time.h>

#define T_A   1   //IPv4 address
#define T_NS  2   //Nameserver
#define T_CNAME   5   // canonical name
#define T_SOA 6   /* start of authority zone */
#define T_PTR 12  /* domain name pointer */
#define T_MX  15  //Mail server
#define T_AAAA    28  // IPv6

#define NIPQUAD(addr) ((unsigned char *)addr)[0], ((unsigned char *)addr)[1], ((unsigned char *)addr)[2], ((unsigned char *)addr)[3]

//DNS header structure
struct DNS_HEADER
{
	unsigned short id;    // identification number

	unsigned char rd :1;  // recursion desired
	unsigned char tc :1;  // truncated message
	unsigned char aa :1;  // authoritive answer
	unsigned char opcode :4;  // purpose of message
	unsigned char qr :1;  // query/response flag

	unsigned char rcode :4;   // response code
	unsigned char cd :1;  // checking disabled
	unsigned char ad :1;  // authenticated data
	unsigned char z :1;   // its z! reserved
	unsigned char ra :1;  // recursion available

	unsigned short q_count;   // number of question entries
	unsigned short ans_count; // number of answer entries
	unsigned short auth_count;    // number of authority entries
	unsigned short add_count; // number of resource entries
};

//Constant sized fields of query structure
struct QUESTION
{
	unsigned short qtype;
	unsigned short qclass;
};

//Constant sized fields of the resource record structure
#pragma pack(push, 1)
struct R_DATA
{
	unsigned short type;
	unsigned short _class;
	unsigned int ttl;
	unsigned short data_len;
};
#pragma pack(pop)

//Pointers to resource record contents
struct RES_RECORD
{
	unsigned char *name;
	struct R_DATA *resource;
	unsigned char *rdata;
};

//Structure of a Query
typedef struct
{
	unsigned char *name;
	struct QUESTION *ques;
} QUERY;

// convert www.google.com to 3www6google3com
void ChangetoDnsNameFormat(unsigned char* dns, unsigned char* host)
{
	int lock = 0, i;
	for (i = 0; i <= strlen(host); i ++) {
		if (host[i] == '.' || host[i] == '\0') {
			*dns++ = i - lock;
			for( ; lock < i; lock ++)
				*dns++ = host[lock];
			lock ++;
		}
	}
	*dns++ = '\0';
}

// convert 3www6google3com0 to www.google.com
void changeToHost(unsigned char *dns)
{
	int i = 0, j = 0, p;

	while (i < 90 && dns[i] && i + dns[i] + 1 < 90) {
		p = dns[i];
		i = i + p + 1;
		while (p -- && j < 90) {
			dns[j] = dns[j+1];
			j ++;
		}
		dns[j++] = '.';
	}
	if (j == 0)
		j = 1;
	dns[j-1] = '\0'; //remove the last dot
}

int readName(unsigned char *reader, unsigned char *buffer, unsigned char *to, unsigned char *end)
{
	unsigned char *start = reader;
	unsigned int p = 0, step = 1, offset, count = 0;
	int i, j;

	//read the names in 3www6google3com format

	while (reader < end && *reader != 0) {
		if (*reader >= 0xc0) {
			offset = (*reader)*256 + *(reader+1) - 0xc000; //49152 = 11000000 00000000
			reader = buffer + offset;
			step = 0;
		} else {
			to[p++] = *reader ++;
			count += step;
		}
		if (reader > end)
			goto err;
	}
	to[p] = '\0';
	count += (step == 0) ? 2 : 1;

	if (start + count > end)
		goto err;

	changeToHost(to);

	return count;
err:
	return 1000000;
}

/*
 * sending a packet
 */
void sendPacket(int fd, struct sockaddr_in *dest, unsigned char *host, int query_type)
{
	unsigned char buf[65536], *qname, *reader;
	int i, j;

	struct DNS_HEADER *dns = NULL;
	struct QUESTION *qinfo = NULL;

	//Set the DNS structure to standard queries
	dns = (struct DNS_HEADER *)&buf;

	dns->id = htons(getpid());
	dns->qr = 0; //This is a query
	dns->opcode = 0; //This is a standard query
	dns->aa = 0; //Not Authoritative
	dns->tc = 0; //This message is not truncated
	dns->rd = 1; //Recursion Desired
	dns->ra = 0; //Recursion not available! hey we dont have it (lol)
	dns->z = 0;
	dns->ad = 0;
	dns->cd = 0;
	dns->rcode = 0;
	dns->q_count = htons(1); //we have only 1 question
	dns->ans_count = 0;
	dns->auth_count = 0;
	dns->add_count = 0;

	//point to the query portion
	qname = &buf[sizeof(struct DNS_HEADER)];

	ChangetoDnsNameFormat(qname, host);
	qinfo = (struct QUESTION*)&buf[sizeof(struct DNS_HEADER) + (strlen(qname) + 1)]; //fill it

	qinfo->qtype = htons(query_type); //type of the query, A, MX, CNAME, NS etc
	qinfo->qclass = htons(1); //its internet (lol)

	if (sendto(fd, buf, sizeof(struct DNS_HEADER) + (strlen(qname) + 1) + sizeof(struct QUESTION), 0, (struct sockaddr*)dest, sizeof(*dest)) < 0) {
		perror("sendto failed");
	}
	printf("send Done\n");
	return;
}

int expBuf(char buf[], int len)
{
	unsigned char *end = buf + len;

	struct DNS_HEADER *dns = NULL;
	struct QUESTION *qinfo = NULL;
	struct R_DATA *resource;

	unsigned char *qname, *reader;

	char name[256];
	char rdata[256];
	int i, j;

	if (len < sizeof(struct DNS_HEADER))
		goto err;

	dns = (struct DNS_HEADER*) buf;

	printf("The response contains:\n");
	printf("%d Questions.\n", ntohs(dns->q_count));
	printf("%d Answers.\n", ntohs(dns->ans_count));
	printf("%d Authoritative Servers.\n", ntohs(dns->auth_count));
	printf("%d Additional records.\n\n", ntohs(dns->add_count));
	
	//move ahead of the dns header and the query field
	//reader = &buf[sizeof(struct DNS_HEADER) + (strlen((const char*)qname) + 1) + sizeof(struct QUESTION)];
	reader = &buf[sizeof(struct DNS_HEADER)];

	//Start reading answers
	printf("Questions Records: %d\n", ntohs(dns->q_count));
	for (i = 0; i < ntohs(dns->q_count); i ++) {
		reader += readName(reader, buf, name, end);
		qinfo = (struct QUESTION *)reader;
		reader = reader + sizeof(struct QUESTION);
		if (reader > end)
			goto err;

		printf("Name: %s Type: %d\n", name, ntohs(qinfo->qtype));
	}
	printf("\n");

	printf("Answer Records: %d\n", ntohs(dns->ans_count));
	for (i = 0; i < ntohs(dns->ans_count); i++) {
		reader += readName(reader, buf, name, end);
		resource = (struct R_DATA*)(reader);
		reader = reader + sizeof(struct R_DATA);
		if (reader > end)
			goto err;

		printf("Name: %s Type: %d ", name, ntohs(resource->type));

		if (ntohs(resource->type) == T_A || ntohs(resource->type) == T_AAAA) { //if its an ipv4 address
			if (reader + ntohs(resource->data_len) > end)
				goto err;
			printf("IPv4: %d.%d.%d.%d", NIPQUAD(reader));
			reader = reader + ntohs(resource->data_len);
		} else {
			reader += readName(reader, buf, rdata, end);
			if (reader > end)
				goto err;
			if (ntohs(resource->type) == T_CNAME)
				printf("CNAME: %s", rdata);
		}
		printf("\n");
	}
	printf("\n");

	//read authorities
	printf("Authoritive Records: %d\n", ntohs(dns->auth_count));
	for(i = 0; i < ntohs(dns->auth_count); i++) {
		reader += readName(reader, buf, name, end);
		resource = (struct R_DATA*)(reader);
		reader += sizeof(struct R_DATA);
		if (reader > end)
			goto err;

		reader += readName(reader, buf, rdata, end);
		if (reader > end)
			goto err;

		printf("Name: %s Type: %d ", name, ntohs(resource->type));

		if (ntohs(resource->type) == T_NS) {
			printf("nameserver: %s", rdata);
		}
		printf("\n");
	}
	printf("\n");

	//read additional
	printf("Additional Records: %d\n", ntohs(dns->add_count));
	for(i = 0; i < ntohs(dns->add_count); i++) {
		reader += readName(reader, buf, name, end);
		resource = (struct R_DATA*)(reader);
		reader += sizeof(struct R_DATA);
		if (reader > end)
			goto err;

		printf("Name: %s Type: %d ", name, ntohs(resource->type));

		if (ntohs(resource->type) == T_A || ntohs(resource->type) == T_AAAA) {
			if (reader + ntohs(resource->data_len) > end)
				goto err;
			printf("IPv4: %d.%d.%d.%d", NIPQUAD(reader));
			reader = reader + ntohs(resource->data_len);
		} else {
			reader += readName(reader, buf, rdata, end);
			if (reader > end)
				goto err;
		}
		printf("\n");
	}
	printf("\n\n");
	return 0;
err:
	printf("\n\n");
	return -1;
}

void *recvPacket(void *arg)
{
	int fd = *((int *)arg);
	struct sockaddr_in dest;
	unsigned char buf[65536];
	int s, len;

	while (1) {
		//Receive the answer
		s = sizeof(dest);
		if ((len = recvfrom(fd, buf, 65536, 0, (struct sockaddr*)&dest, (socklen_t*)&s)) < 0) {
			perror("recvfrom failed");
		}
		printf("recv Done. len=%d\n", len);
		if (expBuf(buf, len)) {
			printf("exp err\n");
		}
	}
}

/*
 * Get the DNS servers from /etc/resolv.conf file on Linux
 */
void get_dns_servers(char dns_servers[])
{
	FILE *fp;
	char line[200], *p;
	if ((fp = fopen("/etc/resolv.conf", "r")) == NULL) {
		printf("Failed opening /etc/resolv.conf file \n");
	}

	while (fgets(line, 200, fp)) {
		if (line[0] == '#') {
			continue;
		}
		if (strncmp(line, "nameserver", 10) == 0) {
			p = strtok(line, " ");
			p = strtok(NULL, " ");

			//p now is the dns ip :)
			//????
		}
	}

	strcpy(dns_servers, "127.0.1.1");
}

int main(int argc, char *argv[])
{
	int fd;
	struct sockaddr_in dest;
	unsigned char hostname[100];
	pthread_t tid;

	char dns_servers[100];

	//Get the DNS servers from the resolv.conf file
	get_dns_servers(dns_servers);

	dest.sin_family = AF_INET;
	dest.sin_port = htons(53);
	dest.sin_addr.s_addr = inet_addr(dns_servers);

	fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

	if (pthread_create(&tid, NULL, recvPacket, (void *)&fd)) {
		printf("pthread err\n");
		exit(-1);
	}

	while (1) {
		printf("Enter Hostname to Lookup: ");
		scanf("%s", hostname);
		sendPacket(fd, &dest, hostname, T_A);
		usleep(500000);
	}

	pthread_join(tid, NULL);
	return 0;
}

API购买CVM

CVM 添加辅助网卡并绑定多 IP

https://cloud.tencent.com/document/product/1199/44153

1
2
3
4
5
6
7
8
9
10
11
12
$ vim /etc/network/interfaces   # 增加如下

auto eth1
iface eth1 inet static
address   172.19.0.13
netmask 172.19.15.255
gateway 172.19.0.1

$ ifconfig eth1 172.19.0.13/20

$ find /proc/sys/net/ -name rp_filter -exec sh -c "echo 0 > {} " \;
$ find /proc/sys/net/ -name rp_filter -exec cat {} \;

python

代理设置 export http_proxy=http://

export https_proxy=http://

SDK

手动安装

https://github.com/TencentCloud/tencentcloud-sdk-python

git clone https://github.com/TencentCloud/tencentcloud-sdk-python.git

python setup.py install

pip 安装

sudo apt-get install python-pip

pip install tencentcloud-sdk-python

请注意,如果同时有 python2 和 python3 环境, python3 环境需要使用 pip3 命令安装。

密钥

https://console.cloud.tencent.com/cam/capi

export TENCENTCLOUD_SECRET_ID=xx

export TENCENTCLOUD_SECRET_KEY=xx

v2.0

方便被其他程序调用,例如网页实现购买

cred = credential.Credential(“your_id”, “your_key”) 中替换自己的ID,KEY

用法: python CVM.py hk 1 会先查寻,如果个数>=n就不购买

查看结果: cat show.log API返回时一般还没分配IP,多调几次 python CVM.py hk 0 就有结果了

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# -*- coding: utf-8 -*-
import os
import time
import logging
import sys

handler = logging.FileHandler("all.log") #, encoding='utf-8')
handler.setFormatter(logging.Formatter(fmt='%(asctime)s %(process)d %(levelname)s %(message)s'))
log = logging.getLogger("QQ")
log.addHandler(handler)
log.setLevel(logging.INFO)

handler = logging.FileHandler("show.log", mode='w')
handler.setFormatter(logging.Formatter(fmt='%(asctime)s %(message)s'))
log2 = logging.getLogger("QQQ")
log2.addHandler(handler)
log2.setLevel(logging.INFO)

RZ = {
        "hk" : {
            "Region" : "ap-hongkong",
            "Zone" : ["ap-hongkong-2", "ap-hongkong-1"],
            "ImageId" : "img-3tdtc58k",
            "InstanceType" : ["S2.SMALL1", ],
            "ActionTime" : [1, 2, 3]
            },
        "gz" : {
            "Region" : "ap-guangzhou",
            "Zone" : ["ap-guangzhou-3", "ap-guangzhou-4"],
            "ImageId" : "img-822xs3s2",
            "InstanceType" : ["S2.SMALL1", ],
            "ActionTime" : [1, 2, 3]
            }
        }

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
from tencentcloud.cvm.v20170312 import cvm_client, models

# 导入可选配置类
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile

def del_ins(client, ins):
    req = models.TerminateInstancesRequest()

    params = '''{
        "InstanceIds" : [
            "%s"
        ]
    }''' % (ins)
    req.from_json_string(params)

    resp = client.TerminateInstances(req)
    #print(resp.to_json_string(indent=2))
    log.error("%s" % req)
    log.error("%s" % resp)


def buy_ins(client, rz):
    req = models.RunInstancesRequest()
    endtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()+3600*RZ[rz]["ActionTime"][0]-100))

    params = '''{
        "Placement" : {
            "Zone" : "%s"
        },
        "ImageId" : "%s",
        "InstanceType" : "%s",
        "InstanceName" : "%s",
        "InstanceChargeType" : "POSTPAID_BY_HOUR",
        "InternetAccessible" : {
            "InternetChargeType" : "TRAFFIC_POSTPAID_BY_HOUR",
            "InternetMaxBandwidthOut" : 10
        },
        "LoginSettings" : {
            "Password" : "Dis@init3"
        },
        "EnhancedService" : {
            "SecurityService" : {
                "Enabled" : false
            },
            "MonitorService" : {
                "Enabled" : false
            }
        },
        "ActionTimer" : {
            "Externals" : {
            },
            "TimerAction" : "TerminateInstances",
            "ActionTime" : "%s"
        }
    }''' % (RZ[rz]["Zone"][0], RZ[rz]["ImageId"], RZ[rz]["InstanceType"][0], endtime, endtime)

    req.from_json_string(params)

    resp = client.RunInstances(req)
    #print(resp.to_json_string(indent=2))
    log.warning("%s" % req)
    log.warning("%s" % resp)


    count = len(resp.InstanceIdSet)
    log2.info("BUY %s count=%d" % (req.Placement.Zone, count))
    return count


def show_ins(client, rz):
    req = models.DescribeInstancesRequest()

    respFilter = models.Filter()
    respFilter.Name = "zone"
    respFilter.Values = RZ[rz]["Zone"]
    req.Filters = [respFilter]

    resp = client.DescribeInstances(req)
    #print(resp.to_json_string(indent=2))
    log.info("%s" % req)
    log.info("%s" % resp)

    for ins in resp.InstanceSet:
        if ins.PublicIpAddresses and len(ins.PublicIpAddresses) > 0:
            log2.info("%s </br>%s %sMb/s %s </br></br>" % (ins.PublicIpAddresses[0], ins.InstanceName, ins.InternetAccessible.InternetMaxBandwidthOut, ins.InstanceId))
        else:
            log2.info("%s </br>%s %sMb/s %s </br></br>" % ("null", ins.InstanceName, ins.InternetAccessible.InternetMaxBandwidthOut, ins.InstanceId))
    log2.info("SHOW zone=%s count=%d </br>" % (RZ[rz]["Zone"], resp.TotalCount))
    return resp.TotalCount

try:
    # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
    #cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"), os.environ.get("TENCENTCLOUD_SECRET_KEY"))
    # TODO
    cred = credential.Credential("your_id", "your_key")

    # 实例化一个http选项,可选的,没有特殊需求可以跳过。
    httpProfile = HttpProfile()
    httpProfile.reqMethod = "GET"  # post请求(默认为post请求)
    httpProfile.reqTimeout = 30    # 请求超时时间,单位为秒(默认60秒)
    httpProfile.endpoint = "cvm.ap-guangzhou.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

    # 实例化一个client选项,可选的,没有特殊需求可以跳过。
    clientProfile = ClientProfile()
    clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
    clientProfile.language = "en-US"
    clientProfile.httpProfile = httpProfile

    rz = "hk"
    count = 0
    if len(sys.argv) >= 2:
        rz = sys.argv[1]

    if len(sys.argv) >= 3:
        count = int(sys.argv[2])

    if rz not in RZ:
        quit()

    # 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的。
    client = cvm_client.CvmClient(cred, RZ[rz]["Region"], clientProfile)

    if show_ins(client, rz) < count:
        if buy_ins(client, rz) > 0:
            show_ins(client, rz)

    #del_ins(client, "")

except TencentCloudSDKException as err:
    print(err)

v1.0

查询

来自SDK样例

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
56
57
58
59
60
61
62
# -*- coding: utf-8 -*-
import os

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
from tencentcloud.cvm.v20170312 import cvm_client, models

# 导入可选配置类
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
try:
    # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
    cred = credential.Credential(
        os.environ.get("TENCENTCLOUD_SECRET_ID"),
        os.environ.get("TENCENTCLOUD_SECRET_KEY"))

    # 实例化一个http选项,可选的,没有特殊需求可以跳过。
    httpProfile = HttpProfile()
    httpProfile.reqMethod = "GET"  # post请求(默认为post请求)
    httpProfile.reqTimeout = 30    # 请求超时时间,单位为秒(默认60秒)
    httpProfile.endpoint = "cvm.ap-guangzhou.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

    # 实例化一个client选项,可选的,没有特殊需求可以跳过。
    clientProfile = ClientProfile()
    clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
    clientProfile.language = "en-US"
    clientProfile.httpProfile = httpProfile

    # 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的。
    client = cvm_client.CvmClient(cred, "ap-hongkong", clientProfile)

    # 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。
    req = models.DescribeInstancesRequest()

    # 填充请求参数,这里request对象的成员变量即对应接口的入参。
    # 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义。
    respFilter = models.Filter()  # 创建Filter对象, 以zone的维度来查询cvm实例。
    respFilter.Name = "zone"
    respFilter.Values = ["ap-hongkong-1", "ap-hongkong-2"]
    req.Filters = [respFilter]  # Filters 是成员为Filter对象的列表

    # 这里还支持以标准json格式的string来赋值请求参数的方式。下面的代码跟上面的参数赋值是等效的。
    params = '''{
        "Filters": [
            {
                "Name": "zone",
                "Values": ["ap-hongkong-1", "ap-hongkong-2"]
            }
        ]
    }'''
    req.from_json_string(params)

    # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的。
    # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。
    resp = client.DescribeInstances(req)

    # 输出json格式的字符串回包
    print(resp.to_json_string(indent=2))

except TencentCloudSDKException as err:
    print(err)

购买 香港-1core-1GB-5Mbps-1小时后销毁

ImageId 换个公共的 或 自己制作一个

https://console.cloud.tencent.com/cvm/image?rid=5&imageType=PUBLIC_IMAGE

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# -*- coding: utf-8 -*-
import os
import time

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
from tencentcloud.cvm.v20170312 import cvm_client, models

# 导入可选配置类
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
try:
    # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
    cred = credential.Credential(
        os.environ.get("TENCENTCLOUD_SECRET_ID"),
        os.environ.get("TENCENTCLOUD_SECRET_KEY"))

    # 实例化一个http选项,可选的,没有特殊需求可以跳过。
    httpProfile = HttpProfile()
    httpProfile.reqMethod = "GET"  # post请求(默认为post请求)
    httpProfile.reqTimeout = 30    # 请求超时时间,单位为秒(默认60秒)
    httpProfile.endpoint = "cvm.ap-guangzhou.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

    # 实例化一个client选项,可选的,没有特殊需求可以跳过。
    clientProfile = ClientProfile()
    clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
    clientProfile.language = "en-US"
    clientProfile.httpProfile = httpProfile

    # 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的。
    client = cvm_client.CvmClient(cred, "ap-hongkong", clientProfile)

    # 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。
    req = models.RunInstancesRequest()

    # 填充请求参数,这里request对象的成员变量即对应接口的入参。
    # 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义。

    # 这里还支持以标准json格式的string来赋值请求参数的方式。下面的代码跟上面的参数赋值是等效的。
    params = '''{
        "Region" : "ap-hongkong",
        "Placement" : {
            "Zone" : "ap-hongkong-2"
        },
        "ImageId" : "img-7b63u5v2",
        "InstanceChargeType" : "POSTPAID_BY_HOUR",
        "InstanceType" : "S2.SMALL1",
        "InternetAccessible" : {
            "InternetChargeType" : "TRAFFIC_POSTPAID_BY_HOUR",
            "InternetMaxBandwidthOut" : 5
        },
        "LoginSettings" : {
            "Password" : "QAZwsx123"
        },
        "EnhancedService" : {
            "SecurityService" : {
                "Enabled" : false
            },
            "MonitorService" : {
                "Enabled" : false
            }
        },
        "ActionTimer" : {
            "Externals" : {
            },
            "TimerAction" : "TerminateInstances",
            "ActionTime" : "%s"
        }
    }''' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()+3300)))

    req.from_json_string(params)

    #print(req)

    # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的。
    # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。
    resp = client.RunInstances(req)

    # 输出json格式的字符串回包
    print(resp.to_json_string(indent=2))

except TencentCloudSDKException as err:
    print(err)

退还CVM

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
# -*- coding: utf-8 -*-
import os

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
from tencentcloud.cvm.v20170312 import cvm_client, models

# 导入可选配置类
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
try:
    # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
    cred = credential.Credential(
        os.environ.get("TENCENTCLOUD_SECRET_ID"),
        os.environ.get("TENCENTCLOUD_SECRET_KEY"))

    # 实例化一个http选项,可选的,没有特殊需求可以跳过。
    httpProfile = HttpProfile()
    httpProfile.reqMethod = "GET"  # post请求(默认为post请求)
    httpProfile.reqTimeout = 30    # 请求超时时间,单位为秒(默认60秒)
    httpProfile.endpoint = "cvm.ap-guangzhou.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

    # 实例化一个client选项,可选的,没有特殊需求可以跳过。
    clientProfile = ClientProfile()
    clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
    clientProfile.language = "en-US"
    clientProfile.httpProfile = httpProfile

    # 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的。
    client = cvm_client.CvmClient(cred, "ap-hongkong", clientProfile)

    # 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。
    req = models.TerminateInstancesRequest()

    # 填充请求参数,这里request对象的成员变量即对应接口的入参。
    params = '''{
        "InstanceIds" : [
            "ins-6y6yfpdw"
        ]
    }'''
    req.from_json_string(params)

    #print(req)
    # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的。
    # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。
    resp = client.TerminateInstances(req)

    # 输出json格式的字符串回包
    print(resp.to_json_string(indent=2))

except TencentCloudSDKException as err:
    print(err)

phpSDK 已经更新,以下需要改

php

看 vendor/GuzzleHttp/Client.php 中 configureDefaults ,代理需要设置

export HTTP_PROXY=tcp://xx

export HTTPS_PROXY=tcp://xx

或者安装 php-curl 就可以改用

export http_proxy=http://

export https_proxy=http://

SDK

https://github.com/TencentCloud/tencentcloud-sdk-php

git clone https://github.com/TencentCloud/tencentcloud-sdk-php.git

密钥

https://console.cloud.tencent.com/cam/capi

export TENCENTCLOUD_SECRET_ID=xx

export TENCENTCLOUD_SECRET_KEY=xx

查询

来自SDK样例

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
56
57
58
59
60
61
62
63
<?php
require_once '../../../TCloudAutoLoader.php';
// 导入对应产品模块的client
use TencentCloud\Cvm\V20170312\CvmClient;
// 导入要请求接口对应的Request类
use TencentCloud\Cvm\V20170312\Models\DescribeInstancesRequest;
use TencentCloud\Cvm\V20170312\Models\Filter;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
// 导入可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;

try {
    // 实例化一个证书对象,入参需要传入腾讯云账户secretId,secretKey
    //$cred = new Credential("secretId", "secretKey");
    $cred = new Credential(getenv("TENCENTCLOUD_SECRET_ID"), getenv("TENCENTCLOUD_SECRET_KEY"));

    // 实例化一个http选项,可选的,没有特殊需求可以跳过
    $httpProfile = new HttpProfile();
    $httpProfile->setReqMethod("GET");  // post请求(默认为post请求)
    $httpProfile->setReqTimeout(30);    // 请求超时时间,单位为秒(默认60秒)
    $httpProfile->setEndpoint("cvm.ap-guangzhou.tencentcloudapi.com");  // 指定接入地域域名(默认就近接入)

    // 实例化一个client选项,可选的,没有特殊需求可以跳过
    $clientProfile = new ClientProfile();
    $clientProfile->setSignMethod("TC3-HMAC-SHA256");  // 指定签名算法(默认为HmacSHA256)
    $clientProfile->setHttpProfile($httpProfile);

    // 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的
    $client = new CvmClient($cred, "ap-hongkong", $clientProfile);

    // 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。
    $req = new DescribeInstancesRequest();

    // 填充请求参数,这里request对象的成员变量即对应接口的入参
    // 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
    $respFilter = new Filter();  // 创建Filter对象, 以zone的维度来查询cvm实例
    $respFilter->Name = "zone";
    $respFilter->Values = ["ap-hongkong-1", "ap-hongkong-2"];
    $req->Filters = [$respFilter];  // Filters 是成员为Filter对象的列表

    // 这里还支持以标准json格式的string来赋值请求参数的方式。下面的代码跟上面的参数赋值是等效的
    $params = [
        "Filters" => [
            [
                "Name" => "zone",
                "Values" => ["ap-hongkong-1", "ap-hongkong-2"]
            ]
        ]
    ];
    $req->fromJsonString(json_encode($params));

    // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的
    // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应
    $resp = $client->DescribeInstances($req);

    // 输出json格式的字符串回包
    print_r($resp->toJsonString());
}
catch(TencentCloudSDKException $e) {
    echo $e;
}

购买 香港-1core-1GB-5Mbps-1小时后销毁

ImageId 换个公共的 或 自己制作一个

https://console.cloud.tencent.com/cvm/image?rid=5&imageType=PUBLIC_IMAGE

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
require_once '../../../TCloudAutoLoader.php';
// 导入对应产品模块的client
use TencentCloud\Cvm\V20170312\CvmClient;
// 导入要请求接口对应的Request类
use TencentCloud\Cvm\V20170312\Models\RunInstancesRequest;
use TencentCloud\Cvm\V20170312\Models\Filter;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
// 导入可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;

try {
    // 实例化一个证书对象,入参需要传入腾讯云账户secretId,secretKey
    //$cred = new Credential("secretId", "secretKey");
    $cred = new Credential(getenv("TENCENTCLOUD_SECRET_ID"), getenv("TENCENTCLOUD_SECRET_KEY"));

    // 实例化一个http选项,可选的,没有特殊需求可以跳过
    $httpProfile = new HttpProfile();
    $httpProfile->setReqMethod("GET");  // post请求(默认为post请求)
    $httpProfile->setReqTimeout(30);    // 请求超时时间,单位为秒(默认60秒)
    $httpProfile->setEndpoint("cvm.ap-guangzhou.tencentcloudapi.com");  // 指定接入地域域名(默认就近接入)

    // 实例化一个client选项,可选的,没有特殊需求可以跳过
    $clientProfile = new ClientProfile();
    $clientProfile->setSignMethod("TC3-HMAC-SHA256");  // 指定签名算法(默认为HmacSHA256)
    $clientProfile->setHttpProfile($httpProfile);

    // 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的
    $client = new CvmClient($cred, "ap-hongkong", $clientProfile);

    // 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。
    $req = new RunInstancesRequest();

    // 填充请求参数,这里request对象的成员变量即对应接口的入参
    // 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
    // 这里还支持以标准json格式的string来赋值请求参数的方式。下面的代码跟上面的参数赋值是等效的
    $params = [
        "Region" => "ap-hongkong",
        "Placement" => [
            "Zone" => "ap-hongkong-2"
        ],
        "ImageId" => "img-7b63u5v2",
        "InstanceChargeType" => "POSTPAID_BY_HOUR",
        "InstanceType" => "S2.SMALL1",
        "InternetAccessible" => [
            "InternetChargeType" => "TRAFFIC_POSTPAID_BY_HOUR",
            "InternetMaxBandwidthOut" => 5
        ],
        "LoginSettings" => [
            "Password" => "QAZwsx123"
        ],
        "EnhancedService" => [
            "SecurityService" => [
                "Enabled" => false
            ],
            "MonitorService" => [
                "Enabled" => false
            ]
        ],
        "ActionTimer" => [
            "Externals" => [
            ],
            "TimerAction" => "TerminateInstances",
            "ActionTime" => date('Y-m-d H:i:s', time()+3300),
        ]
    ];
    $req->fromJsonString(json_encode($params));

    #var_dump($req);
    // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的
    // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应
    $resp = $client->RunInstances($req);

    // 输出json格式的字符串回包
    print_r($resp->toJsonString());
}
catch(TencentCloudSDKException $e) {
    echo $e;
}

退还CVM

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
<?php
require_once '../../../TCloudAutoLoader.php';
// 导入对应产品模块的client
use TencentCloud\Cvm\V20170312\CvmClient;
// 导入要请求接口对应的Request类
use TencentCloud\Cvm\V20170312\Models\TerminateInstancesRequest;
use TencentCloud\Cvm\V20170312\Models\Filter;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
// 导入可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;

try {
    // 实例化一个证书对象,入参需要传入腾讯云账户secretId,secretKey
    //$cred = new Credential("secretId", "secretKey");
    $cred = new Credential(getenv("TENCENTCLOUD_SECRET_ID"), getenv("TENCENTCLOUD_SECRET_KEY"));

    // 实例化一个http选项,可选的,没有特殊需求可以跳过
    $httpProfile = new HttpProfile();
    $httpProfile->setReqMethod("GET");  // post请求(默认为post请求)
    $httpProfile->setReqTimeout(30);    // 请求超时时间,单位为秒(默认60秒)
    $httpProfile->setEndpoint("cvm.ap-guangzhou.tencentcloudapi.com");  // 指定接入地域域名(默认就近接入)

    // 实例化一个client选项,可选的,没有特殊需求可以跳过
    $clientProfile = new ClientProfile();
    $clientProfile->setSignMethod("TC3-HMAC-SHA256");  // 指定签名算法(默认为HmacSHA256)
    $clientProfile->setHttpProfile($httpProfile);

    // 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的
    $client = new CvmClient($cred, "ap-hongkong", $clientProfile);

    // 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。
    $req = new TerminateInstancesRequest();

    // 填充请求参数,这里request对象的成员变量即对应接口的入参
    // 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
    // 这里还支持以标准json格式的string来赋值请求参数的方式。下面的代码跟上面的参数赋值是等效的
    $params = [
        "InstanceIds" => [
            "ins-1rfi3vms"
        ]
    ];
    $req->fromJsonString(json_encode($params));

    // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的
    // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应
    $resp = $client->TerminateInstances($req);

    // 输出json格式的字符串回包
    print_r($resp->toJsonString());
}
catch(TencentCloudSDKException $e) {
    echo $e;
}

ubuntu crash

https://www.jianshu.com/p/3c92647140f7

https://help.ubuntu.com/lts/serverguide/kernel-crash-dump.html

自己编译的内核会OOM,需要增大内存

If the dump does not work due to OOM (Out Of Memory) error, then try increasing the amount of reserved memory by editing

/etc/default/grub.d/kdump-tools.cfg

1
GRUB_CMDLINE_LINUX_DEFAULT="$GRUB_CMDLINE_LINUX_DEFAULT crashkernel=384M-:256M"

run sudo update-grub and then reboot afterwards, and then test again.


安装

1
sudo apt-get install linux-crashdump

重启机器

需要启动下面的服务

1
2
3
4
5
$ service --status-all | grep ' k'
[ + ] kdump-tools
[ + ] kerneloops
[ + ] kexec
[ + ] kexec-load

查看kdump的状态

1
2
3
4
5
6
7
8
9
10
$ kdump-config show
DUMP_MODE:        kdump
USE_KDUMP:        1
KDUMP_SYSCTL:     kernel.panic_on_oops=1
KDUMP_COREDIR:    /var/crash
crashkernel addr: 0x21000000
   /var/lib/kdump/vmlinuz: symbolic link to /boot/vmlinuz-4.15.18
kdump initrd: 
   /var/lib/kdump/initrd.img: symbolic link to /var/lib/kdump/initrd.img-4.15.18
current state:    ready to kdump

验证

1
2
echo 1 > /proc/sys/kernel/sysrq
echo c > /proc/sysrq-trigger