dc-cmnutils 0.0.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dc/cmnutils/basicdata/convert.py +192 -0
- dc/cmnutils/basicdata/convert_basic.py +393 -0
- dc/cmnutils/basicdata/data.py +588 -0
- dc/cmnutils/basicdata/json.py +94 -0
- dc/cmnutils/basicdata/object.py +814 -0
- dc/cmnutils/collection/collection.py +757 -0
- dc/cmnutils/database/database_access.py +213 -0
- dc/cmnutils/database/database_accessor.py +287 -0
- dc/cmnutils/database/db_operater.py +283 -0
- dc/cmnutils/database/dbutil.py +389 -0
- dc/cmnutils/io/file/cfg/config.py +262 -0
- dc/cmnutils/io/file/file.py +212 -0
- dc/cmnutils/io/file/file_utils.py +605 -0
- dc/cmnutils/io/log/log.py +43 -0
- dc/cmnutils/io/log/log_utils.py +50 -0
- dc/cmnutils/net/email.py +185 -0
- dc/cmnutils/net/http.py +468 -0
- dc/cmnutils/net/net.py +252 -0
- dc/cmnutils/sys/env/linuxenv.py +384 -0
- dc/cmnutils/sys/env/windowsenv.py +235 -0
- dc/cmnutils/sys/envutil.py +442 -0
- dc/cmnutils/sys/processutil.py +447 -0
- dc/cmnutils/sys/sys.py +640 -0
- dc/cmnutils/sys/sys_utils.py +580 -0
- dc/cmnutils/sys/threadutil.py +315 -0
- dc_cmnutils-0.0.3.dist-info/METADATA +34 -0
- dc_cmnutils-0.0.3.dist-info/RECORD +30 -0
- dc_cmnutils-0.0.3.dist-info/WHEEL +5 -0
- dc_cmnutils-0.0.3.dist-info/licenses/LICENSE.TXT +19 -0
- dc_cmnutils-0.0.3.dist-info/top_level.txt +1 -0
dc/cmnutils/net/email.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import smtplib
|
|
2
|
+
import ssl
|
|
3
|
+
from email.mime.text import MIMEText
|
|
4
|
+
from email.mime.multipart import MIMEMultipart
|
|
5
|
+
from email.mime.application import MIMEApplication
|
|
6
|
+
from email.mime.image import MIMEImage
|
|
7
|
+
from email.utils import formatdate
|
|
8
|
+
from email.header import Header
|
|
9
|
+
import os
|
|
10
|
+
from typing import List, Union, Optional
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class EmailUtil:
|
|
14
|
+
"""邮件工具类,封装常用邮件发送功能"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, smtp_server: str, smtp_port: int,
|
|
17
|
+
username: str, password: str,
|
|
18
|
+
use_ssl: bool = True, use_tls: bool = False):
|
|
19
|
+
"""
|
|
20
|
+
初始化邮件工具
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
smtp_server: SMTP服务器地址
|
|
24
|
+
smtp_port: SMTP服务器端口
|
|
25
|
+
username: 发件人邮箱
|
|
26
|
+
password: 邮箱密码或授权码
|
|
27
|
+
use_ssl: 是否使用SSL加密连接
|
|
28
|
+
use_tls: 是否使用TLS加密连接
|
|
29
|
+
"""
|
|
30
|
+
self.smtp_server = smtp_server
|
|
31
|
+
self.smtp_port = smtp_port
|
|
32
|
+
self.username = username
|
|
33
|
+
self.password = password
|
|
34
|
+
self.use_ssl = use_ssl
|
|
35
|
+
self.use_tls = use_tls
|
|
36
|
+
self.connection = None
|
|
37
|
+
|
|
38
|
+
def connect(self) -> bool:
|
|
39
|
+
"""建立与SMTP服务器的连接"""
|
|
40
|
+
try:
|
|
41
|
+
if self.use_ssl:
|
|
42
|
+
context = ssl.create_default_context()
|
|
43
|
+
self.connection = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port, context=context)
|
|
44
|
+
else:
|
|
45
|
+
self.connection = smtplib.SMTP(self.smtp_server, self.smtp_port)
|
|
46
|
+
|
|
47
|
+
if self.use_tls:
|
|
48
|
+
self.connection.starttls()
|
|
49
|
+
|
|
50
|
+
self.connection.login(self.username, self.password)
|
|
51
|
+
return True
|
|
52
|
+
except Exception as e:
|
|
53
|
+
print(f"连接SMTP服务器失败: {e}")
|
|
54
|
+
return False
|
|
55
|
+
|
|
56
|
+
def disconnect(self):
|
|
57
|
+
"""断开与SMTP服务器的连接"""
|
|
58
|
+
if self.connection:
|
|
59
|
+
try:
|
|
60
|
+
self.connection.quit()
|
|
61
|
+
except:
|
|
62
|
+
self.connection.close()
|
|
63
|
+
finally:
|
|
64
|
+
self.connection = None
|
|
65
|
+
|
|
66
|
+
def send_email(self, to_addrs: Union[str, List[str]], subject: str,
|
|
67
|
+
content: str, content_type: str = "plain",
|
|
68
|
+
cc_addrs: Optional[Union[str, List[str]]] = None,
|
|
69
|
+
bcc_addrs: Optional[Union[str, List[str]]] = None,
|
|
70
|
+
attachments: Optional[List[str]] = None) -> bool:
|
|
71
|
+
"""
|
|
72
|
+
发送邮件
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
to_addrs: 收件人地址,可以是字符串或列表
|
|
76
|
+
subject: 邮件主题
|
|
77
|
+
content: 邮件内容
|
|
78
|
+
content_type: 内容类型,'plain' 或 'html'
|
|
79
|
+
cc_addrs: 抄送地址,可以是字符串或列表
|
|
80
|
+
bcc_addrs: 密送地址,可以是字符串或列表
|
|
81
|
+
attachments: 附件路径列表
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
bool: 发送是否成功
|
|
85
|
+
"""
|
|
86
|
+
# 确保收件人、抄送、密送是列表形式
|
|
87
|
+
if isinstance(to_addrs, str):
|
|
88
|
+
to_addrs = [to_addrs]
|
|
89
|
+
if isinstance(cc_addrs, str):
|
|
90
|
+
cc_addrs = [cc_addrs]
|
|
91
|
+
if isinstance(bcc_addrs, str):
|
|
92
|
+
bcc_addrs = [bcc_addrs]
|
|
93
|
+
|
|
94
|
+
# 创建邮件
|
|
95
|
+
msg = MIMEMultipart()
|
|
96
|
+
msg['From'] = self.username
|
|
97
|
+
msg['To'] = ', '.join(to_addrs)
|
|
98
|
+
msg['Subject'] = Header(subject, 'utf-8')
|
|
99
|
+
msg['Date'] = formatdate(localtime=True)
|
|
100
|
+
|
|
101
|
+
if cc_addrs:
|
|
102
|
+
msg['Cc'] = ', '.join(cc_addrs)
|
|
103
|
+
if bcc_addrs:
|
|
104
|
+
msg['Bcc'] = ', '.join(bcc_addrs)
|
|
105
|
+
|
|
106
|
+
# 添加邮件正文
|
|
107
|
+
msg.attach(MIMEText(content, content_type, 'utf-8'))
|
|
108
|
+
|
|
109
|
+
# 添加附件
|
|
110
|
+
if attachments:
|
|
111
|
+
for attachment_path in attachments:
|
|
112
|
+
if not os.path.isfile(attachment_path):
|
|
113
|
+
print(f"附件不存在: {attachment_path}")
|
|
114
|
+
continue
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
with open(attachment_path, 'rb') as f:
|
|
118
|
+
file_data = f.read()
|
|
119
|
+
file_name = os.path.basename(attachment_path)
|
|
120
|
+
|
|
121
|
+
# 根据文件类型创建不同的MIME对象
|
|
122
|
+
if attachment_path.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
|
|
123
|
+
attachment = MIMEImage(file_data, name=file_name)
|
|
124
|
+
else:
|
|
125
|
+
attachment = MIMEApplication(file_data, Name=file_name)
|
|
126
|
+
|
|
127
|
+
attachment['Content-Disposition'] = f'attachment; filename="{file_name}"'
|
|
128
|
+
msg.attach(attachment)
|
|
129
|
+
except Exception as e:
|
|
130
|
+
print(f"添加附件失败 {attachment_path}: {e}")
|
|
131
|
+
continue
|
|
132
|
+
|
|
133
|
+
# 连接服务器并发送邮件
|
|
134
|
+
if not self.connect():
|
|
135
|
+
return False
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
# 所有收件人
|
|
139
|
+
all_recipients = to_addrs.copy()
|
|
140
|
+
if cc_addrs:
|
|
141
|
+
all_recipients.extend(cc_addrs)
|
|
142
|
+
if bcc_addrs:
|
|
143
|
+
all_recipients.extend(bcc_addrs)
|
|
144
|
+
|
|
145
|
+
self.connection.sendmail(self.username, all_recipients, msg.as_string())
|
|
146
|
+
print("邮件发送成功!")
|
|
147
|
+
return True
|
|
148
|
+
except Exception as e:
|
|
149
|
+
print(f"邮件发送失败: {e}")
|
|
150
|
+
return False
|
|
151
|
+
finally:
|
|
152
|
+
self.disconnect()
|
|
153
|
+
|
|
154
|
+
def send_text_email(self, to_addrs: Union[str, List[str]], subject: str,
|
|
155
|
+
text_content: str, **kwargs) -> bool:
|
|
156
|
+
"""
|
|
157
|
+
发送纯文本邮件
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
to_addrs: 收件人地址
|
|
161
|
+
subject: 邮件主题
|
|
162
|
+
text_content: 纯文本内容
|
|
163
|
+
**kwargs: 其他参数,如cc_addrs, bcc_addrs, attachments
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
bool: 发送是否成功
|
|
167
|
+
"""
|
|
168
|
+
return self.send_email(to_addrs, subject, text_content, "plain", **kwargs)
|
|
169
|
+
|
|
170
|
+
def send_html_email(self, to_addrs: Union[str, List[str]], subject: str,
|
|
171
|
+
html_content: str, **kwargs) -> bool:
|
|
172
|
+
"""
|
|
173
|
+
发送HTML邮件
|
|
174
|
+
|
|
175
|
+
Args:
|
|
176
|
+
to_addrs: 收件人地址
|
|
177
|
+
subject: 邮件主题
|
|
178
|
+
html_content: HTML内容
|
|
179
|
+
**kwargs: 其他参数,如cc_addrs, bcc_addrs, attachments
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
bool: 发送是否成功
|
|
183
|
+
"""
|
|
184
|
+
return self.send_email(to_addrs, subject, html_content, "html", **kwargs)
|
|
185
|
+
|
dc/cmnutils/net/http.py
ADDED
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
"""网络操作帮助类
|
|
2
|
+
|
|
3
|
+
提供 HTTP 请求、URL 处理、网络状态检测等常用功能封装。
|
|
4
|
+
所有方法均为静态方法,线程安全,适用于多线程环境。
|
|
5
|
+
"""
|
|
6
|
+
import urllib.request
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import socket
|
|
10
|
+
import ssl
|
|
11
|
+
from typing import Any, Dict, Tuple
|
|
12
|
+
|
|
13
|
+
from dc.cmnutils.io.file.file_utils import FileUtils
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# from coreutils.io.file.file_utils import FileUtils
|
|
17
|
+
|
|
18
|
+
class HttpUtils:
|
|
19
|
+
"""网络操作帮助类"""
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
def get(url: str, params: Dict[str, str] = None, headers: Dict[str, str] = None,
|
|
23
|
+
timeout: int = 30, verify_ssl: bool = True) -> Tuple[int, str]:
|
|
24
|
+
"""发送 HTTP GET 请求
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
url: 请求地址
|
|
28
|
+
params: 请求参数字典
|
|
29
|
+
headers: 请求头字典
|
|
30
|
+
timeout: 超时时间(秒),默认为 30
|
|
31
|
+
verify_ssl: 是否验证 SSL 证书,默认为 True
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
Tuple[int, str]: (状态码, 响应内容)
|
|
35
|
+
"""
|
|
36
|
+
if not url or not isinstance(url, str):
|
|
37
|
+
return (0, "")
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
if params:
|
|
41
|
+
query_string = urllib.parse.urlencode(params)
|
|
42
|
+
if '?' in url:
|
|
43
|
+
url += '&' + query_string
|
|
44
|
+
else:
|
|
45
|
+
url += '?' + query_string
|
|
46
|
+
|
|
47
|
+
req = urllib.request.Request(url)
|
|
48
|
+
|
|
49
|
+
if headers:
|
|
50
|
+
for key, value in headers.items():
|
|
51
|
+
req.add_header(key, value)
|
|
52
|
+
|
|
53
|
+
context = None
|
|
54
|
+
if not verify_ssl:
|
|
55
|
+
context = ssl.create_default_context()
|
|
56
|
+
context.check_hostname = False
|
|
57
|
+
context.verify_mode = ssl.CERT_NONE
|
|
58
|
+
|
|
59
|
+
with urllib.request.urlopen(req, timeout=timeout, context=context) as response:
|
|
60
|
+
status_code = response.getcode()
|
|
61
|
+
content = response.read().decode('utf-8', errors='replace')
|
|
62
|
+
return (status_code, content)
|
|
63
|
+
except urllib.error.HTTPError as e:
|
|
64
|
+
return (e.code, e.read().decode('utf-8', errors='replace'))
|
|
65
|
+
except urllib.error.URLError as e:
|
|
66
|
+
return (0, str(e.reason))
|
|
67
|
+
except socket.timeout:
|
|
68
|
+
return (0, "请求超时")
|
|
69
|
+
except Exception as e:
|
|
70
|
+
return (0, str(e))
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def post(url: str, data: Dict[str, str] = None, headers: Dict[str, str] = None,
|
|
74
|
+
timeout: int = 30, verify_ssl: bool = True, content_type: str = 'application/x-www-form-urlencoded') -> Tuple[int, str]:
|
|
75
|
+
"""发送 HTTP POST 请求
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
url: 请求地址
|
|
79
|
+
data: 请求数据字典
|
|
80
|
+
headers: 请求头字典
|
|
81
|
+
timeout: 超时时间(秒),默认为 30
|
|
82
|
+
verify_ssl: 是否验证 SSL 证书,默认为 True
|
|
83
|
+
content_type: 内容类型,默认为 'application/x-www-form-urlencoded'
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
Tuple[int, str]: (状态码, 响应内容)
|
|
87
|
+
"""
|
|
88
|
+
if not url or not isinstance(url, str):
|
|
89
|
+
return (0, "")
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
req = urllib.request.Request(url, method='POST')
|
|
93
|
+
|
|
94
|
+
if headers:
|
|
95
|
+
for key, value in headers.items():
|
|
96
|
+
req.add_header(key, value)
|
|
97
|
+
|
|
98
|
+
req.add_header('Content-Type', content_type)
|
|
99
|
+
|
|
100
|
+
if data:
|
|
101
|
+
if content_type == 'application/json':
|
|
102
|
+
import json
|
|
103
|
+
data_bytes = json.dumps(data).encode('utf-8')
|
|
104
|
+
else:
|
|
105
|
+
data_bytes = urllib.parse.urlencode(data).encode('utf-8')
|
|
106
|
+
req.data = data_bytes
|
|
107
|
+
|
|
108
|
+
context = None
|
|
109
|
+
if not verify_ssl:
|
|
110
|
+
context = ssl.create_default_context()
|
|
111
|
+
context.check_hostname = False
|
|
112
|
+
context.verify_mode = ssl.CERT_NONE
|
|
113
|
+
|
|
114
|
+
with urllib.request.urlopen(req, timeout=timeout, context=context) as response:
|
|
115
|
+
status_code = response.getcode()
|
|
116
|
+
content = response.read().decode('utf-8', errors='replace')
|
|
117
|
+
return (status_code, content)
|
|
118
|
+
except urllib.error.HTTPError as e:
|
|
119
|
+
return (e.code, e.read().decode('utf-8', errors='replace'))
|
|
120
|
+
except urllib.error.URLError as e:
|
|
121
|
+
return (0, str(e.reason))
|
|
122
|
+
except socket.timeout:
|
|
123
|
+
return (0, "请求超时")
|
|
124
|
+
except Exception as e:
|
|
125
|
+
return (0, str(e))
|
|
126
|
+
|
|
127
|
+
@staticmethod
|
|
128
|
+
def download_file(url: str, save_path: str, timeout: int = 60, verify_ssl: bool = True) -> bool:
|
|
129
|
+
"""下载文件
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
url: 文件下载地址
|
|
133
|
+
save_path: 保存路径
|
|
134
|
+
timeout: 超时时间(秒),默认为 60
|
|
135
|
+
verify_ssl: 是否验证 SSL 证书,默认为 True
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
bool: 是否下载成功
|
|
139
|
+
"""
|
|
140
|
+
if not url or not save_path:
|
|
141
|
+
return False
|
|
142
|
+
|
|
143
|
+
try:
|
|
144
|
+
context = None
|
|
145
|
+
if not verify_ssl:
|
|
146
|
+
context = ssl.create_default_context()
|
|
147
|
+
context.check_hostname = False
|
|
148
|
+
context.verify_mode = ssl.CERT_NONE
|
|
149
|
+
|
|
150
|
+
with urllib.request.urlopen(url, timeout=timeout, context=context) as response:
|
|
151
|
+
|
|
152
|
+
FileUtils.ensure_dir_exists(FileUtils.get_parent_dir(save_path))
|
|
153
|
+
with open(save_path, 'wb') as f:
|
|
154
|
+
f.write(response.read())
|
|
155
|
+
return True
|
|
156
|
+
except Exception as e:
|
|
157
|
+
return False
|
|
158
|
+
|
|
159
|
+
@staticmethod
|
|
160
|
+
def url_encode(data: Dict[str, Any]) -> str:
|
|
161
|
+
"""URL 编码
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
data: 要编码的数据字典
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
str: 编码后的字符串
|
|
168
|
+
"""
|
|
169
|
+
if not data or not isinstance(data, dict):
|
|
170
|
+
return ""
|
|
171
|
+
try:
|
|
172
|
+
return urllib.parse.urlencode(data)
|
|
173
|
+
except Exception as e:
|
|
174
|
+
return ""
|
|
175
|
+
|
|
176
|
+
@staticmethod
|
|
177
|
+
def url_decode(query_string: str) -> Dict[str, str]:
|
|
178
|
+
"""URL 解码
|
|
179
|
+
|
|
180
|
+
Args:
|
|
181
|
+
query_string: 编码的查询字符串
|
|
182
|
+
|
|
183
|
+
Returns:
|
|
184
|
+
Dict[str, str]: 解码后的字典
|
|
185
|
+
"""
|
|
186
|
+
if not query_string or not isinstance(query_string, str):
|
|
187
|
+
return {}
|
|
188
|
+
try:
|
|
189
|
+
return dict(urllib.parse.parse_qsl(query_string))
|
|
190
|
+
except Exception as e:
|
|
191
|
+
return {}
|
|
192
|
+
|
|
193
|
+
@staticmethod
|
|
194
|
+
def parse_url(url: str) -> urllib.parse.ParseResult:
|
|
195
|
+
"""解析 URL
|
|
196
|
+
|
|
197
|
+
Args:
|
|
198
|
+
url: 网址
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
urllib.parse.ParseResult: 解析结果对象
|
|
202
|
+
"""
|
|
203
|
+
if not url or not isinstance(url, str):
|
|
204
|
+
return urllib.parse.ParseResult("", "", "", "", "", "")
|
|
205
|
+
try:
|
|
206
|
+
return urllib.parse.urlparse(url)
|
|
207
|
+
except Exception as e:
|
|
208
|
+
return urllib.parse.ParseResult("", "", "", "", "", "")
|
|
209
|
+
|
|
210
|
+
@staticmethod
|
|
211
|
+
def get_url_host(url: str) -> str:
|
|
212
|
+
"""获取 URL 的主机名
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
url: 网址
|
|
216
|
+
|
|
217
|
+
Returns:
|
|
218
|
+
str: 主机名
|
|
219
|
+
"""
|
|
220
|
+
parsed = HttpUtils.parse_url(url)
|
|
221
|
+
return parsed.hostname or ""
|
|
222
|
+
|
|
223
|
+
@staticmethod
|
|
224
|
+
def get_url_path(url: str) -> str:
|
|
225
|
+
"""获取 URL 的路径
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
url: 网址
|
|
229
|
+
|
|
230
|
+
Returns:
|
|
231
|
+
str: 路径
|
|
232
|
+
"""
|
|
233
|
+
parsed = HttpUtils.parse_url(url)
|
|
234
|
+
return parsed.path or ""
|
|
235
|
+
|
|
236
|
+
@staticmethod
|
|
237
|
+
def get_url_params(url: str) -> Dict[str, str]:
|
|
238
|
+
"""获取 URL 的查询参数
|
|
239
|
+
|
|
240
|
+
Args:
|
|
241
|
+
url: 网址
|
|
242
|
+
|
|
243
|
+
Returns:
|
|
244
|
+
Dict[str, str]: 查询参数字典
|
|
245
|
+
"""
|
|
246
|
+
parsed = HttpUtils.parse_url(url)
|
|
247
|
+
return HttpUtils.url_decode(parsed.query)
|
|
248
|
+
|
|
249
|
+
@staticmethod
|
|
250
|
+
def is_url_valid(url: str) -> bool:
|
|
251
|
+
"""验证 URL 是否有效
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
url: 网址
|
|
255
|
+
|
|
256
|
+
Returns:
|
|
257
|
+
bool: 是否有效
|
|
258
|
+
"""
|
|
259
|
+
if not url or not isinstance(url, str):
|
|
260
|
+
return False
|
|
261
|
+
parsed = HttpUtils.parse_url(url)
|
|
262
|
+
return parsed.scheme in ('http', 'https') and parsed.hostname is not None
|
|
263
|
+
|
|
264
|
+
@staticmethod
|
|
265
|
+
def is_network_available(host: str = 'www.google.com', port: int = 80, timeout: int = 5) -> bool:
|
|
266
|
+
"""检测网络是否可用
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
host: 检测主机,默认为 'www.google.com'
|
|
270
|
+
port: 端口号,默认为 80
|
|
271
|
+
timeout: 超时时间(秒),默认为 5
|
|
272
|
+
|
|
273
|
+
Returns:
|
|
274
|
+
bool: 是否可用
|
|
275
|
+
"""
|
|
276
|
+
try:
|
|
277
|
+
socket.setdefaulttimeout(timeout)
|
|
278
|
+
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
|
|
279
|
+
return True
|
|
280
|
+
except Exception as e:
|
|
281
|
+
return False
|
|
282
|
+
|
|
283
|
+
@staticmethod
|
|
284
|
+
def get_local_ip() -> str:
|
|
285
|
+
"""获取本地 IP 地址
|
|
286
|
+
|
|
287
|
+
Returns:
|
|
288
|
+
str: 本地 IP 地址,失败返回空字符串
|
|
289
|
+
"""
|
|
290
|
+
try:
|
|
291
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
292
|
+
sock.connect(('8.8.8.8', 80))
|
|
293
|
+
ip = sock.getsockname()[0]
|
|
294
|
+
sock.close()
|
|
295
|
+
return ip
|
|
296
|
+
except Exception as e:
|
|
297
|
+
return ""
|
|
298
|
+
|
|
299
|
+
@staticmethod
|
|
300
|
+
def get_hostname() -> str:
|
|
301
|
+
"""获取主机名
|
|
302
|
+
|
|
303
|
+
Returns:
|
|
304
|
+
str: 主机名
|
|
305
|
+
"""
|
|
306
|
+
try:
|
|
307
|
+
return socket.gethostname()
|
|
308
|
+
except Exception as e:
|
|
309
|
+
return ""
|
|
310
|
+
|
|
311
|
+
@staticmethod
|
|
312
|
+
def resolve_hostname(hostname: str) -> str:
|
|
313
|
+
"""解析主机名到 IP 地址
|
|
314
|
+
|
|
315
|
+
Args:
|
|
316
|
+
hostname: 主机名
|
|
317
|
+
|
|
318
|
+
Returns:
|
|
319
|
+
str: IP 地址,失败返回空字符串
|
|
320
|
+
"""
|
|
321
|
+
if not hostname or not isinstance(hostname, str):
|
|
322
|
+
return ""
|
|
323
|
+
try:
|
|
324
|
+
return socket.gethostbyname(hostname)
|
|
325
|
+
except Exception as e:
|
|
326
|
+
return ""
|
|
327
|
+
|
|
328
|
+
@staticmethod
|
|
329
|
+
def check_port(host: str = 'localhost', port: int = 8080, timeout: int = 3) -> bool:
|
|
330
|
+
"""检查端口是否开放
|
|
331
|
+
|
|
332
|
+
Args:
|
|
333
|
+
host: 主机名,默认为 'localhost'
|
|
334
|
+
port: 端口号,默认为 8080
|
|
335
|
+
timeout: 超时时间(秒),默认为 3
|
|
336
|
+
|
|
337
|
+
Returns:
|
|
338
|
+
bool: 是否开放
|
|
339
|
+
"""
|
|
340
|
+
try:
|
|
341
|
+
socket.setdefaulttimeout(timeout)
|
|
342
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
343
|
+
result = sock.connect_ex((host, port))
|
|
344
|
+
sock.close()
|
|
345
|
+
return result == 0
|
|
346
|
+
except Exception as e:
|
|
347
|
+
return False
|
|
348
|
+
|
|
349
|
+
@staticmethod
|
|
350
|
+
def is_ipv4(ip: str) -> bool:
|
|
351
|
+
"""判断是否为 IPv4 地址
|
|
352
|
+
|
|
353
|
+
Args:
|
|
354
|
+
ip: IP 地址字符串
|
|
355
|
+
|
|
356
|
+
Returns:
|
|
357
|
+
bool: 是否为 IPv4 地址
|
|
358
|
+
"""
|
|
359
|
+
if not ip or not isinstance(ip, str):
|
|
360
|
+
return False
|
|
361
|
+
try:
|
|
362
|
+
socket.inet_pton(socket.AF_INET, ip)
|
|
363
|
+
return True
|
|
364
|
+
except (socket.error, ValueError):
|
|
365
|
+
return False
|
|
366
|
+
|
|
367
|
+
@staticmethod
|
|
368
|
+
def is_ipv6(ip: str) -> bool:
|
|
369
|
+
"""判断是否为 IPv6 地址
|
|
370
|
+
|
|
371
|
+
Args:
|
|
372
|
+
ip: IP 地址字符串
|
|
373
|
+
|
|
374
|
+
Returns:
|
|
375
|
+
bool: 是否为 IPv6 地址
|
|
376
|
+
"""
|
|
377
|
+
if not ip or not isinstance(ip, str):
|
|
378
|
+
return False
|
|
379
|
+
try:
|
|
380
|
+
socket.inet_pton(socket.AF_INET6, ip)
|
|
381
|
+
return True
|
|
382
|
+
except (socket.error, ValueError):
|
|
383
|
+
return False
|
|
384
|
+
|
|
385
|
+
@staticmethod
|
|
386
|
+
def http_get(url: str, params: Dict[str, str] = None, headers: Dict[str, str] = None,
|
|
387
|
+
timeout: int = 30, verify_ssl: bool = True) -> Dict[str, Any]:
|
|
388
|
+
"""发送 HTTP GET 请求(返回字典格式结果)
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
url: 请求地址
|
|
392
|
+
params: 请求参数字典
|
|
393
|
+
headers: 请求头字典
|
|
394
|
+
timeout: 超时时间(秒),默认为 30
|
|
395
|
+
verify_ssl: 是否验证 SSL 证书,默认为 True
|
|
396
|
+
|
|
397
|
+
Returns:
|
|
398
|
+
Dict[str, Any]: 包含 status_code 和 content 的字典
|
|
399
|
+
"""
|
|
400
|
+
status_code, content = HttpUtils.get(url, params, headers, timeout, verify_ssl)
|
|
401
|
+
return {'status_code': status_code, 'content': content}
|
|
402
|
+
|
|
403
|
+
@staticmethod
|
|
404
|
+
def http_post(url: str, data: Dict[str, str] = None, headers: Dict[str, str] = None,
|
|
405
|
+
timeout: int = 30, verify_ssl: bool = True, content_type: str = 'application/x-www-form-urlencoded') -> Dict[str, Any]:
|
|
406
|
+
"""发送 HTTP POST 请求(返回字典格式结果)
|
|
407
|
+
|
|
408
|
+
Args:
|
|
409
|
+
url: 请求地址
|
|
410
|
+
data: 请求数据字典
|
|
411
|
+
headers: 请求头字典
|
|
412
|
+
timeout: 超时时间(秒),默认为 30
|
|
413
|
+
verify_ssl: 是否验证 SSL 证书,默认为 True
|
|
414
|
+
content_type: 内容类型
|
|
415
|
+
|
|
416
|
+
Returns:
|
|
417
|
+
Dict[str, Any]: 包含 status_code 和 content 的字典
|
|
418
|
+
"""
|
|
419
|
+
status_code, content = HttpUtils.post(url, data, headers, timeout, verify_ssl, content_type)
|
|
420
|
+
return {'status_code': status_code, 'content': content}
|
|
421
|
+
|
|
422
|
+
@staticmethod
|
|
423
|
+
def build_url(base_url: str, path: str = '', params: Dict[str, Any] = None) -> str:
|
|
424
|
+
"""构建 URL
|
|
425
|
+
|
|
426
|
+
Args:
|
|
427
|
+
base_url: 基础 URL
|
|
428
|
+
path: 路径
|
|
429
|
+
params: 查询参数字典
|
|
430
|
+
|
|
431
|
+
Returns:
|
|
432
|
+
str: 完整的 URL
|
|
433
|
+
"""
|
|
434
|
+
try:
|
|
435
|
+
url = base_url
|
|
436
|
+
if path:
|
|
437
|
+
if not base_url.endswith('/') and not path.startswith('/'):
|
|
438
|
+
url += '/' + path
|
|
439
|
+
else:
|
|
440
|
+
url += path
|
|
441
|
+
if params:
|
|
442
|
+
query_string = urllib.parse.urlencode(params)
|
|
443
|
+
if '?' in url:
|
|
444
|
+
url += '&' + query_string
|
|
445
|
+
else:
|
|
446
|
+
url += '?' + query_string
|
|
447
|
+
return url
|
|
448
|
+
except Exception as e:
|
|
449
|
+
return base_url
|
|
450
|
+
|
|
451
|
+
@staticmethod
|
|
452
|
+
def get_local_ips() -> list:
|
|
453
|
+
"""获取本机所有 IP 地址
|
|
454
|
+
|
|
455
|
+
Returns:
|
|
456
|
+
list: IP 地址列表
|
|
457
|
+
"""
|
|
458
|
+
ips = []
|
|
459
|
+
try:
|
|
460
|
+
hostname = socket.gethostname()
|
|
461
|
+
addresses = socket.getaddrinfo(hostname, None, socket.AF_INET)
|
|
462
|
+
for addr in addresses:
|
|
463
|
+
ip = addr[4][0]
|
|
464
|
+
if ip not in ips:
|
|
465
|
+
ips.append(ip)
|
|
466
|
+
except Exception as e:
|
|
467
|
+
pass
|
|
468
|
+
return ips
|