python - Bash 命令仅在第一次执行

标签 python bash shell nmap

我有以下 nmap 命令:

nmap -n -p 25 10.11.1.1-254 --open | grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\.[0-9]\{1,3\}' | cut -d" " -f5

这会生成一个 IP 地址列表,我试图将其传递给以下 python 脚本:

#!/usr/bin/python


# Python tool to check a range of hosts for SMTP servers that respond to VRFY requests

import socket
import sys
from socket import error as socket_error

# Read the username file
with open(sys.argv[1]) as f:
    usernames = f.read().splitlines()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_ip = sys.argv[2]

print("****************************")
print("Results for: " + host_ip)
try: 
    c = s.connect((host_ip,25))
    banner=s.recv(1024)

    #Send VRFY requests and print result
    for user in usernames:
        s.send('VRFY ' + user + '\r\n')
        result = s.recv(1024)
        print(result)

    print("****************************")
    #Close Socket
    s.close()

#If error is thrown
except socket_error as serr:
    print("\nNo SMTP verify for " +host_ip)
    print("****************************")

我尝试使用以下命令执行此操作,但它仅在找到的第一个 IP 上运行脚本:

./smtp_verify.py users.txt $(nmap -n -p 25 10.11.1.1-254 --open | grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\.[0-9]\{1,3\}' | cut -d" " -f5)

我也尝试过这样做:

for $ip in (nmap -n -p 25 10.11.1.1-254 --open | grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\.[0-9]\{1,3\}' | cut -d" " -f5); do ./smtp_verify.py users.txt $ip done

但是我收到一个语法错误,这表明我不能以这种方式传递管道?

bash: syntax error near unexpected token `('

最佳答案

不自觉地使用for循环来解析命令输出,参见DontReadLinesWithFor ,而是使用 Process-Subtitution带有 while 循环的语法

#!/bin/bash

while IFS= read -r line; do
    ./smtp_verify.py users.txt "$line"
done< <(nmap -n -p 25 10.11.1.1-254 --open | grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\.[0-9]\{1,3\}' | cut -d" " -f5)

对于您可能看到的错误,您没有正确使用命令替换 $(..) 语法来运行管道命令,命令应该具有被包围在 () 周围,前面有一个 $ 。比如,

#!/bin/bash

for ip in $(nmap -n -p 25 10.11.1.1-254 --open | grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\.[0-9]\{1,3\}' | cut -d" " -f5); do 
    ./smtp_verify.py users.txt "$ip" 
done

并记住始终用双引号 shell 变量以避免 Word Splitting由 shell 完成。

关于python - Bash 命令仅在第一次执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870053/

相关文章:

python - 使用 Foreman 进行 Flask 日志记录

linux - 当使用 ffmpeg 将脚本传输到 bash 时,第一个字符消失

python - 获取Python中bash命令的所有输出

Linux 备份所有带有时间戳的已知扩展名的文件

linux - 使用 -c 和 awk 的管道字符串调用 bash 命令

python - dplyr R 排列 pandas 中的等效函数

python - KafkaRecord 不能转换为 [B

Python Excel 日期/时间读入问题

ruby - 无法将 Ruby block cat 到文件

Bash 脚本在特定范围内剪切