Search code examples
ubuntuservercronnetplan

My scheduled task in ubuntu shown some errors but it worked


I am new here. So, if there is something absurd in my expression, don't hesitate to let me know. Thanks very much.

Background

The network of my server(Ubuntu 20.04.1 LTS) got wrong sometimes. And I needed to reconnect it using the command below:

cp bak/bad.yaml 00-installer-config.yaml
netplan apply
cp bak/good.yaml 00-installer-config.yaml
netplan apply
cd ~/cmd
./nat.sh

That was not a good experience, because at least a person should be here in the lab. So I decide to build a scheduled task using cron. Below is what I have done.

  1. Type crontab -e to edit the scheduled tasks of user root
  2. Add 0 * * * * /etc/cron.d/netfix >> net_crontab 2&>1 to the file, which means execute the shell script netfix every hour, and put the stdout into a text file
  3. The script netfix is below:
#!/bin/bash

function network()
{
    local timeout=1
    local target=www.baidu.com
    local ret_code=`curl -I -s --connect-timeout ${timeout} ${target} -w %{http_code} | tail -n1`

    if [ "x$ret_code" = "x200" ]; then
        return 1
    else
        return 0
    fi

    return 0
}

now=$(date +"%Y%m%d %H:%M:%S")
network
if [ $? -eq 0 ];then
        echo "$now network error"
        cd /etc/netplan
        cp bak/bad.yaml 00-installer-config.yaml
        netplan apply
        cp bak/good.yaml 00-installer-config.yaml
        netplan apply
        cd /home/qiuzw/cmd
        ./nat.sh
        # exit -1
fi

echo "$now network ok"
exit 0

Problem

I didn't meet the previous problem during the whole Spring Festival! But I check the result file net_crontab, and there are some errors.

...
20230124 04:00:01 network ok
20230124 05:00:01 network error
/etc/cron.d/netfix: line 33: netplan: command not found
/etc/cron.d/netfix: line 35: netplan: command not found
./nat.sh: 3: iptables: not found
./nat.sh: 5: iptables: not found
./nat.sh: 6: iptables: not found
./nat.sh: 7: iptables: not found
20230124 05:00:01 network ok
20230124 06:00:01 network ok
...

Question

So my question is: Why is the network in 20230124 06:00 is ok, if the command netplan is not found?

Some information:

  1. I execute which netplan in bash shell with user root, and it works.
  2. The netfix shell did not check the network after reconnecting it, so 20230124 05:00:01 network ok should be challenged.
  3. Which location shall I put the script netfix in? Is /etc/cron.d acceptable?

Thanks again for giving me some advice.


Solution

  • Finally, the answer is 'using absolute path of commands'.

    For example, use /usr/sbin/netplan apply instead of netplan apply.

    Interesting~