大网数据广告活动
服务器运维问答

Sending Message to server over socket on startup using Upstart

· 52CE 我爱测

Problem I need to send a message to a a server via a TCP socket during computer startup. We are using Ubuntu 14.04 and therefore, by default, must use Upstart as the system initialization. (We also have other computers running Ub…

问题原文

原帖链接 · rabidhamper7 · CC BY-SA 3.0

Problem

I need to send a message to a a server via a TCP socket during computer startup. We are using Ubuntu 14.04 and therefore, by default, must use Upstart as the system initialization. (We also have other computers running Ubuntu 16.04 that can use systemd, so I'm trying to keep the shell scripts separate from the system initialization file)

Current Solution

Currently I'm using two files for the clients: an upstart .conf file and a shell script file.

Upstart file

The upstart file (we will call it foo.conf) has the following contents:


#!upstart
description "Send Message on Startup"

start on (local-filesystems
        and net-device-up
        and runlevel [2345])

exec /opt/foo/foo.sh

Shell File

The shell file (we will call it foo.sh) has the following contents


#!/bin/bash

echo "Sending update message..."
echo "Message" | nc server-hostname 9999
echo "Completed sending update message."

Symptoms

When I reboot the computer that has these files, I get the following in the log file:


Sending update message...
Completed sending update message.

However, the server never receives the message.

The Question

Currently, this solution is not working. I'm looking for suggestions on either how to get this solution to work or other suggestions to accomplish the same task.

UPDATE: systemd file

Here are the details of the systemd service unit file that I have deployed on Ubuntu 16.04 box. This one works on every reboot.


[Unit]
Description=Send Message on Startup
After=network-online.target

[Service]
Type=oneshot
ExecStart=/opt/foo/foo.sh

[Install]
WantedBy=multi-user.target

已采纳解答

原帖链接 · hookenz · CC BY-SA 3.0

Try this:

#!upstart
description "Send Message on Startup"

start on (local-filesystems
        and net-device-up IFACE!=lo
        and runlevel [2345])

Here's another option which should solve it. Basically wait till it responds to ping.

#!/bin/bash

server_hostname='server_hostname'
ping -c 2 $server_hostname
while [ $? -ne 0 ]
do
  echo 'Waiting for server...'
  sleep 2
  ping -c 2 $server_hostname
done

echo "Sending update message..."
echo "Message" | nc server-hostname 9999
echo "Completed sending update message."

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-05-02)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。