今天介紹的這個小工具叫做strings,它實現功能很簡單,就是找出文件內容中的可打印字符串。所謂可打印字符串的涵義是,它的組成部分都是可打印字符,並且以null或者newline結尾。
對於普通文本文件來說,strings沒有任何意義,因為文本文件中的任何內容實際都是可打印的字符串。strings最常用的場合就是列出動態庫或者可執行程序等二進制文件中出現的字符串,結合grep即可實現查找。
strings的使用方法很簡單,strings [文件]即可,它會默認輸出長度大於4的字符串,每行一個。
此外它還有幾個參數。
-n number 僅輸出長度大於number的字符串
-t d/o/x 除了字符串之外,還額外輸出字符串的位置(十進制/八進制/十六進制)
下面我用C語言寫一個很簡單的hello world程序:
#include int main() { printf("hello world\n"); return 0; }
編譯過程中,hello world作為一個靜態字符串會保存在全局數據區。使用strings查看,即可看到”hello world”這個字符串:
[leconte@localhost test]$ strings test /lib/ld-linux.so.2 __gmon_start__ libc.so.6 _IO_stdin_used puts __libc_start_main GLIBC_2.0 PTRh [^_] world world
除了hello world之外還有許多字符串,這些都是二進制文件test里包含的,它們都是編譯,鏈接期間從glibc等動態庫或其他地方引入的。
更為過分的是,我們可以用sed等編輯器對字符串進行修改:
[leconte@localhost test]$ gcc -g -o test a.c [leconte@localhost test]$ ./test hello world [leconte@localhost test]$ sed -i 's/hello world/linuxers.cn/g' test [leconte@localhost test]$ ./test linuxers.cn
可見我將hello world改成了linuxers.cn,執行test后輸出已經變成了linuxers.cn,我們成功修改了可執行程序。但是這種修改必須很小心,通常字符串的長度在修改前后必須嚴格相等,否則很有可能產生段錯誤,因為畢竟我們修改的是數據而非代碼邏輯。假如我像下面這樣修改,執行后就會段錯誤:
[leconte@localhost test]$ sed -i 's/linuxers.cn/linux/g' test [leconte@localhost test]$ ./test 段錯誤