Issue
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.
- Type
crontab -e
to edit the scheduled tasks of userroot
- Add
0 * * * * /etc/cron.d/netfix >> net_crontab 2&>1
to the file, which means execute the shell scriptnetfix
every hour, and put the stdout into a text file - 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:
- I execute
which netplan
inbash shell
with userroot
, and it works. - The
netfix
shell did not check the network after reconnecting it, so20230124 05:00:01 network ok
should be challenged. - 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~
Answered By - Yuankuan Zhang Answer Checked By - Cary Denson (WPSolving Admin)