0

I try listen new file lines and resend it in snmptraps:

#!/usr/bin/env python
import subprocess

sreader = "tail -f /root/zsv/log"
ssreader = subprocess.Popen(sreader,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)

strap = 'snmptrap -c iptvinfo -v 2c 192.168.10.10:163 "" 1.3.3.3.3.3.3.3 1.2.2.2.2.2.2 s '
subprocess.Popen([strap + ssreader.communicate()[0]],shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)

And I'm not getting anything.. This is my first program, please help fix it

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • Could you provide a series of shell commands that *works for you in a terminal* that you would like to translate to Python? – jfs Mar 28 '14 at 12:50
  • of course.. tail -f "file-name" The -f option causes to not stop when end of file is reached, but rather to wait for additional data to be appended to the input. And example command to send snmp trap: snmptrap -c iptvinfo -v 2c 10.144.216.91:163 "" 1.3.3.3.3.3.3.3 1.2.2.2.2.2.2 s same_text_from_tail – user3472604 Mar 28 '14 at 12:57
  • please, [edit] your question instead of posting in a comment (it enables formatting and more visible for other users) – jfs Mar 28 '14 at 13:07
  • Does `tail -f /root/zsv/log | snmptrap -c iptvinfo -v 2c 10.144.216.91:163 "" 1.3.3.3.3.3.3.3 1.2.2.2.2.2.2 s -` work? – jfs Mar 28 '14 at 13:08
  • No, I tried. it would be great – user3472604 Mar 31 '14 at 05:44
  • what does `snmptrap` accept as the argument a filename or a string to send? btw, you haven't provided a series of shell commands that work: I see no connection between `tail -f file-name` and `snmptrap ... same_text_from_tail` What is `same_text_from_tail`? – jfs Mar 31 '14 at 11:37
  • I want get new lines in file and forward it in snmp trap. I tried read new strings in file with `tail -f ` and tried sent to snmp trap with `snmptrap -c iptvinfo -v 2c 10.144.216.91:163 "" 1.3.3.3.3.3.3.3 1.2.2.2.2.2.2 s ` – user3472604 Apr 01 '14 at 05:42
  • does it work if you execute the commands manually in the shell? – jfs Apr 01 '14 at 11:51

1 Answers1

0
import shlex
from subprocess import Popen, PIPE, check_call

snmptrap = shlex.split('snmptrap -c iptvinfo -v 2c 192.168.10.10:163 "" '
                       '1.3.3.3.3.3.3.3 1.2.2.2.2.2.2 s')
tail = Popen(["tail", "-f", filename], stdout=PIPE, bufsize=1)
for line in iter(tail.stdout.readline, b''):
    check_call(snmptrap + [line]) # send line
tail.stdout.close()
rc = tail.wait()

Note: shell=False by default, stderr is not redirected.

You could change the code to send all available lines at once, or send only once a minute.

Depending on your needs, you could choose appropriate for your case tail -f implementation in Python. See How can I tail a log file in Python? and Get last n lines of a file with Python, similar to tail.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670