简体   繁体   中英

How do I add an infinite nc (netcat-openbsd) job as a crontab -e command to run @restart?

The following works fine from a default ubuntu terminal:

    nc -P ANONYMOUS 10.0.1.2 7700 >> ~/some.log

I use that command to make one computer to connect to a remote server and sit there listening to information being sent to it by the remote server. The length of time is infinite, and lines get added to the log every few seconds.

But as soon as I try to add this command as a cron job with crontab -e , it DOES NOT work!

(I really want cron to launch the command @restart )

I have isolated the problem somewhat:

It appears that the connection is initially getting established, but then is closing immediately.

When I add "-q 60" to the command:

 nc -q 60 -P ANONYMOUS 10.0.1.2 7700 >> ~/some.log

The cronjob does in fact open the connection, and listens, for 60 seconds as specified (yay!), but when I change that to "-q -1" , to specify an infinite time period, the connection closes immediately (boo!).

The man page explicitly states for -q : " -q after EOF on stdin , wait the specified number of seconds and then quit. If seconds is negative, wait forever."

I believe this problem may have to do with the default behavior of the -q option, as I have found a related bug report/fix here:

 https://bugs.launchpad.net/ubuntu/+source/netcat-openbsd/+bug/544935 

in which the issue may have been addressed for terminals with a prompt, but perhaps not for terminals without a prompt?

It might also be an independent issue, having just to do with passing in a negative value to the nc -q option.

Another possibility is that it may even be related to the cron shell, however, other tests I have tried, seem to indicate that cron (sh)ell is working as expected.

Note, I tried using various combinations of shells and environments when defining the crontab command, ( env -i sh; and bash; and sourcing various .bashrc files. Setting $PS1 to ensure line 5 in the default .bashrc file does not return before the file is sourced completely.).

I'm running: Ubuntu version 12.04.3 LTS
Release: 12.04 netcat-openbsd: 1.89-4ubuntu1

So my questions are these: Why does adding the "-q -1" not working in this case? and:

What other alternatives do I have to accomplish this task?

try adding the '-d' option to netcat:

nc -d -q -1 -P ANONYMOUS 10.0.1.2 7700 >> ~/some.log

It worked for me. As per the man page the -d flag is "Do not attempt to read from stdin."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM