温馨提示×

怎样脚本调用linux strings

小樊
46
2026-10-20 01:13:06
栏目: 智能运维

在 Linux 里,strings 本质就是一个命令行工具,所谓“脚本调用”通常是指在 Shell 脚本 / Python 脚本 / 其他程序 里执行 strings 命令并处理输出。下面按常见场景给你示例。


一、Shell 脚本中调用 strings

1️⃣ 基本用法

#!/bin/bash

strings /bin/ls

2️⃣ 输出到文件

strings /bin/ls > strings.txt

3️⃣ 指定最小字符串长度

strings -n 8 /bin/ls

4️⃣ 处理多个文件

for f in /bin/*; do
    echo "=== $f ==="
    strings "$f"
done

二、Python 脚本中调用 strings

方法 1:使用 subprocess

import subprocess

result = subprocess.run(
    ["strings", "-n", "6", "/bin/ls"],
    capture_output=True,
    text=True
)

print(result.stdout)

方法 2:逐行处理

import subprocess

with subprocess.Popen(
    ["strings", "/bin/ls"],
    stdout=subprocess.PIPE,
    text=True
) as proc:
    for line in proc.stdout:
        if "version" in line:
            print(line.strip())

三、在 Makefile 中调用

strings:
	strings -n 8 mybinary > strings.txt

四、在 C 程序中调用(system / popen)

#include <stdio.h>
#include <stdlib.h>

int main() {
    system("strings /bin/ls > out.txt");
    return 0;
}

或用 popen 读取输出:

FILE *fp = popen("strings /bin/ls", "r");
char buf[256];
while (fgets(buf, sizeof(buf), fp)) {
    printf("%s", buf);
}
pclose(fp);

五、常见实用参数

参数 作用
-n N 只显示长度 ≥ N 的字符串
-a 扫描整个文件(默认已如此)
-e 指定字符编码(如 s, l, b)
-t x 显示偏移(十六进制)

示例:

strings -n 10 -t x binary_file

六、典型用途

  • 分析二进制中的可见字符串
  • 提取程序中的路径、URL、版本号
  • 逆向 / CTF / 固件分析
  • 快速排查二进制内容

如果你有具体场景(比如:

  • 在 Python 里批量分析
  • 在 CI 脚本里用
  • 只提取某些关键字
  • 对比两个 binary 的 strings)

可以直接说,我可以给你更针对性的脚本。

0 踩