-1

抱歉这么久,下面是我机器上相关的“env”变量

HOSTNAME=localhost.localdomain
SHELL=/bin/bash
TERM=xterm-256color
HISTSIZE=1000
SUDO_USER=subhasish
SUDO_UID=500
USERNAME=root
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
MAIL=/var/spool/mail/subhasish
PWD=/backup
LANG=en_US.UTF-8
SHLVL=1
SUDO_COMMAND=/bin/su
HOME=/root
LOGNAME=root
LESSOPEN=|/usr/bin/lesspipe.sh %s
SUDO_GID=500
G_BROKEN_FILENAMES=1
_=/bin/env

我的 shell 脚本只是登录到路由器并获取信息,

#!/bin/sh 
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
export DISPLAY=:0.0

host=**********
port=23
login=*********
passwd=*******
passwd2=*******
cmd="term len 0"
cmd2="sh clock"
cmd3="sh ip accounting"

(echo open ${host} ${port}
sleep 1
echo ${login}
sleep 1
echo ${passwd}
sleep 1
echo en
sleep 1
echo ${passwd2}
sleep 1
echo ${cmd} 
sleep 1
echo ${cmd2}
sleep 1 
echo ${cmd3}
sleep 5
echo exit) | telnet >> file.txt

sed '/telnet/,/term len 0/d' file.txt >> file2.txt
mv file2.txt file.txt

这可以很好地独立使用,但是使用 crontab,它拒绝工作。

crontab -l
SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
*/2 * * * * /bin/sh /backup/telnet.sh

如果你这样做了,tail -f /var/log/cron,它显示 cron 正在运行,但没有产生 file.txt。手动运行时我得到 file.txt 。

Feb 11 23:26:01 localhost CROND[29053]: (root) CMD (/bin/sh /backup/telnet.sh)
Feb 11 23:28:01 localhost CROND[29074]: (root) CMD (/bin/sh /backup/telnet.sh)

为了测试 crontab 是否真正工作,我从 crontab 运行了 2 行以下,它工作正常。

#* * * * * touch /backup/testing.txt
#* * * * *  /backup/test.sh

where test.sh is,
cat test.sh
#!/bin/sh
touch /backup/testing.txt

我认为来自 crontab 的回显可能是不可能的,即 * * * * * /bin/echo "Hello, world!"不起作用,但是* * * * * /bin/echo "Hello, world!" >> /backup/test.out会给出输出 test.out。但是这里的 echo 在脚本里面,应该不是问题。

4

1 回答 1

2

Take in account that lines like these:

sed '/telnet/,/term len 0/d' file.txt >> file2.txt
mv file2.txt file.txt

Are not very good for a cronjob: you need to put absolute paths, because otherwise everything will be saved in /.

What I suggest is to change it for this:

sed '/telnet/,/term len 0/d' /dir/to/your/file/file.txt >> /dir/to/your/file/file2.txt
mv /dir/to/your/file/file2.txt /dir/to/your/file/file.txt
于 2013-02-12T12:53:07.343 回答