关于用 Python 获得一台 Linux 服务器的 Connections 数

2014-06-14 14:49:09 +08:00
 Livid
之前试过用 psutil,但是貌似不太有效率,因为需要查询每个 Process 的 Connections 数然后累加。

有什么更高效的方式么?/proc 下有系统的总 Connections 数么?
4218 次点击
所在节点    Python
9 条回复
hepochen
2014-06-14 14:58:40 +08:00
ss 这个系统命令是最高效的
dreampuf
2014-06-14 15:05:12 +08:00
https://github.com/giampaolo/psutil/blob/master/psutil/_pslinux.py#L362

自己改写逻辑?按时间倒排增量?
psutil 只是解析 /proc/net/* 中的内容,以枚举器的形式返回。/proc 在内存中,IO问题相对来说没有disk那么严重
Livid
2014-06-14 15:13:13 +08:00
@dreampuf 在非常忙的服务器上,这个过程的耗时太长。
dreampuf
2014-06-14 15:27:50 +08:00
@Livid ss也是读取的/proc/net/中的统计信息。如果你不需要pid相关信息的话,我觉得psutil更易用更容易定制
liwei
2014-06-14 16:29:19 +08:00
@dreampuf 非也,netstat就是因为读取/proc目录的文件导致在大量链接的情况下速度不理想,ss正是为了改善这一状况而产生的,使用的是内核的 ip_diag和tcp_diag功能,走的是netlink接口。
liwei
2014-06-14 16:31:17 +08:00
est
2014-06-14 16:32:56 +08:00
@dreampuf 不是。ss是直接netlink度内核。netstat读/proc
dreampuf
2014-06-15 01:49:57 +08:00
@liwei
@est

多谢告知。感谢已送。
ss.c 里的统计信息似乎还是读取/proc/* 。是我下了错误的版本吗?
$ uname -a
Linux dt 3.11.0-12-generic #19-Ubuntu SMP Wed Oct 9 16:20:46 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

$ sudo apt-get source iproute

~/iproute2-3.12.0/misc$ grep -A13 'static FILE \*generic_proc_open' ss.c
static FILE *generic_proc_open(const char *env, const char *name)
{
const char *p = getenv(env);
char store[128];

if (!p) {
p = getenv("PROC_ROOT") ? : "/proc";
snprintf(store, sizeof(store)-1, "%s/%s", p, name);
p = store;
}

return fopen(p, "r");
}
dreampuf
2014-06-15 02:04:29 +08:00
再看了眼,proc只有在netlink失败后才会作为备选方案解析。

static int tcp_show(struct filter *f, int socktype)
{
FILE *fp = NULL;
char *buf = NULL;
int bufsize = 64*1024;

dg_proto = TCP_PROTO;

if (getenv("TCPDIAG_FILE"))
return tcp_show_netlink_file(f);

if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
&& inet_show_netlink(f, NULL, socktype) == 0)
return 0;

/* Sigh... We have to parse /proc/net/tcp... */

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/117476

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX